· 6 years ago · Oct 22, 2019, 10:04 AM
1<?php
2/*
3Plugin name: Autoshay Api
4Description: Autoshay Api
5Author: Autoshay Api
6Version: 1.0
7*/
8ini_set('display_errors', 1);
9ini_set('display_startup_errors', 1);
10error_reporting(E_ALL);
11
12include_once('autoload_services.php');
13class AutoshayApi extends WP_REST_Controller {
14
15 const DB_ERR_CON_MSG = 'Error database connection';
16
17 protected $db_name_second;
18 protected $is_connected_to_db;
19
20 public function initialize(){
21 $options = $this->get_options();
22 $this->db_name_second = $options['db_name'];
23 $this->is_connected_to_db = $this->test_db_connection($this->db_name_second);
24
25 $this->init_api();
26 $this->init_plugin();
27
28 if(!empty($_GET['fullName']) && !empty($_GET['email']) && !empty($_GET['phone'])){
29 // A hack to use database AutoShay
30 // print_r($this->orderService->wpdb->get_results("show tables"));
31
32 //printf("<pre>%s</pre>", print_r($this, true));
33 try {
34 if(!isset($_COOKIE["Leads"])){
35
36
37
38 $data = array(
39 'first_name' => NULL,
40 'last_name' => NULL,
41 'email' => NULL,
42 'phone' => NULL,
43 'fullName' => NULL
44 );
45if(!isset($_GET['fullName'])){
46 try {
47 $data = json_decode($_COOKIE['clientData']);
48 $data['fullName'] = ($data['first_name'] != NULL || $data['last_name']) ? sprintf("%s %s", $data['first_name'], $data['last_name']): NULL;
49
50 } catch (Exception $e) {
51
52 }
53}else{
54 $data['fullName'] = $_GET['fullName'];
55 $data['email'] = $_GET['email'];
56 $data['phone'] = $_GET['phone'];
57
58
59 $cityFrom = false;
60
61 if(!empty($_GET['cityFrom'])){
62 $sql = "SELECT Country as countryId, Points_of_interest as cityId FROM InterestPoints WHERE ExtCity LIKE '{$_GET['cityFrom']}%'";
63 $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);
64 $cityFrom = (isset($data));
65 if(isset($data) && !empty($data['countryId'])) $_GET['Origincountry'] = $data['countryId'];
66 if(isset($data) && !empty($data['cityId'])) $_GET['OriginCity'] = $data['cityId'];
67 }
68
69 if(!empty($_GET['countryFrom']) && !$cityFrom){
70 $sql = "SELECT STATECODE as countryId FROM states WHERE ExtStateName = UPPER('{$_GET['countryFrom']}')";
71
72 $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);
73 if(isset($data) && !empty($data['countryId'])) $_GET['OriginCity'] = intval($data['countryId']);
74 if(isset($data) && !empty($data['countryId'])) $hasQuery = true;
75
76
77 }
78
79 $cityTo = false;
80 if(isset($_GET['cityTo']) && !empty($_GET['cityTo'])){
81 $data = false;
82 $sql = "SELECT Country as countryId, Points_of_interest as cityId FROM InterestPoints WHERE ExtCity LIKE '{$_GET['cityTo']}%'";
83
84 $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);;
85
86 $cityTo = (isset($data));
87 // var_dump($data, $cityTo);
88 if(isset($data) && !empty($data['countryId'])) $_GET['DescCountry'] = intval($data['countryId']);
89
90
91 if(isset($data) && !empty($data['cityId'])) $_GET['DescCity'] = intval($data['cityId']);
92 }
93
94 if(!empty($_GET['countryTo']) && !$cityTo){
95 $sql = "SELECT STATECODE as countryId FROM states WHERE ExtStateName = UPPER('{$_GET['countryTo']}')";
96
97
98 $data = $this->clientService->wpdb->get_row($sql, ARRAY_A);
99 if(isset($data) && !empty($data['countryId'])) $_GET['DescCountry'] = intval($data['countryId']);
100 }
101
102
103
104 if(isset($_GET['age']) && !empty($_GET['age'])){
105 $data = $this->clientService->wpdb->get_row("SELECT PId FROM DriversRange dr WHERE {$_GET['age']} BETWEEN dr.minVal AND dr.MaxVal", ARRAY_A);
106 if(isset($data['PId'])) $_GET['DriversAgeCode'] = $data['PId'];
107 }
108
109
110
111}
112
113
114
115
116
117
118
119 $lead = ($this->orderService->wpdb->query($this->orderService->wpdb->prepare("INSERT INTO `Leads` (
120 `LeadDate`,
121 `LeadName`,
122 `LeadPhone`,
123 `LeadCountryId`,
124 `LeadCityId`,
125 `ReturnCountryId`,
126 `ReturnCityId`,
127 `FROMDATE`,
128 `TODATE`,
129 `FROMTime`,
130 `TOTime`,
131 `DriversAgeId`,
132 `OrderStatus`, `LeadEmail`) VALUES(NOW(), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s)",
133 (!empty($_GET['fullName']))?$_GET['fullName']:NULL,
134 (!empty($_GET['phone']))?$_GET['phone']:NULL,
135 (!empty($_GET['Origincountry']))?$_GET['Origincountry']:NULL,
136 (!empty($_GET['OriginCity']))?$_GET['OriginCity']:NULL,
137 (!empty($_GET['DescCountry']))?$_GET['DescCountry']:NULL,
138 (!empty($_GET['DescCity']))?$_GET['DescCity']:NULL,
139 (!empty($_GET['DateFrom']))?$_GET['DateFrom']:NULL,
140 (!empty($_GET['DateTo']))?$_GET['DateTo']:NULL,
141 (!empty($_GET['TimeFromHour']) && !empty($_GET['TimeFromMinut']))?$_GET['TimeFromHour'].$_GET['TimeFromMinut']:NULL,
142 (!empty($_GET['TimeToHour']) && !empty($_GET['TimeToMinut']))?$_GET['TimeToHour'].$_GET['TimeToMinut']:NULL,
143 (!empty($_GET['DriversAgeCode']))? $_GET['DriversAgeCode']:NULL,
144 (!empty($_GET['OrderStatus']))? $_GET['OrderStatus']:0,
145 (!empty($_GET['email']))?$_GET['email']:NULL
146 )));
147 setcookie("Leads", $this->orderService->wpdb->insert_id, time()+3600);
148 }
149//var_dump($this->orderService->wpdb->insert_id);
150//exit();
151
152}catch (Exception $e) {
153 // echo 'Caught exception: ', $e->getMessage(), "\n";
154}
155 }
156 }
157
158 protected function test_db_connection($database = ''){
159 $link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, $database);
160 if( !$link ){
161 return false;
162 }
163
164 mysqli_close( $link );
165 return true;
166 }
167
168 protected function init_plugin(){
169 add_action('admin_menu', array($this, 'admin_menu'));
170 }
171
172 function admin_menu() {
173 add_menu_page('Autoshay settings', 'Autoshay settings', 'administrator', 'autoshay' , array($this, 'admin_options'));
174
175 $start = true;
176 $table_first = "";
177
178 if($all_tables = $this->tableService->getAllTables()){
179 $i = 0;
180 $num = 0;
181 $tables = array();
182
183 foreach($all_tables as $table)
184 foreach($table as $table_name)
185 $tables[mb_strtolower($table_name)] = $table_name;
186
187 ksort($tables);
188 foreach($tables as $table_name){
189 if($i%13 == 0){
190 $start = true;
191 $num++;
192 }
193
194 if($start){
195 add_menu_page('Autoshay tables '.$num, 'Autoshay tables '.$num, 'read', 'autoshay-table-'.$table_name);
196 $start = false;
197 $table_first = $table_name;
198 }
199
200 add_submenu_page( 'autoshay-table-'.$table_first, $table_name, $table_name, 'read', 'autoshay-table-'.$table_name, array($this, 'autoshay_table_options'));
201 $i++;
202 }
203 }
204 }
205
206 function autoshay_table_options(){
207 $page = isset($_GET["page"]) ? $_GET["page"] : "";
208 $paged = isset($_GET["paged"]) ? intval($_GET["paged"]) : 1;
209
210 $table_name = str_replace("autoshay-table-", "", $page);
211 $url = ($_SERVER["DOCUMENT_URI"]);
212
213 if($structure = $this->tableService->getStructureTable($table_name)){
214 $columns = array();
215
216 foreach($structure as $row)
217 $columns[] = $row->Field;
218
219 $orderby = isset($_GET["orderby"]) ? $_GET["orderby"] : $columns[0];
220 $order = isset($_GET["order"]) ? $_GET["order"] : "asc";
221
222 $all = $this->tableService->getRowCountTable($table_name);
223 $count_row = $all[0]->count;
224
225 $limit = 50;
226 $count_page = ceil($count_row/$limit);
227
228 $first = $paged > 2;
229 $prev = $paged > 1;
230 $next = $paged < $count_page;
231 $last = $paged < $count_page - 1;
232
233 $first_url = $url."?page=autoshay-table-".$table_name."&paged=1&orderby=".$orderby."&order=".$order;
234 $prev_url = $url."?page=autoshay-table-".$table_name."&paged=".($paged - 1)."&orderby=".$orderby."&order=".$order;
235 $next_url = $url."?page=autoshay-table-".$table_name."&paged=".($paged + 1)."&orderby=".$orderby."&order=".$order;
236 $last_url = $url."?page=autoshay-table-".$table_name."&paged=".$count_page."&orderby=".$orderby."&order=".$order;
237
238 $rows = $this->tableService->read($table_name, $paged, $limit, $orderby, $order);
239 require_once(__DIR__ . '/inc/autoshay_table.php');
240 } else {
241 echo '<div class="updated fade"><p>Table '.$table_name.' not found!</p></div>';
242 }
243
244 }
245
246 function admin_options(){
247
248 $action_url = $_SERVER['REQUEST_URI'];
249 $options = $this->get_options();
250 if ( isset($_POST['submitted']) ) {
251 check_admin_referer('autoshay_options');
252
253 $options['db_name'] = trim($_POST['db_name']);
254 update_option('autoshay_options', $options);
255
256 if($this->test_db_connection($options['db_name'])){
257 echo '<div class="updated fade"><p>Settings saved.</p></div>';
258 } else {
259 $options['db_name'] = '';
260 echo '<div class="updated fade"><p>Can not make connection to database.</p></div>';
261 }
262
263 }
264 $nonce = wp_create_nonce('autoshay_options');
265
266 $db_name = $options['db_name'];
267
268 require_once(__DIR__ . '/inc/admin_form.php');
269 }
270
271 function get_options(){
272
273 $options = array(
274 'db_name' => '',
275 );
276
277 $saved = get_option('autoshay_options');
278
279 if (!empty($saved)) {
280 foreach ($saved as $key => $option){
281 $options[$key] = $option;
282 }
283 }
284
285 if ($saved != $options)
286 update_option('autoshay_options', $options);
287
288 return $options;
289 }
290
291
292 protected function init_api(){
293
294 $connection = null;
295
296 if($this->test_db_connection($this->db_name_second)){
297 $connection = new wpdb(DB_USER, DB_PASSWORD, $this->db_name_second, DB_HOST);
298
299 $this->orderService = new OrderService($connection);
300 $this->carService = new CarService($connection);
301 $this->clientService = new ClientService($connection);
302 $this->tableService = new TableService($connection);
303 }
304
305 add_action( 'rest_api_init', function () {
306
307 $version = '1';
308 $namespace = 'v' . $version;
309
310 register_rest_route( $namespace, '/newOrder', array(
311 'methods' => 'POST',
312 'callback' => ($this->is_connected_to_db ? array($this, 'api_new_order') : array($this, 'error_db_connection')),
313 ) );
314
315 register_rest_route( $namespace, '/getOrders', array(
316 'methods' => 'POST',
317 'callback' => ($this->is_connected_to_db ? array($this, 'api_get_orders') : array($this, 'error_db_connection')),
318 ) );
319
320 register_rest_route( $namespace, '/newUser', array(
321 'methods' => 'POST',
322 'callback' => ($this->is_connected_to_db ? array($this, 'api_new_user') : array($this, 'error_db_connection')),
323 ) );
324
325 register_rest_route( $namespace, '/getUsers', array(
326 'methods' => 'POST',
327 'callback' => ($this->is_connected_to_db ? array($this, 'api_get_users') : array($this, 'error_db_connection')),
328 ) );
329
330 register_rest_route( $namespace, '/search', array(
331 'methods' => 'POST',
332 'callback' => ($this->is_connected_to_db ? array($this, 'api_search') : array($this, 'error_db_connection')),
333 ) );
334
335 register_rest_route( $namespace, '/readOnly/(?P<table>[A-Za-z0-9_]+)', array(
336 'methods' => 'POST',
337 'callback' => ($this->is_connected_to_db ? array($this, 'api_get_table_data') : array($this, 'error_db_connection')),
338 ) );
339
340 register_rest_route( $namespace, '/getcitiesbyid', array(
341 'methods' => 'POST',
342 'callback' => ($this->is_connected_to_db ? array($this, 'api_getcitiesbyid') : array($this, 'error_db_connection')),
343 ) );
344
345 register_rest_route( $namespace, '/auth', array(
346 'methods' => 'POST',
347 'callback' => ($this->is_connected_to_db ? array($this, 'api_auth') : array($this, 'error_db_connection')),
348 ) );
349
350 register_rest_route( $namespace, '/isBooking', array(
351 'methods' => 'POST',
352 'callback' => ($this->is_connected_to_db ? array($this, 'isBooking') : array($this, 'error_db_connection')),
353 ) );
354
355 } );
356 }
357
358 /*API call*/
359 public function error_db_connection( $request ){
360 return new WP_REST_Response( array(
361 'success' => false,
362 'message' => $this->DB_ERR_CON_MSG
363 ), 200 );
364 }
365
366 public function api_new_order( $request ) {
367
368 $client = $this->clientService->getValidatedFields($request);
369
370 if(!is_array($client)){
371 return new WP_REST_Response( array(
372 'success' => false,
373 'message' => $client
374 ), 200 );
375 }
376
377 $order = $this->orderService->getValidatedFields($request);
378 if(!is_array($order)){
379 return new WP_REST_Response( array(
380 'success' => false,
381 'message' => $order
382 ), 200 );
383 }
384
385 $client['Language'] = pll_current_language();
386
387 $equipments = $request->get_param('equipments');
388 $equipments = is_array($equipments) ? $equipments : array();
389
390 $client['id'] = $request->get_param('client_id');
391 $client['SearchId'] = $_POST['searchId'];
392
393
394
395 if( $result = $this->orderService->create($client, $order, $equipments) ) {
396
397 $email_themes = get_field('order_email_themes', 'options')[0];
398
399 $email = $client['email'];
400 if(pll_current_language() == 'he'){
401 $subject = $email_themes['herbrew'];
402 } else {
403 $subject = $email_themes['english'];
404 }
405
406 $headers = array('Content-Type: text/html; charset=UTF-8');
407
408 $email_data = $this->orderService->getOrderEmailDataByID($result['id']);
409
410 $email_data['price_after_discount'] = intval($request->get_param('price_after_discount'));
411 $email_data['PriceInsurance'] = intval($request->get_param('PriceInsurance'));
412 $email_data['Currency'] = $request->get_param('Currency');
413 $email_data['free_options'] = $this->orderService->getFreeOptionsByTariff($request->get_param('TariffCode'));
414
415 $message = $this->get_order_email_text($email_data, pll_current_language() == 'he');
416 wp_mail($email, $subject, $message, $headers);
417
418 $email = trim(get_field('email_receiver', 'options')[0]['address']);
419 wp_mail($email, $subject, $message, $headers);
420
421 return new WP_REST_Response( array(
422 'success' => true,
423 'order_id' => $result['id']
424 ), 200 );
425 }
426
427 }
428
429 protected function get_order_email_text($email_data, $is_rtl = false){
430
431 ob_start();
432 if($is_rtl){
433 require(__DIR__ . '/email/email-rtl.php');
434 } else {
435 require(__DIR__ .'/email/email.php');
436 }
437 return ob_get_clean();
438 }
439
440 protected function get_signin_email_text($email_data, $is_rtl = false){
441
442 ob_start();
443 if($is_rtl){
444 require(__DIR__ .'/email/signin-rtl.php');
445 } else {
446 require(__DIR__ . '/email/signin.php');
447 }
448 return ob_get_clean();
449 }
450
451 public function api_get_orders($request){
452 $dates = $this->orderService->getValidatedDatesRange($request);
453 if(!is_array($dates)){
454 return new WP_REST_Response( array(
455 'success' => false,
456 'message' => $dates
457 ), 200 );
458 }
459
460 $orders = $this->orderService->read(
461 $request->get_param('page'),
462 $dates['min'],
463 $dates['max']
464 );
465
466 return new WP_REST_Response( $orders, 200 );
467 }
468
469 public function api_new_user($request){
470 $client = $this->clientService->getValidatedFields($request);
471 if(!is_array($client)){
472 return new WP_REST_Response( array(
473 'success' => false,
474 'message' => $client
475 ), 200 );
476 }
477
478 $isCreated = $this->clientService->create($client);
479
480 return new WP_REST_Response( array(
481 'success' => is_numeric($isCreated)
482 ), 200 );
483 }
484
485 public function api_get_users($request){
486 $dates = $this->clientService->getValidatedDatesRange($request);
487 if(!is_array($dates)){
488 return new WP_REST_Response( array(
489 'success' => false,
490 'message' => $dates
491 ), 200 );
492 }
493
494 $clients = $this->clientService->read(
495 $request->get_param('page'),
496 $dates['min'],
497 $dates['max']
498 );
499
500 return new WP_REST_Response( $clients, 200 );
501 }
502
503 public function api_search($request){
504 $search = $this->carService->getValidatedFields($request);
505 if(!is_array($search)){
506 return new WP_REST_Response( array(
507 'success' => false,
508 'message' => $search
509 ), 200 );
510 }
511
512 $result = $this->carService->search($search, $request->get_param('initialize'), $request->get_param('filters'));
513
514
515 return new WP_REST_Response( array(
516 'success' => true,
517 'result' => $result
518 ), 200 );
519 }
520
521 public function api_get_table_data($request){
522
523 $table = $request->get_param('table');
524
525 if( !$this->tableService->isAvailable($table) ){
526 return new WP_REST_Response( array(
527 'success' => false,
528 'message' => "{$table} is not available"
529 ), 200 );
530 }
531
532 $result = $this->tableService->read($table, $request->get_param('page'));
533 return new WP_REST_Response( $result, 200 );
534 }
535
536 public function api_getcitiesbyid($request){
537 $id = $request->get_param('id');
538 $result = array();
539 if(!$id){
540 return new WP_REST_Response( array(
541 'result' => $result
542 ), 200 );
543 }
544
545 $result = $this->tableService->getcitiesbyid($id);
546 usort($result, array ('AutoshayApi', 'cities_ordering'));
547
548 return new WP_REST_Response( array(
549 'result' => $result
550 ), 200 );
551 }
552
553 public function isBooking($request){
554
555 if(!isset($_POST['searchId'])){
556 return new WP_REST_Response( array(
557 'success' => false,
558 'message' => sprintf("Missing searchId params")
559 ), 400 );
560 }
561
562 $this->clientService->wpdb->query(sprintf("UPDATE Searches SET isBooking=1 WHERE PId = %d", $_POST['searchId']));
563
564 return new WP_REST_Response( array(
565 'success' => true,
566 'message' => sprintf("search %d was updated", $_POST['searchId'])
567 ), 200 );
568 }
569
570 public function api_auth($request){
571 $client = $this->clientService->getValidatedFields($request, array('last_name'));
572 if(!is_array($client)){
573 return new WP_REST_Response( array(
574 'success' => false,
575 'message' => $client
576 ), 200 );
577 }
578
579 $client['Language'] = pll_current_language();
580
581 $client = $this->clientService->create($client);
582
583 if($client){
584
585 $email_themes = get_field('signin_email_theme', 'options')[0];
586
587 $email = trim(get_field('signin_email_receiver', 'options')[0]['address']);
588 if(pll_current_language() == 'he'){
589 $subject = $email_themes['herbrew'] .' '.$client['first_name'];
590 } else {
591 $subject = $email_themes['english'] .' '.$client['first_name'];
592 }
593 $message = $this->get_signin_email_text($client, pll_current_language() == 'he');
594
595 $headers = array('Content-Type: text/html; charset=UTF-8');
596 wp_mail($email, $subject, $message, $headers);
597
598 return new WP_REST_Response( array(
599 'data' => array('client_id' => $client['id'], 'clientData' => json_encode($client)),
600 'success' => true
601 ), 200 );
602 } else {
603 return new WP_REST_Response( array(
604 'success' => false,
605 'message' => 'Unknown error'
606 ), 200 );
607 }
608
609 }
610
611 /*Direct call*/
612 public function cities_ordering($a,$b){
613 return strnatcmp($a['Points_of_interest_desc'],$b['Points_of_interest_desc']);
614 }
615
616 public function country_ordering($a,$b){
617 return strnatcmp($a['stateName'],$b['stateName']);
618 }
619
620 public function getcitiesbyid($id){
621
622 if(!$this->is_connected_to_db){
623 trigger_error ($this->DB_ERR_CON_MSG);
624 return array();
625 }
626
627 $result = array();
628 if(empty($id)){
629 return $result;
630 }
631 $result = $this->tableService->getcitiesbyid($id);
632 usort($result, array ('AutoshayApi', 'cities_ordering'));
633 return $result;
634 }
635
636 public function getcitybyid($id){
637
638 if(!$this->is_connected_to_db){
639 trigger_error ($this->DB_ERR_CON_MSG);
640 return array();
641 }
642
643 $result = array();
644 if(empty($id)){
645 return $result;
646 }
647 $result = $this->tableService->getcitybyid($id);
648 return $result;
649 }
650
651 public function get_table_data($table){
652
653 if(!$this->is_connected_to_db){
654 trigger_error ($this->DB_ERR_CON_MSG);
655 return array();
656 }
657
658 if(!$this->is_connected_to_db){
659 return array();
660 }
661
662 if( !$this->tableService->isAvailable($table) ){
663 return array();
664 }
665
666 return $this->tableService->read($table, 'all');
667 }
668
669 public function get_states(){
670 $result = $this->tableService->read('states', 'all');
671 usort($result, array ('AutoshayApi', 'country_ordering'));
672 return $result;
673 }
674
675 public function get_client(){
676 if(isset($_COOKIE['client_id'])){
677 return $this->clientService->getClientByID($_COOKIE['client_id']);
678 } else {
679 return false;
680 }
681 }
682
683 public function get_grouped_filters(){
684 return $this->carService->getGroupedFilters();
685 }
686}
687
688function get_autoshay_api(){
689 global $autoshay_api;
690
691 if(!$autoshay_api){
692 $autoshay_api = new AutoshayApi();
693 $autoshay_api->initialize();
694 }
695
696 return $autoshay_api;
697}
698
699get_autoshay_api();