Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin name: Autoshay Api
- Description: Autoshay Api
- Author: Autoshay Api
- Version: 1.0
- */
- ini_set('display_errors', 1);
- ini_set('display_startup_errors', 1);
- error_reporting(E_ALL);
- include_once('autoload_services.php');
- class AutoshayApi extends WP_REST_Controller {
- const DB_ERR_CON_MSG = 'Error database connection';
- protected $db_name_second;
- protected $is_connected_to_db;
- public function initialize(){
- $options = $this->get_options();
- $this->db_name_second = $options['db_name'];
- $this->is_connected_to_db = $this->test_db_connection($this->db_name_second);
- $this->init_api();
- $this->init_plugin();
- if(!empty($_GET['fullName']) && !empty($_GET['email']) && !empty($_GET['phone'])){
- // A hack to use database AutoShay
- // print_r($this->orderService->wpdb->get_results("show tables"));
- //printf("<pre>%s</pre>", print_r($this, true));
- try {
- if(!isset($_COOKIE["Leads"])){
- $data = array(
- 'first_name' => NULL,
- 'last_name' => NULL,
- 'email' => NULL,
- 'phone' => NULL,
- 'fullName' => NULL
- );
- if(!isset($_GET['fullName'])){
- try {
- $data = json_decode($_COOKIE['clientData']);
- $data['fullName'] = ($data['first_name'] != NULL || $data['last_name']) ? sprintf("%s %s", $data['first_name'], $data['last_name']): NULL;
- } catch (Exception $e) {
- }
- }else{
- $data['fullName'] = $_GET['fullName'];
- $data['email'] = $_GET['email'];
- $data['phone'] = $_GET['phone'];
- $cityFrom = false;
- if(!empty($_GET['cityFrom'])){
- $sql = "SELECT Country as countryId, Points_of_interest as cityId FROM InterestPoints WHERE ExtCity LIKE '{$_GET['cityFrom']}%'";
- $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);
- $cityFrom = (isset($data));
- if(isset($data) && !empty($data['countryId'])) $_GET['Origincountry'] = $data['countryId'];
- if(isset($data) && !empty($data['cityId'])) $_GET['OriginCity'] = $data['cityId'];
- }
- if(!empty($_GET['countryFrom']) && !$cityFrom){
- $sql = "SELECT STATECODE as countryId FROM states WHERE ExtStateName = UPPER('{$_GET['countryFrom']}')";
- $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);
- if(isset($data) && !empty($data['countryId'])) $_GET['OriginCity'] = intval($data['countryId']);
- if(isset($data) && !empty($data['countryId'])) $hasQuery = true;
- }
- $cityTo = false;
- if(isset($_GET['cityTo']) && !empty($_GET['cityTo'])){
- $data = false;
- $sql = "SELECT Country as countryId, Points_of_interest as cityId FROM InterestPoints WHERE ExtCity LIKE '{$_GET['cityTo']}%'";
- $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);;
- $cityTo = (isset($data));
- // var_dump($data, $cityTo);
- if(isset($data) && !empty($data['countryId'])) $_GET['DescCountry'] = intval($data['countryId']);
- if(isset($data) && !empty($data['cityId'])) $_GET['DescCity'] = intval($data['cityId']);
- }
- if(!empty($_GET['countryTo']) && !$cityTo){
- $sql = "SELECT STATECODE as countryId FROM states WHERE ExtStateName = UPPER('{$_GET['countryTo']}')";
- $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);
- if(isset($data) && !empty($data['countryId'])) $_GET['DescCountry'] = intval($data['countryId']);
- }
- if(isset($_GET['age']) && !empty($_GET['age'])){
- $data = $this->clientService->wpdb->get_row("SELECT PId FROM DriversRange dr WHERE {$_GET['age']} BETWEEN dr.minVal AND dr.MaxVal", ARRAY_A);
- if(isset($data['PId'])) $_GET['DriversAgeCode'] = $data['PId'];
- }
- }
- $lead = ($this->orderService->wpdb->query($this->orderService->wpdb->prepare("INSERT INTO `Leads` (
- `LeadDate`,
- `LeadName`,
- `LeadPhone`,
- `LeadCountryId`,
- `LeadCityId`,
- `ReturnCountryId`,
- `ReturnCityId`,
- `FROMDATE`,
- `TODATE`,
- `FROMTime`,
- `TOTime`,
- `DriversAgeId`,
- `OrderStatus`, `LeadEmail`) VALUES(NOW(), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s)",
- (!empty($_GET['fullName']))?$_GET['fullName']:NULL,
- (!empty($_GET['phone']))?$_GET['phone']:NULL,
- (!empty($_GET['Origincountry']))?$_GET['Origincountry']:NULL,
- (!empty($_GET['OriginCity']))?$_GET['OriginCity']:NULL,
- (!empty($_GET['DescCountry']))?$_GET['DescCountry']:NULL,
- (!empty($_GET['DescCity']))?$_GET['DescCity']:NULL,
- (!empty($_GET['DateFrom']))?$_GET['DateFrom']:NULL,
- (!empty($_GET['DateTo']))?$_GET['DateTo']:NULL,
- (!empty($_GET['TimeFromHour']) && !empty($_GET['TimeFromMinut']))?$_GET['TimeFromHour'].$_GET['TimeFromMinut']:NULL,
- (!empty($_GET['TimeToHour']) && !empty($_GET['TimeToMinut']))?$_GET['TimeToHour'].$_GET['TimeToMinut']:NULL,
- (!empty($_GET['DriversAgeCode']))? $_GET['DriversAgeCode']:NULL,
- (!empty($_GET['OrderStatus']))? $_GET['OrderStatus']:0,
- (!empty($_GET['email']))?$_GET['email']:NULL
- )));
- setcookie("Leads", $this->orderService->wpdb->insert_id, time()+3600);
- }
- //var_dump($this->orderService->wpdb->insert_id);
- //exit();
- }catch (Exception $e) {
- // echo 'Caught exception: ', $e->getMessage(), "\n";
- }
- }
- }
- protected function test_db_connection($database = ''){
- $link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, $database);
- if( !$link ){
- return false;
- }
- mysqli_close( $link );
- return true;
- }
- protected function init_plugin(){
- add_action('admin_menu', array($this, 'admin_menu'));
- }
- function admin_menu() {
- add_menu_page('Autoshay settings', 'Autoshay settings', 'administrator', 'autoshay' , array($this, 'admin_options'));
- $start = true;
- $table_first = "";
- if($all_tables = $this->tableService->getAllTables()){
- $i = 0;
- $num = 0;
- $tables = array();
- foreach($all_tables as $table)
- foreach($table as $table_name)
- $tables[mb_strtolower($table_name)] = $table_name;
- ksort($tables);
- foreach($tables as $table_name){
- if($i%13 == 0){
- $start = true;
- $num++;
- }
- if($start){
- add_menu_page('Autoshay tables '.$num, 'Autoshay tables '.$num, 'read', 'autoshay-table-'.$table_name);
- $start = false;
- $table_first = $table_name;
- }
- add_submenu_page( 'autoshay-table-'.$table_first, $table_name, $table_name, 'read', 'autoshay-table-'.$table_name, array($this, 'autoshay_table_options'));
- $i++;
- }
- }
- }
- function autoshay_table_options(){
- $page = isset($_GET["page"]) ? $_GET["page"] : "";
- $paged = isset($_GET["paged"]) ? intval($_GET["paged"]) : 1;
- $table_name = str_replace("autoshay-table-", "", $page);
- $url = ($_SERVER["DOCUMENT_URI"]);
- if($structure = $this->tableService->getStructureTable($table_name)){
- $columns = array();
- foreach($structure as $row)
- $columns[] = $row->Field;
- $orderby = isset($_GET["orderby"]) ? $_GET["orderby"] : $columns[0];
- $order = isset($_GET["order"]) ? $_GET["order"] : "asc";
- $all = $this->tableService->getRowCountTable($table_name);
- $count_row = $all[0]->count;
- $limit = 50;
- $count_page = ceil($count_row/$limit);
- $first = $paged > 2;
- $prev = $paged > 1;
- $next = $paged < $count_page;
- $last = $paged < $count_page - 1;
- $first_url = $url."?page=autoshay-table-".$table_name."&paged=1&orderby=".$orderby."&order=".$order;
- $prev_url = $url."?page=autoshay-table-".$table_name."&paged=".($paged - 1)."&orderby=".$orderby."&order=".$order;
- $next_url = $url."?page=autoshay-table-".$table_name."&paged=".($paged + 1)."&orderby=".$orderby."&order=".$order;
- $last_url = $url."?page=autoshay-table-".$table_name."&paged=".$count_page."&orderby=".$orderby."&order=".$order;
- $rows = $this->tableService->read($table_name, $paged, $limit, $orderby, $order);
- require_once(__DIR__ . '/inc/autoshay_table.php');
- } else {
- echo '<div class="updated fade"><p>Table '.$table_name.' not found!</p></div>';
- }
- }
- function admin_options(){
- $action_url = $_SERVER['REQUEST_URI'];
- $options = $this->get_options();
- if ( isset($_POST['submitted']) ) {
- check_admin_referer('autoshay_options');
- $options['db_name'] = trim($_POST['db_name']);
- update_option('autoshay_options', $options);
- if($this->test_db_connection($options['db_name'])){
- echo '<div class="updated fade"><p>Settings saved.</p></div>';
- } else {
- $options['db_name'] = '';
- echo '<div class="updated fade"><p>Can not make connection to database.</p></div>';
- }
- }
- $nonce = wp_create_nonce('autoshay_options');
- $db_name = $options['db_name'];
- require_once(__DIR__ . '/inc/admin_form.php');
- }
- function get_options(){
- $options = array(
- 'db_name' => '',
- );
- $saved = get_option('autoshay_options');
- if (!empty($saved)) {
- foreach ($saved as $key => $option){
- $options[$key] = $option;
- }
- }
- if ($saved != $options)
- update_option('autoshay_options', $options);
- return $options;
- }
- protected function init_api(){
- $connection = null;
- if($this->test_db_connection($this->db_name_second)){
- $connection = new wpdb(DB_USER, DB_PASSWORD, $this->db_name_second, DB_HOST);
- $this->orderService = new OrderService($connection);
- $this->carService = new CarService($connection);
- $this->clientService = new ClientService($connection);
- $this->tableService = new TableService($connection);
- }
- add_action( 'rest_api_init', function () {
- $version = '1';
- $namespace = 'v' . $version;
- register_rest_route( $namespace, '/newOrder', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_new_order') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/getOrders', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_get_orders') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/newUser', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_new_user') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/getUsers', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_get_users') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/search', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_search') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/readOnly/(?P<table>[A-Za-z0-9_]+)', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_get_table_data') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/getcitiesbyid', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_getcitiesbyid') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/auth', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'api_auth') : array($this, 'error_db_connection')),
- ) );
- register_rest_route( $namespace, '/isBooking', array(
- 'methods' => 'POST',
- 'callback' => ($this->is_connected_to_db ? array($this, 'isBooking') : array($this, 'error_db_connection')),
- ) );
- } );
- }
- /*API call*/
- public function error_db_connection( $request ){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $this->DB_ERR_CON_MSG
- ), 200 );
- }
- public function api_new_order( $request ) {
- $client = $this->clientService->getValidatedFields($request);
- if(!is_array($client)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $client
- ), 200 );
- }
- $order = $this->orderService->getValidatedFields($request);
- if(!is_array($order)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $order
- ), 200 );
- }
- $client['Language'] = pll_current_language();
- $equipments = $request->get_param('equipments');
- $equipments = is_array($equipments) ? $equipments : array();
- $client['id'] = $request->get_param('client_id');
- $client['SearchId'] = $_POST['searchId'];
- if( $result = $this->orderService->create($client, $order, $equipments) ) {
- $email_themes = get_field('order_email_themes', 'options')[0];
- $email = $client['email'];
- if(pll_current_language() == 'he'){
- $subject = $email_themes['herbrew'];
- } else {
- $subject = $email_themes['english'];
- }
- $headers = array('Content-Type: text/html; charset=UTF-8');
- $email_data = $this->orderService->getOrderEmailDataByID($result['id']);
- $email_data['price_after_discount'] = intval($request->get_param('price_after_discount'));
- $email_data['PriceInsurance'] = intval($request->get_param('PriceInsurance'));
- $email_data['Currency'] = $request->get_param('Currency');
- $email_data['free_options'] = $this->orderService->getFreeOptionsByTariff($request->get_param('TariffCode'));
- $message = $this->get_order_email_text($email_data, pll_current_language() == 'he');
- wp_mail($email, $subject, $message, $headers);
- $email = trim(get_field('email_receiver', 'options')[0]['address']);
- wp_mail($email, $subject, $message, $headers);
- return new WP_REST_Response( array(
- 'success' => true,
- 'order_id' => $result['id']
- ), 200 );
- }
- }
- protected function get_order_email_text($email_data, $is_rtl = false){
- ob_start();
- if($is_rtl){
- require(__DIR__ . '/email/email-rtl.php');
- } else {
- require(__DIR__ .'/email/email.php');
- }
- return ob_get_clean();
- }
- protected function get_signin_email_text($email_data, $is_rtl = false){
- ob_start();
- if($is_rtl){
- require(__DIR__ .'/email/signin-rtl.php');
- } else {
- require(__DIR__ . '/email/signin.php');
- }
- return ob_get_clean();
- }
- public function api_get_orders($request){
- $dates = $this->orderService->getValidatedDatesRange($request);
- if(!is_array($dates)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $dates
- ), 200 );
- }
- $orders = $this->orderService->read(
- $request->get_param('page'),
- $dates['min'],
- $dates['max']
- );
- return new WP_REST_Response( $orders, 200 );
- }
- public function api_new_user($request){
- $client = $this->clientService->getValidatedFields($request);
- if(!is_array($client)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $client
- ), 200 );
- }
- $isCreated = $this->clientService->create($client);
- return new WP_REST_Response( array(
- 'success' => is_numeric($isCreated)
- ), 200 );
- }
- public function api_get_users($request){
- $dates = $this->clientService->getValidatedDatesRange($request);
- if(!is_array($dates)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $dates
- ), 200 );
- }
- $clients = $this->clientService->read(
- $request->get_param('page'),
- $dates['min'],
- $dates['max']
- );
- return new WP_REST_Response( $clients, 200 );
- }
- public function api_search($request){
- $search = $this->carService->getValidatedFields($request);
- if(!is_array($search)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $search
- ), 200 );
- }
- $result = $this->carService->search($search, $request->get_param('initialize'), $request->get_param('filters'));
- return new WP_REST_Response( array(
- 'success' => true,
- 'result' => $result
- ), 200 );
- }
- public function api_get_table_data($request){
- $table = $request->get_param('table');
- if( !$this->tableService->isAvailable($table) ){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => "{$table} is not available"
- ), 200 );
- }
- $result = $this->tableService->read($table, $request->get_param('page'));
- return new WP_REST_Response( $result, 200 );
- }
- public function api_getcitiesbyid($request){
- $id = $request->get_param('id');
- $result = array();
- if(!$id){
- return new WP_REST_Response( array(
- 'result' => $result
- ), 200 );
- }
- $result = $this->tableService->getcitiesbyid($id);
- usort($result, array ('AutoshayApi', 'cities_ordering'));
- return new WP_REST_Response( array(
- 'result' => $result
- ), 200 );
- }
- public function isBooking($request){
- if(!isset($_POST['searchId'])){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => sprintf("Missing searchId params")
- ), 400 );
- }
- $this->clientService->wpdb->query(sprintf("UPDATE Searches SET isBooking=1 WHERE PId = %d", $_POST['searchId']));
- return new WP_REST_Response( array(
- 'success' => true,
- 'message' => sprintf("search %d was updated", $_POST['searchId'])
- ), 200 );
- }
- public function api_auth($request){
- $client = $this->clientService->getValidatedFields($request, array('last_name'));
- if(!is_array($client)){
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => $client
- ), 200 );
- }
- $client['Language'] = pll_current_language();
- $client = $this->clientService->create($client);
- if($client){
- $email_themes = get_field('signin_email_theme', 'options')[0];
- $email = trim(get_field('signin_email_receiver', 'options')[0]['address']);
- if(pll_current_language() == 'he'){
- $subject = $email_themes['herbrew'] .' '.$client['first_name'];
- } else {
- $subject = $email_themes['english'] .' '.$client['first_name'];
- }
- $message = $this->get_signin_email_text($client, pll_current_language() == 'he');
- $headers = array('Content-Type: text/html; charset=UTF-8');
- wp_mail($email, $subject, $message, $headers);
- return new WP_REST_Response( array(
- 'data' => array('client_id' => $client['id'], 'clientData' => json_encode($client)),
- 'success' => true
- ), 200 );
- } else {
- return new WP_REST_Response( array(
- 'success' => false,
- 'message' => 'Unknown error'
- ), 200 );
- }
- }
- /*Direct call*/
- public function cities_ordering($a,$b){
- return strnatcmp($a['Points_of_interest_desc'],$b['Points_of_interest_desc']);
- }
- public function country_ordering($a,$b){
- return strnatcmp($a['stateName'],$b['stateName']);
- }
- public function getcitiesbyid($id){
- if(!$this->is_connected_to_db){
- trigger_error ($this->DB_ERR_CON_MSG);
- return array();
- }
- $result = array();
- if(empty($id)){
- return $result;
- }
- $result = $this->tableService->getcitiesbyid($id);
- usort($result, array ('AutoshayApi', 'cities_ordering'));
- return $result;
- }
- public function getcitybyid($id){
- if(!$this->is_connected_to_db){
- trigger_error ($this->DB_ERR_CON_MSG);
- return array();
- }
- $result = array();
- if(empty($id)){
- return $result;
- }
- $result = $this->tableService->getcitybyid($id);
- return $result;
- }
- public function get_table_data($table){
- if(!$this->is_connected_to_db){
- trigger_error ($this->DB_ERR_CON_MSG);
- return array();
- }
- if(!$this->is_connected_to_db){
- return array();
- }
- if( !$this->tableService->isAvailable($table) ){
- return array();
- }
- return $this->tableService->read($table, 'all');
- }
- public function get_states(){
- $result = $this->tableService->read('states', 'all');
- usort($result, array ('AutoshayApi', 'country_ordering'));
- return $result;
- }
- public function get_client(){
- if(isset($_COOKIE['client_id'])){
- return $this->clientService->getClientByID($_COOKIE['client_id']);
- } else {
- return false;
- }
- }
- public function get_grouped_filters(){
- return $this->carService->getGroupedFilters();
- }
- }
- function get_autoshay_api(){
- global $autoshay_api;
- if(!$autoshay_api){
- $autoshay_api = new AutoshayApi();
- $autoshay_api->initialize();
- }
- return $autoshay_api;
- }
- get_autoshay_api();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement