PluginProbe
Booking Package / trunk
Booking Package vtrunk
1.7.28 1.7.27 1.7.26 1.7.24 1.7.25 1.7.23 1.7.22 1.7.21 1.7.20 1.7.19 1.7.18 1.7.17 1.7.16 1.7.15 1.7.14 1.7.13 1.7.12 1.7.11 1.7.10 trunk 1.5.30 1.5.31 1.5.32 1.5.33 1.5.35 All 183 releases
booking-package / lib / Schedule.php

Schedule.php in Booking Package trunk, at lib/Schedule.php

15,624 lines 496.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH')) {
3 exit;
4 }
5
6 class booking_package_schedule {
7
8 public $prefix = null;
9
10 public $pluginName = null;
11
12 public $phpVersion = 0;
13
14 public $automaticApprove = false;
15
16 public $targetSchedules = 0;
17
18 public $bookingVerificationCode = 0;
19
20 public $userRoleName = null;
21
22 public $accommodationDetails = null;
23
24 private $isExtensionsValid = null;
25
26 private $numberFormatter = false;
27
28 private $currencies = array();
29
30 private $locale = 'en_US';
31
32 public $payWithPayPay = 0;
33
34 public $request_timeout = 30;
35
36 public function __construct($prefix, $pluginName, $currencies, $userRoleName = 'booking_package_user'){
37
38 global $wpdb;
39 $this->prefix = $prefix;
40 $this->pluginName = $pluginName;
41 $this->phpVersion = floatval(phpversion());
42 $this->accommodationDetails = null;
43 $this->currencies = $currencies;
44 $this->userRoleName = $userRoleName;
45 $this->locale = get_locale();
46 #$this->setting = new booking_package_setting($this->prefix, $this->pluginName);
47 if (class_exists('NumberFormatter') === true) {
48
49 $this->numberFormatter = true;
50
51 }
52
53 }
54
55 public function setPayWithPayPay($payWithPayPay) {
56
57 $this->payWithPayPay = $payWithPayPay;
58
59 }
60
61 public function defaultLabels($type = 'day', $subDirectory = false) {
62
63 $userLabels = array(
64
65 'Sign Up' => __('Sign Up', 'booking-package'),
66 'Sign In' => __('Sign In', 'booking-package'),
67 'Sign Out' => __('Sign Out', 'booking-package'),
68 'Hello, %s' => __('Hello, %s', 'booking-package'),
69 /** 'Create Account' => __('Create Account', 'booking-package'), **/
70 'Register' => __('Register', 'booking-package'),
71 'Edit My Profile' => __('Edit My Profile', 'booking-package'),
72 'Booking History' => __('Booking History', 'booking-package'),
73
74 );
75
76 $generalLables = array(
77 'Booking Details' => __('Booking Details', 'booking-package'),
78 'Select a Date' => __('Select a Date', 'booking-package'),
79 'Next Page' => __('Next Page', 'booking-package'),
80 'Return' => __('Return', 'booking-package'),
81 'Calendar' => __('Calendar', 'booking-package'),
82 'Status' => __('Status', 'booking-package'),
83 'Booking Date' => __('Booking Date', 'booking-package'),
84 'Extra Charges' => __('Extra Charges', 'booking-package'),
85 'Taxes' => __('Taxes', 'booking-package'),
86 'Total Amount' => __('Total Amount', 'booking-package'),
87 'Verify' => __('Verify', 'booking-package'),
88 'Book Now' => __('Book Now', 'booking-package'),
89 'Cancel Booking' => __('Cancel Booking', 'booking-package'),
90 );
91
92 $formLabels = array(
93 'Please fill in your details' => __('Please fill in your details', 'booking-package'),
94 'Please confirm your details' => __('Please confirm your details', 'booking-package'),
95 'Booking Completed' => __('Booking Completed', 'booking-package'),
96 'Select Payment Method' => __('Select Payment Method', 'booking-package'),
97 'Payment Method' => __('Payment Method', 'booking-package'),
98 'Local Payment' => __('Local Payment', 'booking-package'),
99 'Pay with Stripe' => __('Pay with Credit Card', 'booking-package'),
100 'Pay with PayPay' => sprintf(__('Pay with %s', 'booking-package'), 'PayPay'),
101 'Pay at Convenience Store (via Stripe)' => __('Pay at Convenience Store', 'booking-package'),
102 'Credit Card' => __('Credit Card', 'booking-package'),
103 'Pay with PayPal' => __('Pay with PayPal', 'booking-package'),
104 );
105
106 if ($type === 'day') {
107
108 $timeSlotLabels = array(
109 'Please select a service' => __('Please select a service', 'booking-package'),
110 'Service Details' => __('Service Details', 'booking-package'),
111 '%s Slots Left' => __('%s Slots Left', 'booking-package'),
112 'Service' => __('Service', 'booking-package'),
113 'Guests' => __('Guests', 'booking-package'),
114 'Total Number of Guests' => __('Total Number of Guests', 'booking-package'),
115 'Coupon' => __('Coupon', 'booking-package'),
116 'Apply' => __('Apply', 'booking-package'),
117 );
118
119 if ($subDirectory === true) {
120
121 return array('general_labels' => $generalLables, 'timeSlot_labels' => $timeSlotLabels, 'form_labels' => $formLabels, 'user_labels' => $userLabels);
122
123 }
124
125 return array_merge($generalLables, $timeSlotLabels, $formLabels, $userLabels);
126
127 } else {
128
129 $multiNightLabels = array(
130 'Check-in' => __('Check-in', 'booking-package'),
131 'Check-out' => __('Check-out', 'booking-package'),
132 'Total Length of Stay' => __('Total Length of Stay', 'booking-package'),
133 'Options' => __('Options', 'booking-package'),
134 'Total Number of Options' => __('Total Number of Options', 'booking-package'),
135 'Guests' => __('Guests', 'booking-package'),
136 'Total Number of Guests' => __('Total Number of Guests', 'booking-package'),
137 'Summary' => __('Summary', 'booking-package'),
138 );
139
140 if ($subDirectory === true) {
141
142 return array('general_labels' => $generalLables, 'multiNight_Labels' => $multiNightLabels, 'form_labels' => $formLabels, 'user_labels' => $userLabels);
143
144 }
145
146 return array_merge($generalLables, $multiNightLabels, $formLabels, $userLabels);
147
148 }
149
150
151 }
152
153 public function defaultLayouts($calendarAccount, $colorTheme = 'defult') {
154
155 #$colorTheme = 'sunset';
156 $general = array('font-size' => '16px', 'color' => '#3c434a', 'background-color' => '#FFF', 'border-color' => '#DDD');
157
158 $calendar = array(
159 'calendarData' => array('font-size' => '1.5em'),
160 'week_slot' => array(),
161 'day_slot' => array(),
162 'dateField' => array(),
163 'available_day:hover' => array('background-color' => '#EAEDF3'),
164 'available_day:hover .dateField' => array('font-weight' => '500'),
165 'pastDay' => array('background-color' => '#EEE'),
166 'pastDay > .dateField' => array(),
167 'closingDay' => array('background-color' => '#EEE'),
168 'closingDay > .dateField' => array(),
169 'startDateOfFullRoom' => array('background-image' => 'repeating-linear-gradient(90deg, #0f9b79 0px 50%, transparent 0% 100%)', 'background-color' => '#a81c1c'),
170 'dateOfFullRoom' => array('background-color' => '#a81c1c'),
171 'endDateOfFullRoom' => array('background-image' => 'repeating-linear-gradient(270deg, #0f9b79 0px 50%, transparent 0% 100%)', 'background-color' => '#a81c1c'),
172 'selected_day_slot' => array(),
173 );
174
175 $service = array(
176 'topPanel' => array(),
177 'selectedDate' => array(),
178 'selectable_day_slot' => array(),
179 'selectable_day_slot:hover' => array('background-color' => '#EAEDF3'),
180 'selected_day_slot' => array('background-color' => '#EAEDF3'),
181 'closed' => array('color' => '#a81c1c'),
182 'selectable_service_slot' => array(),
183 'selectable_service_slot:hover' => array('background-color' => '#EAEDF3'),
184 'selected_service_slot' => array('background-color' => '#EAEDF3'),
185 'selected_element' => array('border-left' => '5px solid #46b450', 'padding-left' => '10px'),
186 'serviceName' => array(),
187 'serviceCost' => array(),
188 'descriptionOfService' => array(),
189 'selectable_option_element' => array('padding-left' => '10px', 'margin' => '5px 0 0 10px'),
190 'selected_option_element' => array('border-left' => '5px solid #46b450', 'padding-left' => '5px'),
191 'title' => array(),
192 'row' => array(),
193 'name' => array(),
194 'value' => array(),
195
196 );
197
198 $timeSlot = array(
199 'title' => array(),
200 'selectable_time_slot' => array(),
201 'selectable_time_slot:hover' => array('background-color' => '#EAEDF3'),
202 'closed' => array('color' => '#a81c1c'),
203 'selectedTimeSlotPanel' => array('background-color' => '#EAEDF3'),
204 );
205
206 $form = array(
207 'title_in_form' => array(),
208 'row' => array('padding' => '0', 'border-width' => '0', 'display' => 'grid', 'grid-template-columns' => '1fr 1fr'),
209 'error_empty_value' => array('background-color' => '#FFD5D5'),
210 'required:after' => array('position' => 'relative', 'top' => '3px', 'color' => '#ff1c1c', 'margin-left' => '2px', 'display' => 'inline'),
211 'name' => array('background-color' => '#EAEDF3', 'text-align' => 'right', 'padding' => '1em', /**'grid-row-start' => '1', 'grid-row-end' => '3',**/ 'word-wrap' => 'break-word', 'overflow' => 'hidden'),
212 'value' => array('padding' => '1em', 'word-wrap' => 'break-word', 'overflow' => 'hidden'),
213 'description' => array('padding' => '0', 'margin-top' => '0.5em'),
214 'form_text' => array('font-size' => '1em', 'color' => '#2c3338', 'background-color' => '#fff', 'border' => '1px solid #d6d6d6', 'border-radius' => '4px', 'padding' => '0.2em 0.5em', 'line-height' => '2', 'box-sizing' => 'border-box'),
215 'form_select' => array('font-size' => '1em', 'border' => '1px solid #d6d6d6', 'border-radius' => '4px', 'padding' => '0.2em 0.5em', ),
216 'form_radio' => array(),
217 'form_checkbox' => array(),
218 'form_textarea' => array('font-size' => '1em', 'color' => '#2c3338', 'background-color' => '#fff', 'border' => '1px solid #d6d6d6', 'border-radius' => '4px', 'padding' => '0.2em 0.5em', 'line-height' => '2', 'box-sizing' => 'border-box'),
219 );
220
221 $bookingDetails = array(
222 'bookingDetailsTitle' => array(),
223 'row' => array(),
224 'name' => array(),
225 'value' => array(),
226 'clearLabel' => array('float' => 'right', 'color' => '#2626ff', 'cursor' => 'pointer', 'font-weight' => 'normal'),
227 'optionsTitle' => array('all' => 'initial'),
228 'options_row' => array(),
229 'guestsTitle' => array('all' => 'initial'),
230 'guests_row' => array(),
231 'summary' => array(),
232 'summaryTitle' => array(),
233 'summaryValue' => array(),
234 'totalLengthOfStayLabel' => array(),
235 'total_amount' => array(),
236 );
237
238 if ($calendarAccount['type'] === 'hotel') {
239
240 $calendar['pastDay > .dateField'] = array('color' => '#FFF', 'background-color' => '#a81c1c');
241 $calendar['dateField'] = array('color' => '#FFF', 'background-color' => '#0f9b79');
242 $calendar['closingDay'] = array();
243 $calendar['selected_day_slot'] = array('background-color' => '#FFF !important');
244 $calendar['selected_start_day'] = array();
245 $calendar['selected_start_day > .dateField'] = array('background-image' => 'repeating-linear-gradient(270deg, #3979CC 0px 50%, transparent 0% 100%);');
246 $calendar['selected_day_range'] = array();
247 $calendar['selected_day_range > .dateField'] = array('background-color' => '#3979CC');
248 $calendar['selected_end_day'] = array();
249 $calendar['selected_end_day > .dateField'] = array('background-image' => 'repeating-linear-gradient(90deg, #3979CC 0px 50%, transparent 0% 100%)');
250 $form['name'] = array_merge($form['name'], array('color' => '#FFF', 'background-color' => '#0f9b79') );
251
252 }
253
254 if ($colorTheme === 'warm') {
255
256 $general = array_merge($general, array('color' => '#776B5D', 'background-color' => '#F3EEEA', 'border-color' => '#B0A695') );
257 $calendar = array_merge($calendar,
258 array(
259 'week_slot' => array('color' => '#fff', 'background-color' => '#B0A695', 'font-size' => '1em', 'border-top' => '0'),
260 'day_slot' => array('border-top-width' => '0'),
261 'dateField' => array('background-color' => '#EBE3D5', 'font-size' => '1em', 'border-top' => '0'),
262 'available_day:hover' => array('background-color' => 'initial'),
263 'available_day:hover .dateField' => array('font-weight' => '600'),
264 'closingDay' => array('color' => '#fff'),
265 'closingDay > .dateField' => array('color' => '#fff', 'background-color' => '#a81c1c'),
266 )
267 );
268 $service = array_merge($service,
269 array(
270 'selectable_day_slot:hover' => array('background-color' => '#EBE3D5'),
271 'selectable_service_slot:hover' => array('background-color' => '#EBE3D5'),
272 'selected_day_slot' => array('background-color' => '#EBE3D5'),
273 'selected_service_slot' => array('background-color' => '#EBE3D5'),
274 )
275 );
276 $timeSlot = array_merge($timeSlot,
277 array(
278 'selectable_time_slot:hover' => array('background-color' => '#EBE3D5'),
279 'selectedTimeSlotPanel' => array('background-color' => '#EBE3D5'),
280 )
281 );
282
283 $form = array_merge($form,
284 array(
285 'row' => array('padding' => '0', 'border-width' => '0', 'display' => 'grid', 'grid-template-columns' => '1fr 1fr'),
286 'name' => array('background-color' => '#EBE3D5', 'text-align' => 'right', 'padding' => '1em', /**'grid-row-start' => '1', 'grid-row-end' => '3'**/ ),
287 'description' => array('padding' => '0.5em 1em 1em 1em', 'margin-top' => '-1em'),
288 )
289 );
290
291 } else if ($colorTheme === 'green') {
292
293 $general = array_merge($general, array('color' => '#40513B', 'background-color' => '#EDF1D6', 'border-color' => '#40513B') );
294 $calendar = array_merge($calendar,
295 array(
296 'week_slot' => array('color' => '#fff', 'background-color' => '#40513B', 'font-size' => '1em', 'border-top' => '0'),
297 'day_slot' => array('border-top-width' => '0'),
298 'dateField' => array('background-color' => '#9DC08B', 'font-size' => '1em', 'border-top' => '0'),
299 'available_day:hover' => array('background-color' => 'initial'),
300 'available_day:hover .dateField' => array('color' => '#FFF', 'font-weight' => '500', 'background-color' => '#609966'),
301 'closingDay' => array('color' => '#fff'),
302 'closingDay > .dateField' => array('color' => '#fff', 'background-color' => '#a81c1c'),
303 )
304 );
305 $service = array_merge($service,
306 array(
307 'selectable_day_slot:hover' => array('color' => '#FFF', 'background-color' => '#609966'),
308 'selectable_service_slot:hover' => array('color' => '#FFF', 'background-color' => '#609966'),
309 'selected_day_slot' => array('background-color' => '#9DC08B'),
310 'selected_service_slot' => array('background-color' => '#9DC08B'),
311 )
312 );
313 $timeSlot = array_merge($timeSlot,
314 array(
315 'selectable_time_slot:hover' => array('color' => '#FFF', 'background-color' => '#609966'),
316 'selectedTimeSlotPanel' => array('background-color' => '#9DC08B'),
317 )
318 );
319
320 } else if ($colorTheme === 'sea') {
321
322 $general = array_merge($general, array('color' => '#146c94', 'background-color' => '#f6f1f1', 'border-color' => '#19A7CE') );
323 $calendar = array_merge($calendar,
324 array(
325 'week_slot' => array('color' => '#FFF', 'background-color' => '#146C94', 'font-size' => '1em', 'border-top' => '0'),
326 'day_slot' => array('background-color' => '#AFD3E2', 'border-top-width' => '0'),
327 'dateField' => array('color' => '#FFF', 'background-color' => '#19A7CE', 'border-top' => '0'),
328 'available_day:hover' => array('background-color' => 'initial'),
329 'available_day:hover .dateField' => array('font-weight' => '500', 'opacity' => '0.8'),
330 'closingDay' => array('color' => '#FFF'),
331 'closingDay > .dateField' => array('color' => '#FFF', 'background-color' => '#a81c1c'),
332 )
333 );
334 $service = array_merge($service,
335 array(
336 'selectable_day_slot:hover' => array('color' => '#FFF', 'background-color' => '#19A7CE'),
337 'selectable_service_slot:hover' => array('color' => '#FFF', 'background-color' => '#19A7CE'),
338 'selected_day_slot' => array('background-color' => '#AFD3E2'),
339 'selected_service_slot' => array('background-color' => '#AFD3E2'),
340 )
341 );
342 $timeSlot = array_merge($timeSlot,
343 array(
344 'selectable_time_slot:hover' => array('color' => '#FFF', 'background-color' => '#19A7CE'),
345 'selectedTimeSlotPanel' => array('background-color' => '#AFD3E2'),
346 )
347 );
348
349 } else if ($colorTheme === 'dark') {
350
351 $general = array_merge($general, array('color' => '#27374d', 'background-color' => '#dde6ed', 'border-color' => '#27374d') );
352 $calendar = array_merge($calendar,
353 array(
354 'week_slot' => array('color' => '#FFF', 'background-color' => '#27374D', 'font-size' => '1em', 'border-top' => '0'),
355 'day_slot' => array('background-color' => '#9DB2BF', 'border-top-width' => '0'),
356 'dateField' => array('color' => '#FFF', 'background-color' => '#526D82', 'border-top' => '0'),
357 'available_day:hover' => array('background-color' => 'initial'),
358 'available_day:hover .dateField' => array('font-weight' => '500', 'opacity' => '0.8'),
359 'closingDay' => array('color' => '#FFF'),
360 'closingDay > .dateField' => array('color' => '#FFF', 'background-color' => '#a81c1c'),
361 )
362 );
363 $service = array_merge($service,
364 array(
365 'selectable_day_slot:hover' => array('color' => '#FFF', 'background-color' => '#526D82'),
366 'selectable_service_slot:hover' => array('color' => '#FFF', 'background-color' => '#526D82'),
367 'selected_day_slot' => array('color' => '#FFF', 'background-color' => '#9DB2BF'),
368 'selected_service_slot' => array('color' => '#FFF', 'background-color' => '#9DB2BF'),
369 )
370 );
371 $timeSlot = array_merge($timeSlot,
372 array(
373 'selectable_time_slot:hover' => array('color' => '#FFF', 'background-color' => '#526D82'),
374 'selectedTimeSlotPanel' => array('color' => '#FFF', 'background-color' => '#9DB2BF'),
375 )
376 );
377
378 } else if ($colorTheme === 'sunset') {
379
380 $general = array_merge($general, array('color' => '#cd104d', 'background-color' => '#FFF', 'border-color' => '#f38181') );
381 $calendar = array_merge(
382 $calendar,
383 array(
384 'week_slot' => array('border-width' => '0', 'border-bottom-width' => '1px', 'margin-bottom' => '10px'),
385 'day_slot' => array('border-width' => '0', 'border-bottom-width' => '1px', 'border-color' => '#f3818142', /** 'height' => '50px',**/ 'margin-bottom' => '1px', 'padding-bottom' => '10px'),
386 'dateField' => array(),
387 'available_day:hover' => array('background-color' => 'initial', 'z-index' => '1', 'outline' => '1px solid', 'outline-offset' => '0px', 'animation' => 'light 1s infinite'),
388 'available_day:hover .dateField' => array('font-weight' => '500'),
389 'closingDay' => array('color' => '#FFF'),
390 'closingDay > .dateField' => array('color' => '#FFF', 'background-color' => '#a81c1c'),
391 )
392 );
393 $service = array_merge($service,
394 array(
395 'selectable_day_slot' => array('border-bottom-width' => '0'),
396 'selectable_day_slot:hover' => array('color' => '#FFF', 'background-color' => '#cd104d'),
397 'selectable_service_slot' => array('border-bottom-width' => '0', 'padding-left' => '15px'),
398 'selectable_service_slot:hover' => array('border-left' => '5px solid #cd104d', 'padding-left' => '10px'),
399 'selected_day_slot' => array('color' => '#FFF', 'background-color' => '#CD104D'),
400 'selected_service_slot' => array('color' => '#FFF', 'background-color' => '#CD104D'),
401 'selected_element' => array('border-left' => '5px solid #f38181', 'padding-left' => '10px'),
402 'selected_option_element' => array('border-left' => '5px solid #f38181', 'padding-left' => '5px'),
403 'title' => array('color' => '#3c434a', 'border-top-width' => '1px'),
404 'row' => array('border-color' => '#f3818142'),
405 )
406 );
407 $timeSlot = array_merge($timeSlot,
408 array(
409 'selectable_time_slot' => array('border-bottom-width' => '0', 'padding-left' => '15px'),
410 'selectable_time_slot:hover' => array('z-index' => '1', 'border-left' => '5px solid #cd104d', 'padding-left' => '10px'),
411 'selectedTimeSlotPanel' => array('color' => '#FFF', 'background-color' => '#CD104D'),
412 'closed' => array('color' => '#a81c1c', 'text-decoration' => 'line-through'),
413 )
414 );
415 $form = array_merge($form,
416 array(
417 'row' => array('padding' => '0', 'border-width' => '0', 'display' => 'grid', 'grid-template-columns' => '1fr 1fr'),
418 'required:after' => array('position' => 'relative', 'top' => '3px', 'color' => '#fff', 'margin-left' => '2px', 'display' => 'inline'),
419 'name' => array('color' => '#FFF', 'background-color' => '#cd104d', 'text-align' => 'right', 'padding' => '1em', /**'grid-row-start' => '1', 'grid-row-end' => '3'**/ ),
420 'value' => array('color' => '#3c434a', 'padding' => '1em', 'word-wrap' => 'break-word', 'overflow' => 'auto'),
421 )
422 );
423
424 }
425
426 $layouts = array(
427 'general' => $general,
428 'service' => $service,
429 'calendar' => $calendar,
430 'timeSlot' => $timeSlot,
431 'form' => $form,
432 );
433
434 if ($calendarAccount['type'] === 'hotel') {
435
436 $layouts = array(
437 'general' => $general,
438 'calendar' => $calendar,
439 'bookingDetails' => $bookingDetails,
440 'form' => $form,
441 );
442
443 }
444
445 return $layouts;
446
447 }
448
449 public function defaultButtons($type = 'day', $subDirectory = false) {
450
451 $generalButtons = array(
452 'all' => 'initial',
453 'font-size' => '1em',
454 'font-weight' => '500',
455 'text-decoration' => 'none',
456 'text-align' => 'center',
457 'color' => '#fff',
458 'background-color' => '#10A37F',
459 'padding' => '10px 0',
460 'margin' => '0px',
461 'border' => '1px solid #0f9b79',
462 'border-radius' => '5px',
463 'cursor' => 'pointer',
464 );
465
466 $generalButtons_hover = array('background-color' => '#0f9b79');
467
468 $buttons = array(
469 'select_date_button' => array_merge($generalButtons, array('width' => '100%')),
470 'return_button' => array_merge($generalButtons, array('padding' => '10px')),
471 'previous_available_day_button' => array_merge($generalButtons, array('padding' => '10px', 'margin' => '0 0 0 10px')),
472 'next_available_day_button' => array_merge($generalButtons, array('padding' => '10px', 'margin' => '0 0 0 10px')),
473 'next_button' => array_merge($generalButtons, array('padding' => '10px')),
474 'apply_button' => array_merge($generalButtons, array('width' => '100px', 'margin' => '1em 0 0 0')),
475 'next_page_button' => array_merge($generalButtons, array('margin-bottom' => '1em', 'width' => '100%', 'box-sizing' => 'inherit')),
476 'booking_verification_button' => array_merge($generalButtons, array('width' => '100%', 'box-sizing' => 'inherit', 'padding' => '10px 0')),
477 'book_now_button' => array_merge($generalButtons, array('width' => '100%', 'box-sizing' => 'inherit')),
478 'return_form_button' => array_merge($generalButtons, array('width' => '100%', 'box-sizing' => 'inherit')),
479 'cancel_booking_button' => array_merge($generalButtons, array('padding' => '10px', 'margin' => '0 10px', 'background-color' => '#ff4b4b', 'border' => '1px solid #ff4b4b')),
480 'login_button' => array_merge($generalButtons, array('padding' => '10px')),
481 'register_button' => array_merge($generalButtons, array('padding' => '10px')),
482 'left_arrow_button' => array_merge($generalButtons, array('padding' => '10px')),
483 'right_arrow_button' => array_merge($generalButtons, array('padding' => '10px')),
484 'cancel_user_booking_button' => array_merge($generalButtons, array('padding' => '10px', 'margin' => '10px 0', 'background-color' => '#ff4b4b', 'border' => '1px solid #ff4b4b')),
485 'change_user_password_button' => array_merge($generalButtons, array('display' => 'block', 'padding' => '10px')),
486 'update_user_button' => array_merge($generalButtons, array('padding' => '10px')),
487 'delete_user_button' => array_merge($generalButtons, array('padding' => '10px', 'background-color' => '#ff4b4b', 'border' => '1px solid #ff4b4b')),
488
489 'select_date_button:hover' => $generalButtons_hover,
490 'return_button:hover' => $generalButtons_hover,
491 'previous_available_day_button:hover' => $generalButtons_hover,
492 'next_available_day_button:hover' => $generalButtons_hover,
493 'next_button:hover' => $generalButtons_hover,
494 'apply_button:hover' => $generalButtons_hover,
495 'next_page_button:hover' => $generalButtons_hover,
496 'book_now_button:hover' => $generalButtons_hover,
497 'return_form_button:hover' => $generalButtons_hover,
498 'cancel_booking_button:hover' => array(),
499 'login_button:hover' => $generalButtons_hover,
500 'register_button:hover' => $generalButtons_hover,
501 'left_arrow_button:hover' => $generalButtons_hover,
502 'right_arrow_button:hover' => $generalButtons_hover,
503 'cancel_user_booking_button:hover' => array(),
504 'change_user_password_button:hover' => $generalButtons_hover,
505 'update_user_button:hover' => $generalButtons_hover,
506 'delete_user_button:hover' => array(),
507 );
508
509 if ($type === 'hotel') {
510
511 unset($buttons['select_date_button']);
512 unset($buttons['previous_available_day_button']);
513 unset($buttons['next_available_day_button']);
514 unset($buttons['next_button']);
515 unset($buttons['apply_button']);
516
517 unset($buttons['select_date_button:hover']);
518 unset($buttons['return_button:hover']);
519 unset($buttons['previous_available_day_button:hover']);
520 unset($buttons['next_available_day_button:hover']);
521 unset($buttons['next_button:hover']);
522 unset($buttons['apply_button:hover']);
523
524 }
525
526 return $buttons;
527
528 }
529
530 public function getPhpVersion() {
531
532 $version = explode('.', phpversion());
533 $php = intval($version[0] . $version[1]);
534 return $php;
535
536 }
537
538 public function getTimestamp(){
539
540 $timestamp = array(
541 'unixTime' => date('U'),
542 'F' => __(date('F'), 'booking-package'),
543 'm' => date('m'),
544 'n' => date('n'),
545 'd' => date('d'),
546 'j' => date('j'),
547 'Y' => date('Y'),
548 'date' => date('Ymd'),
549 );
550
551 return $timestamp;
552 }
553
554 public function setAccommodationDetails($accommodationDetails){
555
556 $this->accommodationDetails = $accommodationDetails;
557
558 }
559
560 public function getAccommodationDetails(){
561
562 return $this->accommodationDetails;
563
564 }
565
566 public function get_coupons($offset, $number = null) {
567
568
569 return array();
570
571 }
572
573 public function createUser($administrator = 0, $accountKey = null) {
574
575 if (intval($administrator) === 1) {
576
577 if (is_user_logged_in() === false || ( current_user_can('edit_users') === false && current_user_can('booking_package_manager') === false && current_user_can('booking_package_editor') === false) ) {
578
579 return array(
580 'status' => 'error',
581 'error_messages' => 'Permission denied: You do not have authorization to create a user.'
582 );
583
584 }
585
586 }
587
588 if (intval($administrator) === 0) {
589
590 if (!isset($_POST['googleReCaptchaToken'])) {
591
592 $_POST['googleReCaptchaToken'] = '';
593
594 }
595 $result = $this->verifyGoogleReCaptchaToken($_POST['googleReCaptchaToken']);
596 if ($result['status'] === false) {
597
598 $this->cancelPayment();
599 $result['status'] = 'error';
600 return $result;
601
602 }
603
604 if (!isset($_POST['hCaptcha'])) {
605
606 $_POST['hCaptcha'] = '';
607
608 }
609 $result = $this->verifyHCaptcha($_POST['hCaptcha']);
610 if ($result['status'] === false) {
611
612 $this->cancelPayment();
613 $result['status'] = 'error';
614 return $result;
615
616 }
617
618 }
619
620 $isExtensionsValid = $this->getExtensionsValid();
621 if ($isExtensionsValid === false) {
622
623 $response['status'] = 'error';
624 $response['error_messages'] = __("Member related functions are not available", 'booking-package');
625 return $response;
626
627 }
628
629 global $wpdb;
630 $table_name = $wpdb->prefix."booking_package_users";
631 #$activation = intval(get_option($this->prefix."activation_user", 0));
632 $activation = 0;
633
634 if ($administrator == 0) {
635
636 $activation = 1;
637
638 } else {
639
640 $activation = 1;
641
642 }
643
644 $s_user_login = sanitize_user($_POST['user_login']);
645 $s_user_email = sanitize_email($_POST['user_email']);
646 $response = array("status" => "success", "activation" => $activation);
647 #$user_login = username_exists($s_user_login);
648 $user_pass = trim($_POST['user_pass']);
649 $userdata = array(
650 'user_login' => sanitize_user($s_user_login),
651 'user_pass' => $user_pass,
652 'user_email' => $s_user_email,
653 'role' => $this->userRoleName,
654 );
655
656 ob_start();
657 $user_id = wp_insert_user($userdata);
658 ob_get_clean();
659 $type = gettype($user_id);
660 if (is_wp_error($user_id)) {
661
662 $response['status'] = 'error';
663 $response['step'] = 1;
664 $response['error_messages'] = $user_id->get_error_message();
665
666 } else {
667
668 if ($administrator == 0) {
669
670 $this->logout();
671
672 }
673
674 $customUserFields = array('TEXT' => array(), 'SELECT' => array(), 'CHECK' => array(), 'RADIO' => array(), 'TEXTAREA' => array());
675 if (isset($_POST['customUserFields']) === true) {
676
677 $customUserFields = json_decode(sanitize_text_field( stripslashes($_POST['customUserFields']) ), true);
678
679 }
680
681 update_user_meta($user_id, 'show_admin_bar_front', 'false');
682 $hash = wp_hash(sanitize_text_field($s_user_email).sanitize_text_field($s_user_login).date('U'));
683 $response['user_id'] = $user_id;
684 $response['user_login'] = esc_html($s_user_login);
685 $response['user_email'] = esc_html($s_user_email);
686 $response['profile'] = $customUserFields;
687 $this->add_user($user_id, $s_user_login, $s_user_email, $activation, $hash);
688
689 if ($activation == 1) {
690
691 $userdata = array(
692 'user_login' => $s_user_login,
693 'user_password' => $user_pass,
694 'remember' => true
695 );
696
697 if ($administrator == 0) {
698
699 $user = wp_signon($userdata, true);
700 if (is_wp_error($user)) {
701
702 $response['status'] = 'error';
703 $response['step'] = 2;
704 $response['error_messages'] = $user->get_error_message();
705
706 }
707
708 }
709
710 } else {
711
712 $uri = $_POST['permalink'] . "?mode=activation&k=" . $hash . "&u=" . $s_user_login;
713 $subject = get_option($this->prefix."subject_email_for_member", "No title");
714 $body = get_option($this->prefix."body_email_for_member", "No message");
715 $body = str_replace('[activation_url]', $uri, $body);
716 $this->sendMail($s_user_email, $subject, $body, 'text', $accountKey);
717
718 }
719
720 do_action('booking_package_created_user', $response);
721
722 }
723
724 return $response;
725
726 }
727
728 public function setActivationUser($user_activation_key, $user_login, $activation = 0){
729
730 $user = get_user_by('login', $user_login);
731 $id = null;
732 if (isset($user->ID)) {
733
734 $id = $user->ID;
735
736 } else {
737
738 return array('status' => 'error', 'mode' => 'notFound', "message" => __("Your information could not be found.", 'booking-package'));
739
740 }
741
742 global $wpdb;
743 $table_name = $wpdb->prefix . "booking_package_users";
744 $sql = $wpdb->prepare(
745 "SELECT `status` FROM `" . $table_name . "` WHERE `key` = %d AND `user_activation_key` = %s;",
746 array(intval($id), sanitize_text_field($user_activation_key))
747 );
748 $row = $wpdb->get_row($sql, ARRAY_A);
749 if (is_null($row)) {
750
751 return array('status' => 'error', 'mode' => 'notFound', "message" => __("Your information could not be found.", 'booking-package'));
752
753 } else {
754
755 if (intval($row['status']) == 0) {
756
757 try {
758
759 $wpdb->query("START TRANSACTION");
760 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
761 $bool = $wpdb->update(
762 $table_name,
763 array(
764 'status' => 1,
765 ),
766 array('key' => intval($id)),
767 array('%d'),
768 array('%d')
769 );
770
771 $wpdb->query('COMMIT');
772 $wpdb->query('UNLOCK TABLES');
773
774 } catch (Exception $e) {
775
776 $wpdb->query('ROLLBACK');
777 $wpdb->query('UNLOCK TABLES');
778
779 }/** finally {
780
781 $wpdb->query('UNLOCK TABLES');
782
783 }**/
784
785
786 do_action('booking_package_activation_user', $id);
787 return array('status' => 'success', 'id' => $id, 'user_login' => $user_login);
788
789 } else {
790
791 return array('status' => 'error', 'mode' => 'approved', "message" => __("You have already been approved.", 'booking-package'));
792
793 }
794
795 }
796 #var_dump($row);
797
798 }
799
800
801 public function updateUser($administrator, $accountKey){
802
803 $isExtensionsValid = $this->getExtensionsValid();
804 if ($isExtensionsValid === false) {
805
806 $response['status'] = 'error';
807 $response['error_messages'] = __("Member related functions are not available", 'booking-package');
808 return $response;
809
810 }
811
812 global $wpdb;
813 $table_name = $wpdb->prefix . "booking_package_users";
814 $response = array("status" => "error");
815 $userId = 0;
816
817 if (is_user_logged_in() === false) {
818
819 $response['error_messages'] = 'Unauthorized: You must be logged in.';
820 return $response;
821
822 }
823
824 $currentUser = wp_get_current_user();
825 $user = get_user_by('login', sanitize_text_field($_POST['user_login']));
826 if ($user === false) {
827
828 return $response;
829
830 }
831
832 $userId = $user->ID;
833 $userOldEmail = $user->user_email;
834
835 if ( user_can( $userId, 'manage_options' ) && current_user_can( 'manage_options' ) === false ) {
836
837 $response['error_messages'] = 'Permission denied: You cannot edit an administrator account.';
838 return $response;
839
840 }
841
842 if ($currentUser->ID !== $userId && current_user_can('edit_users') === false) {
843
844 $response['error_messages'] = 'Permission denied: You cannot edit this user.';
845 return $response;
846
847 }
848
849 if ($administrator === 0 && $currentUser->user_login !== sanitize_text_field($_POST['user_login'])) {
850
851 $response['error_messages'] = 'Error';
852 return $response;
853
854 }
855
856 if (intval($userId) == 0) {
857
858 $response['error_messages'] = "Not found user ID.";
859 return $response;
860
861 } else {
862
863 $customUserFields = array('TEXT' => array(), 'SELECT' => array(), 'CHECK' => array(), 'RADIO' => array(), 'TEXTAREA' => array());
864 if (isset($_POST['customUserFields']) === true) {
865
866 $customUserFields = json_decode(sanitize_text_field( stripslashes($_POST['customUserFields']) ), true);
867
868 }
869
870 $login = 0;
871 $status = 1;
872 $hash = 0;
873 $userdata = array('ID' => $userId);
874 if (isset($_POST['user_email'])) {
875
876 $userdata['user_email'] = sanitize_text_field($_POST['user_email']);
877 $hash = wp_hash(sanitize_text_field($_POST['user_email']) . sanitize_text_field($_POST['user_login']) . date('U'));
878
879 } else {
880
881 $hash = wp_hash(sanitize_text_field($userOldEmail) . sanitize_text_field($_POST['user_login']) . date('U'));
882
883 }
884
885 if (isset($_POST['user_pass'])) {
886
887 $login = 1;
888 $userdata['user_pass'] = $_POST['user_pass'];
889
890 }
891
892 $user = wp_update_user($userdata);
893 if (is_wp_error($user)) {
894
895 $response['error_messages'] = "Update error.";
896 return $response;
897
898 } else {
899
900 if ($administrator == 1) {
901
902 #$status = 1;
903 $status = intval($_POST['status']);
904
905 }
906
907 $bool = $this->update_profile($userId, $_POST['user_email'], $status, $customUserFields, $hash);
908
909 if ($login == 1) {
910
911 $userdata = array(
912 'user_login' => $_POST['user_login'],
913 'user_password' => $_POST['user_pass'],
914 'remember' => true
915 );
916
917 }
918
919 $response['status'] = 'success';
920 $response['login'] = $status;
921
922 do_action('booking_package_updated_user', array('user_id' => $userId, 'user_login' => $_POST['user_login']));
923
924 return $response;
925
926 }
927
928 }
929
930 }
931
932 public function update_profile($userId, $email, $status, $customUserFields, $hash = null){
933
934 global $wpdb;
935 $table_name = $wpdb->prefix . "booking_package_users";
936 try {
937
938 $wpdb->query("START TRANSACTION");
939 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
940 $bool = $wpdb->update(
941 $table_name,
942 array(
943 'email' => sanitize_text_field($email),
944 'status' => $status,
945 'user_activation_key' => $hash,
946 'profile' => sanitize_text_field( json_encode($customUserFields) ),
947 ),
948 array('key' => intval($userId)),
949 array('%s', '%d', '%s', '%s'),
950 array('%d')
951 );
952
953 $wpdb->query('COMMIT');
954 $wpdb->query('UNLOCK TABLES');
955
956 } catch (Exception $e) {
957
958 $wpdb->query('ROLLBACK');
959 $wpdb->query('UNLOCK TABLES');
960
961 }/** finally {
962
963 $wpdb->query('UNLOCK TABLES');
964
965 }**/
966
967 do_action('booking_package_update_profile', $userId);
968 return $bool;
969
970 }
971
972 public function update_email($userId){
973
974 global $wpdb;
975 $table_name = $wpdb->prefix . "booking_package_users";
976 $user = get_user_by('id', intval($userId));
977 try {
978
979 $wpdb->query("START TRANSACTION");
980 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
981 $bool = $wpdb->update(
982 $table_name,
983 array(
984 'email' => sanitize_text_field($user->user_email),
985 ),
986 array('key' => intval($userId)),
987 array('%s'),
988 array('%d')
989 );
990
991 $wpdb->query('COMMIT');
992 $wpdb->query('UNLOCK TABLES');
993
994 } catch (Exception $e) {
995
996 $wpdb->query('ROLLBACK');
997 $wpdb->query('UNLOCK TABLES');
998
999 }/** finally {
1000
1001 $wpdb->query('UNLOCK TABLES');
1002
1003 }**/
1004 do_action('booking_package_update_email', $userId);
1005
1006 }
1007
1008 public function get_users($authority, $offset, $number = null, $search = null){
1009
1010 global $wpdb;
1011 if ($offset < 0) {
1012
1013 $offset = 0;
1014
1015 }
1016
1017 $limit = get_option($this->prefix."read_member_limit");
1018 if ($limit === false) {
1019
1020 add_option($this->prefix."read_member_limit", intval($number));
1021
1022 } else {
1023
1024 update_option($this->prefix."read_member_limit", intval($number));
1025
1026 }
1027
1028 $role = $this->userRoleName;
1029 if ($authority == 'subscriber') {
1030
1031 $role = 'subscriber';
1032
1033 } else if ($authority == 'contributor') {
1034
1035 $role = 'contributor';
1036
1037 }
1038
1039 if (!isset($_POST['keywords'])) {
1040
1041 $args = array(
1042 'role' => $role,
1043 'orderby' => 'ID',
1044 'order' => 'ASC',
1045 'offset' => intval($offset),
1046 'number' => intval($number),
1047 'fields' => array('ID', 'user_login', 'user_email', 'user_registered'),
1048 );
1049
1050 if (!is_null($search)) {
1051 $args['search'] = $search;
1052 }
1053
1054 $users = get_users($args);
1055 $table_name = $wpdb->prefix . "booking_package_users";
1056 foreach ((array) $users as $key => $user) {
1057
1058 $sql = $wpdb->prepare(
1059 "SELECT `key`, `status`, `user_login`, `subscription_list`, `profile`, `user_registered`, `locale` FROM `".$table_name."` WHERE `email` = %s;",
1060 array(sanitize_text_field($user->user_email))
1061 );
1062
1063 $row = $wpdb->get_row($sql, ARRAY_A);
1064 if (empty($row)) {
1065
1066 $this->add_user($user->ID, $user->user_login, $user->user_email, 1, null);
1067 $user->status = '1';
1068 $user->profile = array();
1069 #continue;
1070
1071 } else {
1072
1073 $user->status = $row['status'];
1074 #$user->locale = $row['locale'];
1075 $user->locale = get_user_locale($user->ID);
1076 if (empty($row['profile']) === true) {
1077
1078 $user->profile = array();
1079
1080 } else {
1081
1082 $user->profile = json_decode($row['profile'], true);
1083
1084 }
1085
1086 }
1087
1088
1089 #$user->subscription_list = $this->get_subscription_list_of_user($user->ID);
1090 if (!empty($row['key'])) {
1091
1092 if (empty($row['user_login']) || empty($row['user_registered'])) {
1093
1094 try {
1095
1096 $wpdb->query("START TRANSACTION");
1097 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
1098 $bool = $wpdb->update(
1099 $table_name,
1100 array(
1101 'user_login' => $user->user_login,
1102 'user_registered' => $user->user_registered,
1103 ),
1104 array('key' => intval($row['key'])),
1105 array('%s', '%s'),
1106 array('%d')
1107 );
1108
1109 $wpdb->query('COMMIT');
1110 $wpdb->query('UNLOCK TABLES');
1111
1112 } catch (Exception $e) {
1113
1114 $wpdb->query('ROLLBACK');
1115 $wpdb->query('UNLOCK TABLES');
1116
1117 }/** finally {
1118
1119 $wpdb->query('UNLOCK TABLES');
1120
1121 }**/
1122
1123 }
1124
1125 }
1126
1127 }
1128
1129 } else {
1130
1131 /**
1132 $queryList = array();
1133 $valueList = array();
1134 $keywords = $_POST['keywords'];
1135 if (function_exists('mb_convert_kana')) {
1136
1137 $keywords = preg_replace('/( | )/', ' ', mb_convert_kana($keywords, 'a', 'UTF-8'));
1138
1139 }
1140
1141 $keywords = stripslashes($keywords);
1142 $keywords = explode(' ', sanitize_text_field($keywords));
1143 for ($i = 0; $i < count($keywords); $i++) {
1144
1145 array_push($queryList, "`user_login` LIKE '%%%s%%'");
1146 array_push($queryList, "`email` LIKE '%%%s%%'");
1147 array_push($queryList, "`value` LIKE '%%%s%%'");
1148 array_push($valueList, $keywords[$i]);
1149 array_push($valueList, $keywords[$i]);
1150 $word = rtrim(ltrim(json_encode($keywords[$i]), '"'), '"');
1151 $word = str_replace('\\', '%\\', $word);
1152 array_push($valueList, $word);
1153
1154 }
1155
1156 if (intval($_POST['offset']) < 0) {
1157
1158 $_POST['offset'] = 0;
1159
1160 }
1161
1162 array_push($valueList, intval($_POST['offset']));
1163 array_push($valueList, intval($_POST['number']));
1164
1165 $table_name = $wpdb->prefix."booking_package_users";
1166 $sql = $wpdb->prepare(
1167 "SELECT `key` AS `ID`, `user_login`, `email` AS `user_email`, `status`, `subscription_list`, `user_registered`, `profile`, `locale` FROM `".$table_name."` WHERE " . implode(' OR ', $queryList) . " LIMIT %d, %d;",
1168 $valueList
1169 );
1170
1171 if (isset($_POST['meta']) && intval($_POST['meta']) == 1) {
1172
1173 $sql = $wpdb->prepare(
1174 "SELECT `key` AS `ID`, `user_login`, `email` AS `user_email`, `status`, `subscription_list`, `user_registered`, `value`, `profile`, `locale` FROM `".$table_name."` WHERE " . implode(' OR ', $queryList) . " LIMIT %d, %d;",
1175 $valueList
1176 );
1177
1178 }
1179 **/
1180
1181
1182 $valueList = array();
1183 $and_conditions = array();
1184 $keywords_raw = isset($_POST['keywords']) ? wp_unslash($_POST['keywords']) : '';
1185 if (function_exists('mb_convert_kana')) {
1186 $keywords_raw = mb_convert_kana($keywords_raw, 's', 'UTF-8');
1187 }
1188
1189 $keywords_sanitized = sanitize_text_field($keywords_raw);
1190 $keywords_array = explode(' ', $keywords_sanitized);
1191
1192 $keywords_array = array_filter($keywords_array, 'strlen');
1193
1194 foreach ($keywords_array as $keyword) {
1195
1196 $escaped_keyword = $wpdb->esc_like($keyword);
1197 $like_string = '%' . $escaped_keyword . '%';
1198
1199 $word_json = trim(json_encode($keyword), '"');
1200 $word_json = str_replace('\\', '%\\', $word_json);
1201 $escaped_word_json = $wpdb->esc_like($word_json);
1202 $like_string_json = '%' . $escaped_word_json . '%';
1203
1204 $keyword_group = array(
1205 "`user_login` LIKE %s",
1206 "`email` LIKE %s",
1207 "`value` LIKE %s"
1208 );
1209
1210 $and_conditions[] = "(" . implode(' OR ', $keyword_group) . ")";
1211
1212 $valueList[] = $like_string;
1213 $valueList[] = $like_string;
1214 $valueList[] = $like_string_json;
1215
1216 }
1217
1218 $offset = isset($_POST['offset']) ? max(0, intval($_POST['offset'])) : 0;
1219 $number = isset($_POST['number']) ? max(1, intval($_POST['number'])) : 20;
1220
1221 array_push($valueList, $offset, $number);
1222
1223 $table_name = $wpdb->prefix . "booking_package_users";
1224
1225 $is_meta = isset($_POST['meta']) && intval($_POST['meta']) === 1;
1226 $select_columns = $is_meta
1227 ? "`key` AS `ID`, `user_login`, `email` AS `user_email`, `status`, `subscription_list`, `user_registered`, `value`, `profile`, `locale`"
1228 : "`key` AS `ID`, `user_login`, `email` AS `user_email`, `status`, `subscription_list`, `user_registered`, `profile`, `locale`";
1229
1230 if (!empty($and_conditions)) {
1231
1232 $where_clause = implode(' AND ', $and_conditions);
1233 $sql = $wpdb->prepare(
1234 "SELECT {$select_columns} FROM `" . $table_name . "` WHERE " . $where_clause . " LIMIT %d, %d",
1235 $valueList
1236 );
1237
1238 } else {
1239
1240 $sql = $wpdb->prepare(
1241 "SELECT {$select_columns} FROM `" . $table_name . "` LIMIT %d, %d",
1242 $offset, $number
1243 );
1244
1245 }
1246
1247
1248
1249
1250 $rows = $wpdb->get_results($sql, ARRAY_A);
1251 foreach ($rows as $key => $row) {
1252
1253 if (empty($row['profile']) === true) {
1254
1255 $row['profile'] = '{}';
1256 $rows[$key] = $row;
1257
1258 }
1259
1260 }
1261
1262 return $rows;
1263
1264 }
1265
1266 return $users;
1267
1268 }
1269
1270 public function margeProfile($bookedValues, $userProfile) {
1271
1272 $setting = new booking_package_setting($this->prefix, $this->pluginName);
1273 $userInputFields = $setting->initialUserInputFields();
1274 for ($i = 0; $i < count($userInputFields); $i++) {
1275
1276 $filed = $userInputFields[$i];
1277 if ($filed['type'] === 'SELECT') {
1278
1279 $options = $filed['options'];
1280 if ($userProfile[ $filed['type'] ] != null && $userProfile[ $filed['type'] ][ $filed['id'] ] != null) {
1281
1282 $userProfile[ $filed['type'] ][ $filed['id'] ]['value'] = $options[intval($userProfile[ $filed['type'] ][ $filed['id'] ]['value'])];
1283
1284 }
1285
1286 } else if ($filed['type'] === 'CHECK' || $filed['type'] === 'RADIO') {
1287
1288 if ($userProfile[ $filed['type'] ] != null && $userProfile[ $filed['type'] ][ $filed['id'] ] != null) {
1289
1290 $userProfile[ $filed['type'] ][ $filed['id'] ]['value'] = (function($options, $value) {
1291
1292 $values = array();
1293 for ($i = 0; $i < count($value); $i++) {
1294
1295 array_push($values, $options[ intval($value[$i]) ]);
1296
1297 }
1298
1299 return $values;
1300
1301 })($filed['options'], $userProfile[ $filed['type'] ][ $filed['id'] ]['value']);
1302
1303
1304 }
1305
1306 }
1307
1308
1309 }
1310
1311
1312
1313 foreach ($userProfile as $type => $uniques) {
1314
1315 if (array_key_exists($type, $bookedValues)) {
1316
1317 foreach ($uniques as $key => $unique) {
1318 /**
1319 if (array_key_exists($key, $userInputFields) === false) {
1320
1321 continue;
1322
1323 } else {
1324
1325 if ($userInputFields[$key]['active'] === 'false') {
1326
1327 continue;
1328
1329 }
1330
1331 }
1332 **/
1333 if (array_key_exists($key, $bookedValues[$type])) {
1334
1335 #var_dump($unique['value']);
1336 $bookedValues[$type][$key]['value'] = $unique['value'];
1337
1338 } else {
1339
1340 $bookedValues[$type][$key] = array('id' => $unique['id'], 'value' => $unique['value']);
1341
1342 }
1343
1344 }
1345
1346 } else {
1347
1348 $bookedValues[$type] = $userProfile[$type];
1349
1350 }
1351
1352 }
1353
1354 return $bookedValues;
1355
1356 }
1357
1358 public function login($userId, $statusCheck = true) {
1359
1360 $isExtensionsValid = $this->getExtensionsValid();
1361 if ($isExtensionsValid === false) {
1362
1363 return 0;
1364
1365 }
1366
1367 global $wpdb;
1368 $table_name = $wpdb->prefix."booking_package_users";
1369 $sql = $wpdb->prepare(
1370 "SELECT `value`,`status`,`profile`, `locale` FROM `" . $table_name . "` WHERE `key` = %d;",
1371 array(intval($userId))
1372 );
1373 $row = $wpdb->get_row($sql, ARRAY_A);
1374 $hasProfile = true;
1375 $response = 0;
1376 $locale = get_user_locale($userId);
1377 if (!empty($row) && intval($row['status']) == 1) {
1378
1379 if (empty($row['profile'])) {
1380
1381 $hasProfile = false;
1382 $row['profile'] = '[]';
1383
1384 }
1385
1386 $value = json_decode($row['value'], true);
1387 $profile = json_decode($row['profile'], true);
1388 if ($hasProfile === true) {
1389
1390 $value = $this->margeProfile($value, $profile);
1391
1392 }
1393 $response = array('value' => $value, 'profile' => $profile, 'locale' => $locale);
1394
1395 } else {
1396
1397 $response = 0;
1398 if ($statusCheck === false && !empty($row)) {
1399
1400 if (empty($row['profile'])) {
1401
1402 $hasProfile= false;
1403 $row['profile'] = '[]';
1404
1405 }
1406
1407 $value = json_decode($row['value'], true);
1408 $profile = json_decode($row['profile'], true);
1409 if ($hasProfile === true) {
1410
1411 $value = $this->margeProfile($value, $profile);
1412
1413 }
1414 $response = array('value' => $value, 'profile' => $profile, 'locale' => $locale);
1415
1416 }
1417
1418 }
1419
1420 if (is_int($response) === false && empty($response['value'])) {
1421
1422 $response['value'] = array();
1423
1424 }
1425
1426 if (is_int($response) === false && empty($response['profile'])) {
1427
1428 $response['profile'] = array();
1429
1430 }
1431
1432 return $response;
1433
1434 }
1435
1436 public function add_user($userId, $user_login, $email, $activation, $hash = null){
1437
1438 if (is_null($hash)) {
1439
1440 $hash = wp_hash(sanitize_text_field($email).sanitize_text_field($userId).date('U'));
1441
1442 }
1443
1444 global $wpdb;
1445 $customUserFields = array('TEXT' => array(), 'SELECT' => array(), 'CHECK' => array(), 'RADIO' => array(), 'TEXTAREA' => array());
1446 if (isset($_POST['customUserFields']) === true) {
1447
1448 $customUserFields = json_decode(sanitize_text_field( stripslashes($_POST['customUserFields']) ), true);
1449
1450 }
1451
1452 $table_name = $wpdb->prefix . "booking_package_users";
1453 $wpdb->insert(
1454 $table_name,
1455 array(
1456 'key' => $userId,
1457 'status' => intval($activation),
1458 'user_login' => sanitize_text_field($user_login),
1459 'firstname' => "",
1460 'lastname' => "",
1461 'email' => sanitize_text_field($email),
1462 'value' => json_encode(array()),
1463 'user_activation_key' => $hash,
1464 'profile' => sanitize_text_field( json_encode($customUserFields) ),
1465 ),
1466 array('%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
1467 );
1468
1469 do_action('booking_package_add_user', $userId);
1470
1471 }
1472
1473 public function find_users($userId, $activation, $create = false){
1474
1475 global $wpdb;
1476 $status = true;
1477 $table_name = $wpdb->prefix . "booking_package_users";
1478 $sql = $wpdb->prepare("SELECT `value`,`status` FROM `" . $table_name . "` WHERE `key` = %d;", array(intval($userId)));
1479 $row = $wpdb->get_row($sql, ARRAY_A);
1480 if (is_null($row)) {
1481
1482 if ($create === true) {
1483
1484 $user = get_user_by('id', $userId);
1485 #var_dump($user->user_email);
1486 $this->add_user($userId, $user->user_login, $user->user_email, $activation);
1487
1488 }
1489
1490 } else {
1491
1492 if (intval($row['status']) == 0) {
1493
1494 $status = false;
1495
1496 }
1497
1498 }
1499
1500 return $status;
1501
1502 }
1503
1504 public function get_user($userId = null, $statusCheck = true){
1505
1506 $pluginName = $this->pluginName;
1507 $reality = false;
1508 $user = null;
1509 $value = null;
1510 $setting = new booking_package_setting($this->prefix, $this->pluginName);
1511 $memberSetting = array_merge($setting->getMemberSettingValues(), array('current_member_id' => 0, 'login' => 0));
1512 $response = array("status" => 0, "message" => "", "user" => $memberSetting);
1513 if (is_null($userId)) {
1514
1515 $userId = get_current_user_id();
1516 $roleName = $this->userRoleName;
1517 if ($userId != 0) {
1518
1519 $bool = false;
1520 if (current_user_can($roleName) === true) {
1521
1522 $bool = true;
1523
1524 } else if (current_user_can("subscriber") === true && intval($memberSetting['accept_subscribers_as_users'] == 1)) {
1525
1526 $bool = true;
1527 $this->find_users($userId, 1, true);
1528
1529 } else if (current_user_can("contributor") === true && intval($memberSetting['accept_contributors_as_users'] == 1)) {
1530
1531 $bool = true;
1532 $this->find_users($userId, 1, true);
1533
1534 }/** else if (current_user_can("author") === true && intval($memberSetting['accept_authors_as_users'] == 1)) {
1535
1536 $bool = true;
1537 $this->find_users($userId, 1, true);
1538
1539 }**/
1540
1541 #$capability = current_user_can($roleName);
1542 if ($bool === true) {
1543
1544 $user = get_user_by('id', intval($userId));
1545 $value = $this->login($userId);
1546 if (!is_int($value) && is_array(array_values($value))) {
1547
1548 $reality = true;
1549 /**
1550 $memberSetting['user_login'] = $user->user_login;
1551 $memberSetting['user_email'] = $user->user_email;
1552 $memberSetting['value'] = $value;
1553 $memberSetting['current_member_id'] = intval($userId);
1554 $memberSetting['login'] = 1;
1555 $memberSetting['subscription_list'] = $this->get_subscription_list_of_user($userId);
1556
1557 $response = array("status" => 1, "user" => $memberSetting);
1558 **/
1559
1560 } else {
1561
1562 #$response = array("status" => 0, "user" => array_merge($memberSetting, array("status" => 0, "message" => __('Your email address has not been accepted.', $pluginName), "reload" => 1)));
1563 $response = array("status" => 0, "user" => array_merge($memberSetting, array("status" => 0, "message" => "", "reload" => 1)));
1564
1565 }
1566
1567 } else {
1568
1569 $response = array("status" => 0, "user" => array_merge($memberSetting, array("status" => 0, "message" => "", "reload" => 1)));
1570
1571 }
1572
1573 }
1574
1575 } else {
1576
1577 $user = get_user_by('id', intval($userId));
1578 $value = $this->login($userId, $statusCheck);
1579 if (!is_int($value) && is_array($value)) {
1580
1581 $reality = true;
1582
1583 } else {
1584
1585 $response = array("status" => 0, "user" => array_merge($memberSetting, array("status" => 0, "message" => __('Your email address has not been accepted.', $pluginName), "reload" => 1)));
1586
1587 }
1588
1589 }
1590
1591 if ($reality === true) {
1592
1593 if (isset($value['profile']['TEXT']['user_login']) === false) {
1594
1595 $value['profile']['TEXT']['user_login'] = array('id' => 'user_login', 'value' => $user->user_login);
1596
1597 }
1598
1599 if (isset($value['profile']['TEXT']['user_email']) === false) {
1600
1601 $value['profile']['TEXT']['user_email'] = array('id' => 'user_email', 'value' => $user->user_email);
1602
1603 }
1604
1605 $memberSetting['user_login'] = $user->user_login;
1606 $memberSetting['user_email'] = $user->user_email;
1607 $memberSetting['value'] = $value['value'];
1608 $memberSetting['profile'] = $value['profile'];
1609 #$memberSetting['locale'] = $value['locale'];
1610 $memberSetting['locale'] = get_user_locale($user->ID);
1611 $memberSetting['current_member_id'] = intval($userId);
1612 $memberSetting['login'] = 1;
1613 $memberSetting['subscription_list'] = $this->get_subscription_list_of_user($userId);
1614
1615 $response = array("status" => 1, "message" => "", "user" => $memberSetting);
1616
1617 }
1618
1619 return $response;
1620
1621 }
1622
1623 public function update_subscription_list_of_user($userId, $subscription_list){
1624
1625 #$subscription_list = $user['user']['subscription_list'];
1626 global $wpdb;
1627 $table_name = $wpdb->prefix . "booking_package_users";
1628 try {
1629
1630 $wpdb->query("START TRANSACTION");
1631 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
1632 $bool = $wpdb->update(
1633 $table_name,
1634 array(
1635 'subscription_list' => sanitize_text_field( json_encode($subscription_list) ),
1636 ),
1637 array('key' => intval($userId)),
1638 array('%s'),
1639 array('%d')
1640 );
1641 $wpdb->query('COMMIT');
1642 $wpdb->query('UNLOCK TABLES');
1643
1644 } catch (Exception $e) {
1645
1646 $wpdb->query('ROLLBACK');
1647 $wpdb->query('UNLOCK TABLES');
1648
1649 }/** finally {
1650
1651 $wpdb->query('UNLOCK TABLES');
1652
1653 }**/
1654
1655 return $bool;
1656
1657 }
1658
1659 public function get_subscription_list_of_user($userId){
1660
1661 global $wpdb;
1662 $table_name = $wpdb->prefix."booking_package_users";
1663 $sql = $wpdb->prepare(
1664 "SELECT `subscription_list`,`status` FROM `".$table_name."` WHERE `key` = %d;",
1665 array(intval($userId))
1666 );
1667 $row = $wpdb->get_row($sql, ARRAY_A);
1668 $subscription_list = array();
1669 if (!is_null($row['subscription_list'])) {
1670
1671 $subscription_list = json_decode($row['subscription_list'], true);
1672
1673 }
1674
1675 if (is_null($subscription_list)) {
1676
1677 $subscription_list = array();
1678
1679 } else {
1680
1681 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
1682 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
1683 $deleteKey = array();
1684 foreach ((array) $subscription_list as $key => $value) {
1685
1686 $delete = false;
1687 if ($value['period_end'] < date('U')) {
1688
1689 $value = $this->update_subscription($value);
1690 if (is_array($value)) {
1691
1692 $subscription_list[$key] = $value;
1693
1694 if ($value['canceled'] == 1) {
1695
1696 #var_dump($subscription_list[$key]);
1697 $delete = true;
1698 array_push($deleteKey, $key);
1699 unset($subscription_list[$key]);
1700
1701 }
1702
1703 $this->update_subscription_list_of_user($userId, $subscription_list);
1704 #var_dump($subscription_list[$value]);
1705
1706 } else {
1707
1708 array_push($deleteKey, $key);
1709
1710 }
1711
1712 }
1713
1714 if ($delete === false) {
1715
1716 $subscription_list[$key]['period_start_date'] = $this->dateFormat($dateFormat, $positionOfWeek, $value['period_start'], "", true, true, 'text');
1717 $subscription_list[$key]['period_end_date'] = $this->dateFormat($dateFormat, $positionOfWeek, $value['period_end'], "", true, true, 'text');
1718
1719 }
1720
1721 }
1722
1723 }
1724
1725 return $subscription_list;
1726
1727 }
1728
1729 public function update_subscription($subscription){
1730
1731 global $wpdb;
1732 $response = array("status" => 1);
1733 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
1734 if ($subscription['payType'] == 'stripe') {
1735
1736 $secret_key = get_option($this->prefix."stripe_secret_key", null);
1737 $update_subscription = $creditCard->update_subscription($secret_key, $subscription);
1738 $add_subscription = $this->prepare_subscription($subscription['payType'], $update_subscription, $subscription);
1739 return $add_subscription;
1740
1741 }
1742
1743 return false;
1744
1745 }
1746
1747 public function deleteSubscription($productKey = false, $userId = null){
1748
1749 global $wpdb;
1750 $productKey = sanitize_text_field($productKey);
1751 $response = array("status" => 1);
1752 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
1753
1754 if (is_null($userId)) {
1755
1756 $user = $this->get_user();
1757
1758 } else {
1759
1760 $user = $this->get_user($userId, false);
1761
1762 }
1763
1764 if(intval($user['status']) == 1){
1765
1766 $subscription_list = $user['user']['subscription_list'];
1767 if(isset($subscription_list[$productKey])){
1768
1769 $secret_key = get_option($this->prefix."stripe_secret_key", null);
1770 $response = $creditCard->deleteSubscription($subscription_list[$productKey], $secret_key);
1771 if($response['deleted'] === true){
1772
1773 #unset($subscription_list[$productKey]);
1774 $subscription_list[$productKey]['canceled'] = 1;
1775 $bool = $this->update_subscription_list_of_user($user['user']['current_member_id'], $subscription_list);
1776 $response['status'] = 1;
1777 $response['bool'] = $bool;
1778 #$response['user'] = $user;
1779 #$response['subscription_list'] = $subscription_list;
1780
1781 }else{
1782
1783 if($response['code'] == 404){
1784
1785 unset($subscription_list[$productKey]);
1786 $bool = $this->update_subscription_list_of_user($user['user']['current_member_id'], $subscription_list);
1787 $response['bool'] = $bool;
1788
1789 }
1790
1791 $response['status'] = 0;
1792
1793 }
1794 return $response;
1795
1796 }else{
1797
1798 $response = array("status" => 0, "reload" => 1);
1799
1800 }
1801
1802 return $subscription_list;
1803
1804 }else{
1805
1806 return $user;
1807
1808 }
1809
1810 }
1811
1812 public function user_login_for_frontend($user_login, $user_password, $remember) {
1813
1814 if (!isset($_POST['googleReCaptchaToken'])) {
1815
1816 $_POST['googleReCaptchaToken'] = '';
1817
1818 }
1819 $result = $this->verifyGoogleReCaptchaToken($_POST['googleReCaptchaToken']);
1820 if ($result['status'] === false) {
1821
1822 $this->cancelPayment();
1823 $result['status'] = 'error';
1824 return $result;
1825
1826 }
1827
1828 if (!isset($_POST['hCaptcha'])) {
1829
1830 $_POST['hCaptcha'] = '';
1831
1832 }
1833 $result = $this->verifyHCaptcha($_POST['hCaptcha']);
1834 if ($result['status'] === false) {
1835
1836 $this->cancelPayment();
1837 $result['status'] = 'error';
1838 return $result;
1839
1840 }
1841
1842 $response = array('status' => 'success');
1843 $creds = array('user_login' => $user_login, 'user_password' => $user_password);
1844 if (intval($remember) == 1) {
1845
1846 $creds['remember'] = true;
1847
1848 }
1849
1850 $user = wp_signon($creds, true);
1851 if (is_wp_error($user)) {
1852
1853 $response['status'] = 'error';
1854 $response['code'] = $user->get_error_code();
1855 $response['message'] = $user->get_error_message();
1856 #$response['user'] = $user;
1857
1858 } else {
1859
1860 $bool = 'false';
1861 $user_toolbar = intval(get_option($this->prefix . 'user_toolbar', 0));
1862 if (intval($user_toolbar) == 1) {
1863
1864 $bool = 'true';
1865
1866 }
1867 update_user_meta($user->ID, 'show_admin_bar_front', $bool);
1868 $responseUser = $this->get_user($user->ID, true);
1869 if ($responseUser['status'] == 0) {
1870
1871 wp_logout();
1872 $response['status'] = 'error';
1873 $response['code'] = 'not_approved';
1874 $response['message'] = __('Your username has not been approved.', 'booking-package');
1875
1876 }
1877
1878
1879 }
1880
1881 return $response;
1882
1883
1884 }
1885
1886 public function logout(){
1887
1888 wp_logout();
1889 return array("status" => "success");
1890
1891 }
1892
1893 public function deleteUser($administrator = 0){
1894
1895 require_once( ABSPATH.'wp-admin/includes/user.php' );
1896 $reality = false;
1897 $userId = 0;
1898
1899 if (is_user_logged_in() === false) {
1900
1901 $response['error_messages'] = 'Unauthorized: You must be logged in.';
1902 return $response;
1903
1904 }
1905
1906 $currentUser = wp_get_current_user();
1907
1908 if (intval($administrator) == 1) {
1909
1910 $user = get_user_by('login', sanitize_text_field($_POST['user_login']));
1911 if ($user !== false) {
1912
1913 $reality = true;
1914 $userId = $user->ID;
1915
1916 }
1917
1918 } else {
1919
1920 $userId = get_current_user_id();
1921 if ($userId != 0) {
1922
1923 $reality = true;
1924
1925 }
1926
1927 }
1928
1929
1930 if (user_can( $userId, 'manage_options' ) && current_user_can( 'manage_options' ) === false) {
1931
1932 $response['error_messages'] = 'Permission denied: You cannot delete an administrator account.';
1933 return $response;
1934
1935 }
1936
1937 if ($currentUser->ID !== $userId && current_user_can( 'delete_users' ) === false) {
1938
1939 $response['error_messages'] = 'Permission denied: You cannot delete this user.';
1940 return $response;
1941
1942 }
1943
1944
1945 if ($reality === true) {
1946
1947 $response = array("status" => "success", "userId" => $userId);
1948 if (wp_delete_user($userId) === true) {
1949
1950 $this->deleteForPluginUser($userId);
1951 return $response;
1952
1953 }
1954
1955 $response['status'] = "error";
1956 return $response;
1957
1958 } else {
1959
1960 $response = array("status" => "error", "userId" => $userId);
1961 return $response;
1962
1963 }
1964
1965 }
1966
1967 public function deleteForPluginUser($user_id){
1968
1969 global $wpdb;
1970 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
1971 $user = $this->get_user($user_id, false);
1972 if (isset($user['user']['subscription_list']) && is_null($user['user']['subscription_list']) === false) {
1973
1974 $items = $user['user']['subscription_list'];
1975 foreach ((array) $items as $key => $value) {
1976
1977 $secret_key = get_option($this->prefix."stripe_secret_key", null);
1978 $response = $creditCard->deleteSubscription($value, $secret_key);
1979
1980 }
1981
1982 }
1983
1984 $table_name = $wpdb->prefix."booking_package_users";
1985 $wpdb->delete($table_name, array('key' => intval($user_id)), array('%d'));
1986 do_action('booking_package_delete_user', $user_id);
1987
1988 }
1989
1990 public function setUserInformation($form){
1991
1992 global $wpdb;
1993 $table_name = $wpdb->prefix . "booking_package_users";
1994 $setting = new booking_package_setting($this->prefix, $this->pluginName);
1995 $memberSetting = array_merge($setting->getMemberSettingValues(), array('current_member_id' => 0, 'login' => 0));
1996
1997 $response = array("status" => "success");
1998 $bool = false;
1999 $userId = get_current_user_id();
2000 $roleName = $this->userRoleName;
2001 if ($userId != 0 && current_user_can($roleName) === true) {
2002
2003 $bool = true;
2004
2005 } else if ($userId != 0 && current_user_can("subscriber") === true && intval($memberSetting['accept_subscribers_as_users'] == 1)) {
2006
2007 $bool = true;
2008
2009 } else if ($userId != 0 && current_user_can("contributor") === true && intval($memberSetting['accept_contributors_as_users'] == 1)) {
2010
2011 $bool = true;
2012
2013 }/** else if ($userId != 0 && current_user_can("author") === true && intval($memberSetting['accept_authors_as_users'] == 1)) {
2014
2015 $bool = true;
2016
2017 }**/
2018
2019 if ($bool === true) {
2020
2021 $sql = $wpdb->prepare("SELECT `value`,`status` FROM `" . $table_name . "` WHERE `key` = %d;", array(intval($userId)));
2022 $row = $wpdb->get_row($sql, ARRAY_A);
2023 if (!is_null($row)) {
2024
2025 $values = json_decode($row['value'], true);
2026 for ($i = 0; $i < count($form); $i++) {
2027
2028 $type = $form[$i]['type'];
2029 $formId = $form[$i]['id'];
2030 $value = $form[$i]['value'];
2031 $array = array("id" => $formId, "value" => $value);
2032 if (isset($values[$type])) {
2033
2034 $values[$type][$formId] = $array;
2035
2036 } else {
2037
2038 $values[$type] = array($formId => $array);
2039
2040 }
2041
2042 }
2043
2044 try {
2045
2046 $wpdb->query("START TRANSACTION");
2047 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
2048 $bool = $wpdb->update(
2049 $table_name,
2050 array(
2051 'value' => sanitize_text_field( json_encode($values) ),
2052 ),
2053 array('key' => intval($userId)),
2054 array('%s'),
2055 array('%d')
2056 );
2057 $wpdb->query('COMMIT');
2058 $wpdb->query('UNLOCK TABLES');
2059
2060 } catch (Exception $e) {
2061
2062 $wpdb->query('ROLLBACK');
2063 $wpdb->query('UNLOCK TABLES');
2064
2065 }/** finally {
2066
2067 $wpdb->query('UNLOCK TABLES');
2068
2069 }**/
2070 $response['values'] = $values;
2071 return $response;
2072
2073 } else {
2074
2075 $response["status"] = "error";
2076 return $response;
2077
2078 }
2079
2080 }
2081
2082 return $response;
2083
2084 }
2085
2086 public function prepare_subscription($payType, $response_subscription, $subscription){
2087
2088 $items = array();
2089 for($i = 0; $i < count($response_subscription['items']['data']); $i++){
2090
2091 $item = $response_subscription['items']['data'][$i]['plan'];
2092 array_push($items, $item);
2093
2094 }
2095
2096 $canceled = 0;
2097 if($response_subscription['status'] == "active"){
2098
2099 $canceled = 0;
2100
2101 }else if($response_subscription['status'] == "canceled"){
2102
2103 $canceled = 1;
2104
2105 }
2106
2107 $add_subscription = array(
2108 'product' => $subscription['product'],
2109 'name' => $subscription['name'],
2110 'customer_id_for_stripe' => $response_subscription['customer'],
2111 'subscription_id_for_stripe' => $response_subscription['id'],
2112 'period_start' => $response_subscription['current_period_start'],
2113 'period_end' => $response_subscription['current_period_end'],
2114 'booking_count' => null,
2115 'payType' => sanitize_text_field($payType),
2116 'canceled' => $canceled,
2117 'items' => $items,
2118 );
2119
2120 return $add_subscription;
2121
2122 }
2123
2124 public function createCustomer(){
2125
2126 $response = array("status" => 1);
2127 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
2128 $payment_active = 0;
2129 $payment_live = 0;
2130 $calendarAccount = $this->getCalendarAccount(intval($_POST['calendarAccountKey']));
2131 $paymentMethod = explode(",", $calendarAccount['paymentMethod']);
2132 $response['calendarAccount'] = $calendarAccount;
2133 $user = $this->get_user();
2134 #$response['user'] = $user;
2135 if(intval($user['status']) == 1){
2136
2137 if(isset($_POST['payType']) && $_POST['payType'] == 'stripe'){
2138
2139 #$payment_active = get_option($this->prefix."stripe_active", "0");
2140 $payment_active = 0;
2141 if (!is_bool(array_search(strtolower($_POST['payType']), $paymentMethod))) {
2142
2143 $payment_active = 1;
2144
2145 }
2146
2147 $secret_key = get_option($this->prefix."stripe_secret_key", null);
2148 $products = $calendarAccount["subscriptionIdForStripe"];
2149 $products = explode(",", $products);
2150 $subscription = $this->getProductForStripe($secret_key, array($products[0]));
2151 $response['subscription'] = $subscription;
2152 if(is_array($subscription)){
2153
2154 $stripe = $creditCard->createCustomer($_POST['payType'], $public_key, $secret_key, $_POST['payToken'], $calendarAccount, $subscription, $user['user'], $payment_live, $payment_active);
2155 $response['stripe'] = $stripe;
2156 if(isset($stripe['subscription']['status']) && $stripe['subscription']['status'] == 'active'){
2157
2158 $response_subscription = $stripe['subscription'];
2159 $subscription_list = $user['user']['subscription_list'];
2160 #$subscription_list['customer_id_for_stripe'] = $response_subscription['customer'];
2161
2162 $add_subscription = $this->prepare_subscription($_POST['payType'], $response_subscription, $subscription);
2163
2164 /**
2165 $items = array();
2166 for($i = 0; $i < count($response_subscription['items']['data']); $i++){
2167
2168 $item = $response_subscription['items']['data'][$i]['plan'];
2169 array_push($items, $item);
2170
2171 }
2172
2173 $add_subscription = array(
2174 'product' => $subscription['product'],
2175 'name' => $subscription['name'],
2176 'customer_id_for_stripe' => $response_subscription['customer'],
2177 'subscription_id_for_stripe' => $response_subscription['id'],
2178 'period_start' => $response_subscription['current_period_start'],
2179 'period_end' => $response_subscription['current_period_end'],
2180 'booking_count' => null,
2181 'payType' => sanitize_text_field($_POST['payType']),
2182 'items' => $items,
2183 );
2184 **/
2185
2186 $subscription_list[$subscription['product']] = $add_subscription;
2187 $user['user']['subscription_list'] = $subscription_list;
2188 $update = $this->update_subscription_list_of_user($user['user']['current_member_id'], $subscription_list);
2189
2190 $response['update_subscription'] = $update;
2191 #$response['user'] = $user;
2192 $response['subscription_list'] = $subscription_list;
2193
2194 }else{
2195
2196 $response["status"] = 0;
2197
2198 }
2199
2200 }else{
2201
2202 $response["status"] = 0;
2203
2204 }
2205
2206 }else if(isset($_POST['payType']) && $_POST['payType'] == 'paypal'){
2207
2208 #$payment_active = get_option($this->prefix."paypal_active", "0");
2209 $payment_active = 0;
2210 if (!is_bool(array_search(strtolower($_POST['payType']), $paymentMethod))) {
2211
2212 $payment_active = 1;
2213
2214 }
2215
2216 $payment_live = get_option($this->prefix."paypal_live", "0");
2217 $public_key = get_option($this->prefix."paypal_client_id", null);
2218 $secret_key = get_option($this->prefix."paypal_secret_key", null);
2219
2220 }
2221
2222 }else{
2223
2224 $response["status"] = 0;
2225
2226 }
2227
2228 return $response;
2229
2230 }
2231
2232 public function getProductForStripe($secret, $products = array()){
2233
2234 $subscriptions = array();
2235 for($index = 0; $index < count($products); $index++){
2236
2237 $product = $products[$index];
2238 $args = array(
2239 'method' => 'GET',
2240 'timeout' => $this->request_timeout,
2241 'headers' => array(
2242 'Authorization' => 'Basic ' . base64_encode($secret . ':')
2243 )
2244 );
2245 $response = wp_remote_request("https://api.stripe.com/v1/plans?limit=100&product=" . $product, $args);
2246 $object = json_decode(wp_remote_retrieve_body($response));
2247 $statusCode = wp_remote_retrieve_response_code($response);
2248
2249 /**
2250 $ch = curl_init();
2251 curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com/v1/plans?limit=100&product=".$product);
2252 curl_setopt($ch, CURLOPT_USERPWD, $secret.":");
2253 curl_setopt($ch, CURLOPT_POST, 0);
2254
2255 ob_start();
2256 $response = curl_exec($ch);
2257 $response = ob_get_contents();
2258 ob_end_clean();
2259 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2260 curl_close ($ch);
2261 $response = json_decode($response, true);
2262 **/
2263
2264 $name = null;
2265 $currency = 'usd';
2266 $amount = 0;
2267 $bool = false;
2268 $planKeys = array();
2269 $plans = array();
2270 for($i = 0; $i < count($response['data']); $i++){
2271
2272 $data = $response['data'][$i];
2273 if($data['active'] === true){
2274
2275 $bool = true;
2276 $name = $data['name'];
2277 $currency = $data['currency'];
2278 $amount += intval($data['amount']);
2279
2280 array_push($planKeys, $data['id']);
2281 array_push($plans, array(
2282 'id' => $data['id'],
2283 'name' => $data['name'],
2284 'label' => $data['name'],
2285 'amount' => $data['amount'],
2286 'currency' => $data['currency'],
2287 ));
2288
2289 }
2290
2291 }
2292
2293 if($bool === true){
2294
2295 $subscription = array('product' => $product, 'name' => $name, 'amount' => $amount, 'currency' => $currency, 'planKeys' => $planKeys, 'plans' => $plans, 'status' => 1, 'subscribed' => 0);
2296 array_push($subscriptions, $subscription);
2297
2298 }
2299
2300 }
2301
2302 if(count($subscriptions) > 0){
2303
2304 return $subscriptions[0];
2305
2306 }else{
2307
2308 return false;
2309
2310 }
2311
2312 }
2313
2314 public function updateRegularHolidays() {
2315
2316 global $wpdb;
2317 $table_name = $wpdb->prefix . "booking_package_regular_holidays";
2318 $sql = $wpdb->prepare(
2319 "SELECT * FROM ".$table_name." WHERE `accountKey` = %s AND `day` = %d AND `month` = %d AND `year` = %d;",
2320 array(
2321 sanitize_text_field($_POST['accountKey']),
2322 intval($_POST['day']),
2323 intval($_POST['month']),
2324 intval($_POST['year']),
2325 )
2326 );
2327
2328 $unixTime = date('U', mktime(0, 0, 0, intval($_POST['month']), intval($_POST['day']), intval($_POST['year'])));
2329 $row = $wpdb->get_row($sql, ARRAY_A);
2330 if (!is_null($row)) {
2331
2332 try {
2333
2334 $wpdb->query("START TRANSACTION");
2335 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
2336 $bool = $wpdb->update(
2337 $table_name,
2338 array(
2339 'status' => sanitize_text_field($_POST['status']),
2340 ),
2341 array(
2342 'accountKey' => sanitize_text_field($_POST['accountKey']),
2343 'day' => intval($_POST['day']),
2344 'month' => intval($_POST['month']),
2345 'year' => intval($_POST['year']),
2346 ),
2347 array('%s'),
2348 array('%s', '%d', '%d', '%d')
2349 );
2350
2351 $wpdb->query('COMMIT');
2352 $wpdb->query('UNLOCK TABLES');
2353
2354 } catch (Exception $e) {
2355
2356 $wpdb->query('ROLLBACK');
2357 $wpdb->query('UNLOCK TABLES');
2358
2359 }/** finally {
2360
2361 $wpdb->query('UNLOCK TABLES');
2362
2363 }**/
2364 } else {
2365
2366 $wpdb->insert(
2367 $table_name,
2368 array(
2369 'accountKey' => sanitize_text_field($_POST['accountKey']),
2370 'day' => intval($_POST['day']),
2371 'month' => intval($_POST['month']),
2372 'year' => intval($_POST['year']),
2373 'unixTime' => sanitize_text_field($unixTime),
2374 'status' => sanitize_text_field($_POST['status']),
2375 'update' => date('U'),
2376 ),
2377 array('%s', '%d', '%d', '%d', '%s', '%s', '%s')
2378 );
2379
2380 }
2381
2382 return $this->getRegularHolidays($_POST['month_calendar'], $_POST['year_calendar'], $_POST['accountKey'], get_option('start_of_week', 0));
2383
2384 }
2385
2386 public function confirmRegularHolidays($accountKey, $month, $day, $year) {
2387
2388 $value = false;
2389 global $wpdb;
2390 $table_name = $wpdb->prefix . "booking_package_regular_holidays";
2391 $sql = $wpdb->prepare(
2392 "SELECT `status` FROM `" . $table_name . "` WHERE `month` = %d AND `day` = %d AND `year` = %d AND (`accountKey` = 'share' || `accountKey` = %s);",
2393 array(
2394 intval($month),
2395 intval($day),
2396 intval($year),
2397 sanitize_text_field($accountKey)
2398 )
2399 );
2400
2401 $holidays = $wpdb->get_results($sql, ARRAY_A);
2402 foreach ((array) $holidays as $key => $holiday) {
2403
2404 if (intval($holiday['status']) == 1) {
2405
2406 $value = true;
2407 break;
2408
2409 }
2410
2411 }
2412
2413 return $value;
2414
2415 }
2416
2417 public function confirmPublicHolidays($month, $day, $year) {
2418
2419 $value = false;
2420 global $wpdb;
2421 $table_name = $wpdb->prefix . "booking_package_regular_holidays";
2422 $sql = $wpdb->prepare(
2423 "SELECT `status` FROM `" . $table_name . "` WHERE `month` = %d AND `day` = %d AND `year` = %d AND `accountKey` = 'national';",
2424 array(
2425 intval($month),
2426 intval($day),
2427 intval($year),
2428 sanitize_text_field($accountKey)
2429 )
2430 );
2431
2432 $holidays = $wpdb->get_results($sql, ARRAY_A);
2433 foreach ((array) $holidays as $key => $holiday) {
2434
2435 if (intval($holiday['status']) == 1) {
2436
2437 $value = true;
2438 break;
2439
2440 }
2441
2442 }
2443
2444 return $value;
2445
2446 }
2447
2448 public function getRegularHolidays($month, $year, $accountKey = null, $startOfWeek = 0, $share = false) {
2449
2450 $last_day = date('t', mktime(0, 0, 0, $month, 1, $year));
2451 $week_start_num = intval(date('w', mktime(0, 0, 0, $month, 1, $year)));
2452 $week_last_num = intval(date('w', mktime(0, 0, 0, $month, $last_day, $year)));
2453 $date = array('startDay' => 1, 'lastDay' => $last_day, 'startWeek' => $week_start_num, 'lastWeek' => $week_last_num, 'year' => $year, 'month' => intval($month), 'day' => 1);
2454 $calendar = array("date" => $date, "calendar" => array());
2455
2456 global $wpdb;
2457 $table_name = $wpdb->prefix . "booking_package_regular_holidays";
2458 $calendarList = $this->getCalendarList($month, 1, $year, $startOfWeek);
2459
2460 if (empty($accountKey) === false && $accountKey != 'share' && $accountKey != 'national') {
2461
2462 $calendarAccount = $this->getCalendarAccount($accountKey);
2463 $startOfWeek = $calendarAccount['startOfWeek'];
2464 $calendarList = $this->getCalendarList($month, 1, $year, $startOfWeek);
2465
2466 }
2467
2468 $list = array();
2469 foreach ((array) $calendarList as $key => $value) {
2470
2471 for ($i = $value['startDay']; $i <= $value['lastDay']; $i++) {
2472
2473 $month = $value['month'];
2474 $year = $value['year'];
2475 $key = $value['year'].sprintf("%02d%02d", $value['month'], $i);
2476 $week = date('w', mktime(0, 0, 0, $month, $i, $year));
2477 $dayArray = array('year' => $value['year'], 'month' => $value['month'], 'day' => $i, 'week' => $week, 'count' => null, 'accountKey' => $accountKey, 'status' => 0);
2478 $list[$key] = $dayArray;
2479
2480 if ($share === true) {
2481
2482 $sql = $wpdb->prepare(
2483 "SELECT * FROM ".$table_name." WHERE (`accountKey` = 'share' || `accountKey` = %s) AND `year` = %d AND `month` = %d AND `day` = %d ORDER BY unixTime ASC;",
2484 /** "SELECT * FROM ".$table_name." WHERE `accountKey` = %s AND `year` = %d AND `month` = %d AND `day` = %d ORDER BY unixTime ASC;", **/
2485 array(
2486 sanitize_text_field($accountKey),
2487 intval($year),
2488 intval($month),
2489 intval($i),
2490 )
2491 );
2492
2493 } else {
2494
2495 $sql = $wpdb->prepare(
2496 "SELECT * FROM ".$table_name." WHERE `accountKey` = %s AND `year` = %d AND `month` = %d AND `day` = %d ORDER BY unixTime ASC;",
2497 array(
2498 sanitize_text_field($accountKey),
2499 intval($year),
2500 intval($month),
2501 intval($i),
2502 )
2503 );
2504
2505 }
2506
2507 $rows = $wpdb->get_results($sql, ARRAY_A);
2508 foreach ((array) $rows as $holidayKey => $holidayValue) {
2509
2510 if (intval($holidayValue['status']) == 1) {
2511
2512 $list[$key] = $holidayValue;
2513 break;
2514
2515 }
2516
2517 }
2518
2519 }
2520
2521 }
2522
2523 if ($accountKey == 'national') {
2524
2525 $setting = new booking_package_setting($this->prefix, $this->pluginName);
2526 $numberKeys = $setting->getListOfDaysOfWeek();
2527 $list = $this->addPriceKeyByDayOfWeek($list, $numberKeys, true);
2528
2529 }
2530
2531 $calendar['calendarList'] = $calendarList;
2532 $calendar['calendar'] = $list;
2533
2534 return $calendar;
2535
2536 }
2537
2538 public function addPriceKeyByDayOfWeek($schedules, $numberKeys, $updateNationalHoliday = false) {
2539
2540 foreach ((array) $schedules as $key => $value) {
2541
2542 if (isset($value['week'])) {
2543
2544 $week = intval($value['week']) - 1;
2545 if ($week < 0) {
2546
2547 $week = 6;
2548
2549 }
2550 $schedules[$key]['priceKeyByDayOfWeek'] = $numberKeys[$week];
2551
2552 }
2553
2554 if (isset($value['weekKey'])) {
2555
2556 $week = intval($value['weekKey']) - 1;
2557 if ($week < 0) {
2558
2559 $week = 6;
2560
2561 }
2562 $schedules[$key]['priceKeyByDayOfWeek'] = $numberKeys[$week];
2563
2564 }
2565
2566 if ($updateNationalHoliday === true) {
2567
2568 if (isset($value['status']) && intval($value['status']) == 1) {
2569
2570 $dayBeforeUnixTime = intval($value['unixTime']) - (1440 * 60);
2571 $dayBeforeKey = date('Y', $dayBeforeUnixTime) . date('m', $dayBeforeUnixTime) . date('d', $dayBeforeUnixTime);
2572 $week = date('w', mktime(0, 0, 0, $value['month'], $value['day'], $value['year']));
2573 $schedules[$key]['week'] = $week;
2574 $schedules[$key]['priceKeyByDayOfWeek'] = 'priceOnNationalHoliday';
2575 if (isset($schedules[$dayBeforeKey]) && $schedules[$dayBeforeKey]['priceKeyByDayOfWeek'] != 'priceOnNationalHoliday') {
2576
2577 $schedules[$dayBeforeKey]['priceKeyByDayOfWeek'] = 'priceOnDayBeforeNationalHoliday';
2578
2579 }
2580
2581 }
2582
2583 }
2584
2585 }
2586
2587 return $schedules;
2588
2589 }
2590
2591 public function createFirstCalendar($timeZone){
2592
2593 global $wpdb;
2594 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
2595 $sql = "SELECT COUNT(`key`) FROM `".$table_name."`;";
2596
2597 $rows = $wpdb->get_results("SELECT COUNT(`key`) FROM `".$table_name."`;", ARRAY_A);
2598 foreach ((array) $rows as $row) {
2599
2600 if (intval($row['COUNT(`key`)']) == 0) {
2601
2602 $date = date('U');
2603 $local = get_locale();
2604 $startOfWeek = 0;
2605 if ($local == 'es_ES' || $local == 'en_GB' || $local == 'de_DE' || $local == 'it_IT' || $local == 'nl_NL' || $local == 'da_DK' || $local == 'nb_NO' || $local == 'sv_SE' || $local == 'fr_FR') {
2606
2607 $startOfWeek = 1;
2608
2609 }
2610
2611 $siteName = get_bloginfo('name');
2612 $email = get_bloginfo('admin_email');
2613
2614 if ($local == 'ja' || $local == 'ja-jp' || $local == 'ja_jp') {
2615
2616 $wpdb->insert(
2617 $table_name,
2618 array(
2619 'key' => 1,
2620 'name' => sanitize_text_field('First Calendar'),
2621 'type' => sanitize_text_field('day'),
2622 'status' => sanitize_text_field('open'),
2623 'created' => sanitize_text_field($date),
2624 'uploadDate' => sanitize_text_field($date),
2625 'displayRemainingCapacityInCalendar' => 0,
2626 'displayRemainingCapacityHasMoreThenThreshold' => '{"symbol":"panorama_fish_eye","color":"#969696"}',
2627 'displayRemainingCapacityHasLessThenThreshold' => '{"symbol":"change_history","color":"#f4e800"}',
2628 'displayRemainingCapacityHas0' => '{"symbol":"close","color":"#e24b00"}',
2629 'startOfWeek' => $startOfWeek,
2630 'icalToken' => hash('ripemd160', date('U')),
2631 'email_to' => sanitize_text_field($email),
2632 'email_from' => sanitize_text_field($email),
2633 'email_from_title' => sanitize_text_field('First Calendar'),
2634 'timezone' => sanitize_text_field($timeZone),
2635 ),
2636 array(
2637 '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s',
2638 '%d', '%s', '%s', '%s', '%s', '%s',
2639 )
2640 );
2641 add_option($this->prefix . 'positionTimeDate', 'dateTime');
2642 add_option($this->prefix . 'positionOfWeek', 'after');
2643 add_option($this->prefix . 'currency', 'jpy');
2644 add_option($this->prefix . 'country', 'JP');
2645
2646 } else {
2647
2648 $wpdb->insert(
2649 $table_name,
2650 array(
2651 'key' => 1,
2652 'name' => sanitize_text_field('First Calendar'),
2653 'type' => sanitize_text_field('day'),
2654 'status' => sanitize_text_field('open'),
2655 'created' => sanitize_text_field($date),
2656 'startOfWeek' => $startOfWeek,
2657 'icalToken' => hash('ripemd160', date('U')),
2658 'uploadDate' => sanitize_text_field($date),
2659 'email_to' => sanitize_text_field($email),
2660 'email_from' => sanitize_text_field($email),
2661 'email_from_title' => sanitize_text_field('First Calendar'),
2662 'timezone' => sanitize_text_field($timeZone),
2663 ),
2664 array(
2665 '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s',
2666 '%s', '%s',
2667 )
2668 );
2669
2670 if ($local == 'en_US' || $local == 'en_GB') {
2671
2672 add_option($this->prefix . 'positionTimeDate', 'timeDate');
2673
2674 }
2675 add_option($this->prefix . 'positionOfWeek', 'before');
2676
2677 if ($local == 'en' || $local == 'en_US') {
2678
2679 add_option($this->prefix . 'country', 'US');
2680 add_option($this->prefix . 'currency', 'usd');
2681
2682 } else if ($local == 'en_GB') {
2683
2684 add_option($this->prefix . 'country', 'GB');
2685 add_option($this->prefix . 'currency', 'gbp');
2686
2687 } else if ($local == 'fr' || $local == 'fr_FR' || $local == 'es_ES' || $local == 'it_IT' || $local == 'de_DE' || $local == 'nl_NL') {
2688
2689 add_option($this->prefix . 'currency', 'eur');
2690
2691 }
2692
2693 if (strlen($local) === 5) {
2694
2695 $country_code = strtoupper(substr($local, -2));
2696 add_option($this->prefix . 'country', $country_code);
2697
2698 }
2699
2700 }
2701 $this->addGuests(1, 'day');
2702
2703 $wpdb->insert(
2704 $table_name,
2705 array(
2706 'key' => 2,
2707 'name' => sanitize_text_field('First Calendar for hotel'),
2708 'type' => sanitize_text_field('hotel'),
2709 'status' => sanitize_text_field('open'),
2710 'created' => sanitize_text_field($date),
2711 'uploadDate' => sanitize_text_field($date),
2712 'numberOfRoomsAvailable' => 5,
2713 'includeChildrenInRoom' => 1,
2714 'startOfWeek' => $startOfWeek,
2715 'icalToken' => hash('ripemd160', date('U')),
2716 'email_to' => sanitize_text_field($email),
2717 'email_from' => sanitize_text_field($email),
2718 'email_from_title' => sanitize_text_field('First Calendar for hotel'),
2719 'timezone' => sanitize_text_field($timeZone),
2720 ),
2721 array(
2722 '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s',
2723 '%s', '%s', '%s', '%s',
2724 )
2725 );
2726 $this->addGuests(2, 'hotel');
2727
2728 }
2729
2730 break;
2731
2732 }
2733
2734 $this->insertAccountSchedule(date('m'), date('d'), date('Y'));
2735
2736 }
2737
2738 public function setMessagingServiceInCalendarAccount($accountKey) {
2739
2740 global $wpdb;
2741 $twilio_active = get_option($this->prefix . 'twilio_active', 0);
2742 $messagingService = 0;
2743 if (intval($twilio_active) === 1) {
2744
2745 $messagingService = 'twilio';
2746
2747 }
2748
2749 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
2750 try {
2751
2752 $wpdb->query("START TRANSACTION");
2753 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
2754 $bool = $wpdb->update(
2755 $table_name,
2756 array(
2757 'messagingService' => sanitize_text_field($messagingService),
2758 ),
2759 array('key' => intval($accountKey)),
2760 array('%s'),
2761 array('%d')
2762 );
2763 $wpdb->query('COMMIT');
2764 $wpdb->query('UNLOCK TABLES');
2765
2766 } catch (Exception $e) {
2767
2768 $wpdb->query('ROLLBACK');
2769 $wpdb->query('UNLOCK TABLES');
2770
2771 }/** finally {
2772
2773 $wpdb->query('UNLOCK TABLES');
2774
2775 }**/
2776 }
2777
2778 public function setTimeZoneInCalendarAccount($accountKey) {
2779
2780 global $wpdb;
2781 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
2782 $timezone = get_option($this->prefix . "timezone", null);
2783 if (is_null($timezone)) {
2784
2785 $timezone = get_option('timezone_string', '');
2786 if (empty($timezone) || strlen($timezone) == 0) {
2787
2788 $timezone = 'UTC';
2789
2790 }
2791
2792 }
2793
2794 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
2795 try {
2796
2797 $wpdb->query("START TRANSACTION");
2798 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
2799 $bool = $wpdb->update(
2800 $table_name,
2801 array(
2802 'timezone' => sanitize_text_field($timezone),
2803 ),
2804 array('key' => intval($accountKey)),
2805 array('%s'),
2806 array('%d')
2807 );
2808 $wpdb->query('COMMIT');
2809 $wpdb->query('UNLOCK TABLES');
2810
2811 } catch (Exception $e) {
2812
2813 $wpdb->query('ROLLBACK');
2814 $wpdb->query('UNLOCK TABLES');
2815
2816 }/** finally {
2817
2818 $wpdb->query('UNLOCK TABLES');
2819
2820 }**/
2821
2822 return $timezone;
2823
2824 }
2825
2826 public function resetCustomizeLabels($calendarAccount) {
2827
2828 $customizeLabels = $this->setCustomizeLabels($calendarAccount, null, false);
2829 return array('status' => true);
2830
2831 }
2832
2833 public function resetCustomizeButtons($calendarAccount) {
2834
2835 $customizeButtons = $this->setCustomizeButtons($calendarAccount, null);
2836 return array('status' => true);
2837
2838 }
2839
2840 public function resetCustomizeLayouts($calendarAccount) {
2841
2842 $customizeLayouts = $this->setCustomizeLayouts($calendarAccount, null);
2843 return array('status' => true);
2844
2845 }
2846
2847 public function updateCustomize($calendarAccount, $key, $customize) {
2848
2849 global $wpdb;
2850 if ($key === 'customizeLabels') {
2851
2852 if (array_key_exists('Hello, %s', $customize) === true && strpos($customize['Hello, %s'], '%s') === false) {
2853
2854 $customize['Hello, %s'] .= ' %s';
2855
2856 }
2857
2858 if (array_key_exists('%s Slots Left', $customize) === true && strpos($customize['%s Slots Left'], '%s') === false) {
2859
2860 $customize['%s Slots Left'] = '%s ' . $customize['%s Slots Left'];
2861
2862 }
2863
2864 }
2865 $status = false;
2866 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
2867 try {
2868
2869 $bool = $wpdb->update(
2870 $table_name,
2871 array( sanitize_text_field($key) => sanitize_text_field(json_encode($customize)) ),
2872 array( 'key' => intval($calendarAccount['key']) ),
2873 array( '%s' ),
2874 array('%d')
2875 );
2876 $status = true;
2877 $wpdb->query('COMMIT');
2878 $wpdb->query('UNLOCK TABLES');
2879
2880 } catch (Exception $e) {
2881
2882 $wpdb->query('ROLLBACK');
2883 $wpdb->query('UNLOCK TABLES');
2884
2885 }/** finally {
2886
2887 $wpdb->query('UNLOCK TABLES');
2888
2889 }**/
2890
2891 return array('status' => $status);
2892
2893 }
2894
2895 public function setCustomizeLabels($calendarAccount, $customizeLabels, $subDirectory = false) {
2896
2897 $defaultLabels = $this->defaultLabels($calendarAccount['type'], false);
2898 if (empty($customizeLabels) === true) {
2899
2900 if ($calendarAccount['type'] === 'hotel') {
2901
2902 $defaultLabels['Check-in'] = __('Arrival (Check-in)', 'booking-package');
2903 $defaultLabels['Check-out'] = __('Departure (Check-out)', 'booking-package');
2904 if (intval($calendarAccount['expressionsCheck']) === 1) {
2905
2906 $defaultLabels['Check-in'] = __('Arrival', 'booking-package');
2907 $defaultLabels['Check-out'] = __('Departure', 'booking-package');
2908
2909 } else if (intval($calendarAccount['expressionsCheck']) === 2) {
2910
2911 $defaultLabels['Check-in'] = __('Check-in', 'booking-package');
2912 $defaultLabels['Check-out'] = __('Check-out', 'booking-package');
2913
2914 }
2915
2916 } else {
2917
2918 if (empty($calendarAccount['courseTitle']) === false) {
2919
2920 $defaultLabels['Service'] = $calendarAccount['courseTitle'];
2921
2922 }
2923
2924 }
2925
2926 $this->updateCustomize($calendarAccount, 'customizeLabels', $defaultLabels);
2927
2928 } else {
2929
2930 $update = false;
2931 $customizeLabels = json_decode($customizeLabels, true);
2932 $defaultLabels = $this->mergeCustomizeElements($calendarAccount, 'customizeLabels', $defaultLabels, $customizeLabels);
2933 /**
2934 foreach ($customizeLabels as $key => $value) {
2935
2936 if (array_key_exists($key, $defaultLabels) === false) {
2937
2938 $update = true;
2939 unset($customizeLabels[$key]);
2940
2941 }
2942
2943 }
2944
2945 foreach ($defaultLabels as $key => $value) {
2946
2947 if (array_key_exists($key, $customizeLabels) === false) {
2948
2949 $update = true;
2950 $customizeLabels[$key] = $value;
2951
2952 } else {
2953
2954 $defaultLabels[$key] = $customizeLabels[$key];
2955
2956 }
2957
2958 }
2959
2960 if ($update === true) {
2961
2962 $this->updateCustomize($calendarAccount, 'customizeLabels', $defaultLabels);
2963
2964 }
2965 **/
2966 }
2967
2968 if ($subDirectory === true) {
2969
2970 $directoryLabels = $this->defaultLabels($calendarAccount['type'], $subDirectory);
2971 if ($this->payWithPayPay === 0) {
2972
2973 unset($directoryLabels['form_labels']['Pay with PayPay']);
2974
2975 }
2976
2977 foreach ($directoryLabels as $key => $subDirectoryLabels) {
2978
2979 $directoryLabels[$key] = (function($subDirectoryLabels, $defaultLabels) {
2980
2981 foreach ($subDirectoryLabels as $key => $label) {
2982
2983 if (array_key_exists($key, $defaultLabels) === true) {
2984
2985 $subDirectoryLabels[$key] = $defaultLabels[$key];
2986
2987 }
2988
2989 }
2990
2991 return $subDirectoryLabels;
2992
2993 })($subDirectoryLabels, $defaultLabels);
2994
2995 }
2996
2997 return $directoryLabels;
2998
2999 }
3000
3001 return $defaultLabels;
3002
3003 }
3004
3005 public function setCustomizeButtons($calendarAccount, $customizeButtons) {
3006
3007 $defaultButtons = $this->defaultButtons($calendarAccount['type'], false);
3008 if (empty($customizeButtons) === true) {
3009
3010 $this->updateCustomize($calendarAccount, 'customizeButtons', $defaultButtons);
3011
3012 } else {
3013
3014 $customizeButtons = json_decode($customizeButtons, true);
3015 $defaultButtons = $this->mergeCustomizeElements($calendarAccount, 'customizeButtons', $defaultButtons, $customizeButtons);
3016
3017 }
3018
3019 return $defaultButtons;
3020
3021 }
3022
3023 public function setCustomizeLayouts($calendarAccount, $customizeCss) {
3024
3025 $defaultCss = $this->defaultLayouts($calendarAccount);
3026 if (empty($customizeCss) === true) {
3027
3028 $this->updateCustomize($calendarAccount, 'customizeLayouts', $defaultCss);
3029
3030 } else {
3031
3032 $customizeCss = json_decode($customizeCss, true);
3033 $defaultCss = $this->mergeCustomizeElements($calendarAccount, 'customizeLayouts', $defaultCss, $customizeCss);
3034
3035 }
3036
3037 return $defaultCss;
3038
3039 }
3040
3041 public function mergeCustomizeElements($calendarAccount, $name, $defaultElements, $customizeElements) {
3042
3043 $update = false;
3044 foreach ($customizeElements as $key => $value) {
3045
3046 if (array_key_exists($key, $defaultElements) === false) {
3047
3048 $update = true;
3049 unset($customizeElements[$key]);
3050
3051 }
3052
3053 }
3054
3055 foreach ($defaultElements as $key => $value) {
3056
3057 if (array_key_exists($key, $customizeElements) === false) {
3058
3059 $update = true;
3060 $customizeElements[$key] = $value;
3061
3062 } else {
3063
3064 $defaultElements[$key] = $customizeElements[$key];
3065
3066 }
3067
3068 }
3069
3070 if ($update === true) {
3071
3072 $this->updateCustomize($calendarAccount, $name, $defaultElements);
3073
3074 }
3075
3076 return $defaultElements;
3077
3078 }
3079
3080 public function changeCustomizeTheme($calendarAccount, $selectedTheme) {
3081
3082 $theme = $this->defaultLayouts($calendarAccount, $selectedTheme);
3083 return $theme;
3084
3085 }
3086
3087 public function getCalendarAccountListData($columns = "*") {
3088
3089 global $wpdb;
3090 $table_name = $wpdb->prefix."booking_package_calendar_accounts";
3091 $rows = $wpdb->get_results("SELECT ".$columns." FROM `".$table_name."`;", ARRAY_A);
3092 foreach ((array) $rows as $key => $row) {
3093
3094 if (array_key_exists('customizeLabels', $row)) {
3095
3096 $rows[$key]['customizeLabels'] = $this->setCustomizeLabels($row, $row['customizeLabels'], true);
3097
3098 }
3099
3100 if (array_key_exists('customizeButtons', $row)) {
3101
3102 $rows[$key]['customizeButtons'] = $this->setCustomizeButtons($row, $row['customizeButtons']);
3103
3104 }
3105
3106 if (array_key_exists('customizeLayouts', $row)) {
3107
3108 $rows[$key]['customizeLayouts'] = $this->setCustomizeLayouts($row, $row['customizeLayouts']);
3109
3110 }
3111
3112 if (array_key_exists('maxBookingSlotsPerDay', $row)) {
3113
3114 $rows[$key]['maxBookingSlotsPerDay'] = $this->updateMaxBookingSlotsPerDay('set', $rows[$key]['maxBookingSlotsPerDay']);
3115
3116 }
3117
3118
3119 /**
3120 if ($columns === '*') {
3121
3122 $rows[$key]['customizeLayouts'] = $this->defaultLayouts($row);
3123
3124 }
3125 **/
3126 if (isset($row['icalToken']) && intval($row['icalToken']) == 0) {
3127
3128 $this->refreshIcalToken($row['key']);
3129
3130 }
3131
3132 if (isset($row['limitNumberOfGuests'])) {
3133
3134 $limitNumberOfGuests = json_decode($row['limitNumberOfGuests'], true);
3135 if (empty($limitNumberOfGuests)) {
3136
3137 $limitNumberOfGuests = array(
3138 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3139 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3140 );
3141
3142 }
3143 $rows[$key]['limitNumberOfGuests'] = $limitNumberOfGuests;
3144
3145 }
3146
3147 if (isset($row['minimumGuests'])) {
3148
3149 $minimumGuests = json_decode($row['minimumGuests'], true);
3150 if (empty($minimumGuests) === true) {
3151
3152 $minimumGuests = array('enabled' => 0, 'included' => 0, 'number' => 0);
3153
3154 }
3155 $rows[$key]['minimumGuests'] = $minimumGuests;
3156
3157 }
3158
3159 if (isset($row['maximumGuests'])) {
3160
3161 $maximumGuests = json_decode($row['maximumGuests'], true);
3162 if (empty($maximumGuests) === true) {
3163
3164 $maximumGuests = array('enabled' => 0, 'included' => 0, 'number' => 0);
3165
3166 }
3167 $rows[$key]['maximumGuests'] = $maximumGuests;
3168
3169 }
3170
3171 if (isset($row['timezone']) && $row['timezone'] == 'none') {
3172
3173 $rows[$key]['timezone'] = $this->setTimeZoneInCalendarAccount($row['key']);
3174
3175 }
3176
3177 if (array_key_exists('messagingService', $row) && is_null($row['messagingService'])) {
3178
3179 $rows[$key]['messagingService'] = $this->setMessagingServiceInCalendarAccount($row['key']);
3180
3181 }
3182
3183 }
3184
3185 return $rows;
3186
3187 }
3188
3189 public function getCalendarAccount($accountKey = 1, $isExtensionsValid = null){
3190
3191 global $wpdb;
3192 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3193 $sql = $wpdb->prepare("SELECT * FROM `" . $table_name . "` WHERE `key` = %d;", array($accountKey));
3194 $row = $wpdb->get_row($sql, ARRAY_A);
3195
3196 if (is_null($row) === true) {
3197
3198 return false;
3199
3200 }
3201
3202 if (strlen($row['type']) == 0) {
3203
3204 $row['type'] = 'day';
3205
3206 }
3207
3208 if (isset($row['limitNumberOfGuests'])) {
3209
3210 $limitNumberOfGuests = json_decode($row['limitNumberOfGuests'], true);
3211 if (empty($limitNumberOfGuests)) {
3212
3213 $limitNumberOfGuests = array(
3214 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3215 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3216 );
3217
3218 }
3219 $row['limitNumberOfGuests'] = $limitNumberOfGuests;
3220
3221 }
3222
3223 $row['customizeLabels'] = $this->setCustomizeLabels($row, $row['customizeLabels'], false);
3224 $row['customizeButtons'] = $this->setCustomizeButtons($row, $row['customizeButtons']);
3225 $row['customizeLayouts'] = $this->setCustomizeLayouts($row, $row['customizeLayouts']);
3226 $row['maxBookingSlotsPerDay'] = $this->updateMaxBookingSlotsPerDay('set', $row['maxBookingSlotsPerDay']);
3227
3228 /**
3229 if (isset($row['minimumGuests'])) {
3230
3231 $minimumGuests = json_decode($row['minimumGuests'], true);
3232 if (empty($minimumGuests) === true) {
3233
3234 $minimumGuests = array('enabled' => 0, 'included' => 0, 'number' => 0);
3235
3236 }
3237 $row['minimumGuests'] = $minimumGuests;
3238
3239 }
3240
3241 if (isset($row['maximumGuests'])) {
3242
3243 $maximumGuests = json_decode($row['maximumGuests'], true);
3244 if (empty($maximumGuests) === true) {
3245
3246 $maximumGuests = array('enabled' => 0, 'included' => 0, 'number' => 0);
3247
3248 }
3249 $row['maximumGuests'] = $maximumGuests;
3250
3251 }
3252 **/
3253 if ($isExtensionsValid === false && $row['type'] == 'hotel') {
3254
3255 if ($row['hotelChargeOnDayBeforeNationalHoliday'] != 0 || $row['hotelChargeOnNationalHoliday'] != 0) {
3256
3257 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3258 try {
3259
3260 $wpdb->query("START TRANSACTION");
3261 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
3262 $bool = $wpdb->update(
3263 $table_name,
3264 array(
3265 'hotelChargeOnDayBeforeNationalHoliday' => 0,
3266 'hotelChargeOnNationalHoliday' => 0,
3267 ),
3268 array('key' => intval($accountKey)),
3269 array(
3270 '%d', '%d',
3271 ),
3272 array('%d')
3273 );
3274
3275 $wpdb->query('COMMIT');
3276 $wpdb->query('UNLOCK TABLES');
3277
3278 } catch (Exception $e) {
3279
3280 $wpdb->query('ROLLBACK');
3281 $wpdb->query('UNLOCK TABLES');
3282
3283 }/** finally {
3284
3285 $wpdb->query('UNLOCK TABLES');
3286
3287 }**/
3288
3289 }
3290
3291 }
3292
3293 if (isset($row['timezone']) === true && $row['timezone'] == 'none') {
3294
3295 $row['timezone'] = $this->setTimeZoneInCalendarAccount($accountKey);
3296
3297 }
3298
3299
3300 $timezone = new DateTimeZone($row['timezone']);
3301 $datetime = new DateTime('now', $timezone);
3302 $offset = $datetime->getOffset();
3303 $minutes = $offset / 60;
3304 $row['timezonOffset'] = ($minutes >= 0 ? "+" : "") . $minutes;
3305
3306 if (is_null($row['paymentMethod'])) {
3307
3308 $row['paymentMethod'] = $this->setPaymentMethod($accountKey);
3309
3310 }
3311
3312 if (is_null($row['messagingService'])) {
3313
3314 #$rows[$key]['messagingService'] = $this->setMessagingServiceInCalendarAccount($row['key']);
3315
3316 }
3317
3318
3319
3320 return $row;
3321
3322 }
3323
3324 public function verificationMaxBookingSlotsPerDay($calendarAccount, $schedule, $applicantCount) {
3325
3326 global $wpdb;
3327 $isExtensionsValid = $this->getExtensionsValid();
3328 $response = array('status' => true, 'message' => null);
3329 $maxBookingSlotsPerDay = $calendarAccount['maxBookingSlotsPerDay'];
3330 if (intval($maxBookingSlotsPerDay['maxBookingSlotsPerDayStatus']) === 1) {
3331
3332 $maxBookingSlotsWeekday = array(
3333 intval($maxBookingSlotsPerDay['maxBookingSlotsOnSunday']),
3334 intval($maxBookingSlotsPerDay['maxBookingSlotsOnMonday']),
3335 intval($maxBookingSlotsPerDay['maxBookingSlotsOnTuesday']),
3336 intval($maxBookingSlotsPerDay['maxBookingSlotsOnWednesday']),
3337 intval($maxBookingSlotsPerDay['maxBookingSlotsOnThursday']),
3338 intval($maxBookingSlotsPerDay['maxBookingSlotsOnFriday']),
3339 intval($maxBookingSlotsPerDay['maxBookingSlotsOnSaturday']),
3340 intval($maxBookingSlotsPerDay['maxBookingSlotsOnNationalHoliday']),
3341 );
3342
3343 $weekKey = intval($schedule['weekKey']);
3344 $publicHoliday = $this->confirmPublicHolidays($schedule['month'], $schedule['day'], $schedule['year']);
3345 if ($publicHoliday === true) {
3346
3347 $weekKey = 7;
3348
3349 }
3350
3351 $bookingCount = 0;
3352 $table_name = $wpdb->prefix . "booking_package_schedules";
3353 $sql = $wpdb->prepare("SELECT * FROM `" . $table_name . "` WHERE `accountKey` = %d AND `month` = %d AND `day` = %d AND `year` = %d AND `status` = 'open';", array(intval($calendarAccount['key']), intval($schedule['month']), intval($schedule['day']), intval($schedule['year'])));
3354 $rows = $wpdb->get_results($sql, ARRAY_A);
3355 foreach ((array) $rows as $row) {
3356
3357 $unixTime = date('U', mktime($row['hour'], $row['min'], 0, $row['month'], $row['day'], $row['year']));
3358 $bookingCount += intval($row['bookingCount']);
3359
3360 }
3361 #var_dump($bookingCount + $applicantCount);
3362 #var_dump($maxBookingSlotsWeekday[$weekKey]);
3363 if ($maxBookingSlotsWeekday[$weekKey] < ($bookingCount + intval($applicantCount))) {
3364
3365 $response['status'] = false;
3366 $dateFormat = intval(get_option($this->prefix . "dateFormat", 0));
3367 $positionOfWeek = get_option($this->prefix . "positionOfWeek", "before");
3368 $response['message'] = sprintf(
3369 __('Based on the "%s" settings, all remaining booking slots for %s have been filled.', 'booking-package'),
3370 __('Max booking slots per weekday', 'booking-package'),
3371 $this->dateFormat($dateFormat, $positionOfWeek, intval($schedule['unixTime']), null, true, false, 'text')
3372 );
3373
3374 }
3375
3376 }
3377
3378 return $response;
3379
3380 }
3381
3382 public function updateMaxBookingSlotsPerDay($mode, $maxBookingSlotsPerDay) {
3383
3384 if (is_null($maxBookingSlotsPerDay) === true) {
3385
3386 $maxBookingSlotsPerDay = '[]';
3387
3388 }
3389
3390 $maxBookingSlotsPerDay = JSON_decode($maxBookingSlotsPerDay, true);
3391 $keys = array('maxBookingSlotsPerDayStatus' => 0, 'maxBookingSlotsOnMonday' => 10, 'maxBookingSlotsOnTuesday' => 10, 'maxBookingSlotsOnWednesday' => 10, 'maxBookingSlotsOnThursday' => 10, 'maxBookingSlotsOnFriday' => 10, 'maxBookingSlotsOnSaturday' => 10, 'maxBookingSlotsOnSunday' => 10, 'maxBookingSlotsOnNationalHoliday' => 0);
3392 foreach ($keys as $key => $value) {
3393
3394 if ($mode === 'add' && isset($_POST[$key])) {
3395
3396 $maxBookingSlotsPerDay[$key] = intval($_POST[$key]);
3397
3398 }
3399
3400 if (array_key_exists($key, $maxBookingSlotsPerDay) === false) {
3401
3402 $maxBookingSlotsPerDay[$key] = $value;
3403
3404 }
3405
3406 }
3407
3408 return $maxBookingSlotsPerDay;
3409
3410 }
3411
3412 public function setPaymentMethod($accountKey) {
3413
3414 global $wpdb;
3415 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3416 $paymentMethod = array();
3417 if (intval(get_option($this->prefix."stripe_active", 0)) == 1) {
3418
3419 array_push($paymentMethod, "stripe");
3420
3421 }
3422
3423 if (intval(get_option($this->prefix."paypal_active", 0)) == 1) {
3424
3425 array_push($paymentMethod, "paypal");
3426
3427 }
3428
3429 $paymentMethod = implode(",", $paymentMethod);
3430 try {
3431
3432 $wpdb->query("START TRANSACTION");
3433 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
3434 $bool = $wpdb->update(
3435 $table_name,
3436 array(
3437 'paymentMethod' => sanitize_text_field($paymentMethod),
3438 ),
3439 array('key' => intval($accountKey)),
3440 array('%s'),
3441 array('%d')
3442 );
3443 $wpdb->query('COMMIT');
3444 $wpdb->query('UNLOCK TABLES');
3445
3446 } catch (Exception $e) {
3447
3448 $wpdb->query('ROLLBACK');
3449 $wpdb->query('UNLOCK TABLES');
3450
3451 }/** finally {
3452
3453 $wpdb->query('UNLOCK TABLES');
3454
3455 }**/
3456 return $paymentMethod;
3457
3458 }
3459
3460 public function addCalendarAccount(){
3461
3462 $postList = array('cost' => 0, 'numberOfRoomsAvailable' => 1, 'numberOfPeopleInRoom' => 2, 'includeChildrenInRoom' => 0);
3463 foreach ((array) $postList as $key => $value) {
3464
3465 if (!isset($_POST[$key])) {
3466
3467 $_POST[$key] = $value;
3468
3469 }
3470
3471 }
3472
3473 $messagingService = 0;
3474 if (array_key_exists('messagingService', $_POST) === true) {
3475
3476 $messagingService = $_POST['messagingService'];
3477
3478 }
3479
3480 if (isset($_POST['displayRemainingSlotsInCalendar']) === true) {
3481
3482 $_POST['displayRemainingCapacityInCalendar'] = 0;
3483 $_POST['displayRemainingCapacityInCalendarAsNumber'] = 0;
3484 if ($_POST['displayRemainingSlotsInCalendar'] == 'int') {
3485
3486 $_POST['displayRemainingCapacityInCalendar'] = 1;
3487 $_POST['displayRemainingCapacityInCalendarAsNumber'] = 1;
3488
3489 } else if ($_POST['displayRemainingSlotsInCalendar'] == 'text') {
3490
3491 $_POST['displayRemainingCapacityInCalendar'] = 1;
3492
3493 }
3494
3495 }
3496
3497 $defaultKeys = array('timezone' => 'none', 'blockSameTimeBookingByUser' => 0, 'allowCancellationUser' => 0, 'bookingReminder' => 60, 'insertConfirmedPage' => 0, 'autoPublish' => 0, 'flowOfBooking' => 'calendar', 'multipleRooms' => 0, 'bookingVerificationCode' => 'false', 'bookingVerificationCodeToUser' => 'false', 'type' => 'day');
3498 foreach ($defaultKeys as $key => $value) {
3499
3500 if (array_key_exists($key, $_POST) === false) {
3501
3502 $_POST[$key] = $value;
3503
3504 }
3505
3506 }
3507
3508 if (intval($_POST['schedulesSharing']) == 1) {
3509
3510 $targetCalendar = $this->getCalendarAccount($_POST['targetSchedules']);
3511 if ($targetCalendar === false || $targetCalendar['type'] != $_POST['type']) {
3512
3513 $_POST['schedulesSharing'] = 0;
3514 $_POST['targetSchedules'] = 0;
3515
3516 } else {
3517
3518 $_POST['timezone'] = $targetCalendar['timezone'];
3519
3520 }
3521
3522 }
3523
3524 if (!isset($_POST['enableSubscriptionForStripe']) || $_POST['type'] == 'hotel') {
3525
3526 $_POST['subscriptionIdForStripe'] = "";
3527 $_POST['enableSubscriptionForStripe'] = 0;
3528 $_POST['termsOfServiceForSubscription'] = "";
3529 $_POST['enableTermsOfServiceForSubscription'] = 0;
3530 $_POST['privacyPolicyForSubscription'] = "";
3531 $_POST['enablePrivacyPolicyForSubscription'] = 0;
3532
3533 }
3534
3535 if (!isset($_POST['displayRemainingCapacityInCalendar'])) {
3536
3537 $_POST['displayRemainingCapacityInCalendar'] = 0;
3538 $_POST['displayThresholdOfRemainingCapacity'] = 50;
3539 $_POST['displayRemainingCapacityHasMoreThenThreshold'] = "";
3540 $_POST['displayRemainingCapacityHasLessThenThreshold'] = "";
3541 $_POST['displayRemainingCapacityHas0'] = "";
3542
3543 }
3544
3545 if (!isset($_POST['cancellationOfBooking'])) {
3546
3547 $_POST['cancellationOfBooking'] = 0;
3548 $_POST['allowCancellationVisitor'] = 0;
3549 $_POST['allowCancellationUser'] = 0;
3550 $_POST['refuseCancellationOfBooking'] = "not_refuse";
3551
3552 }
3553
3554 if (!isset($_POST['preparationTime'])) {
3555
3556 $_POST['preparationTime'] = 0;
3557 $_POST['positionPreparationTime'] = 'before_after';
3558
3559 }
3560
3561 $pages = array('servicesPage', 'calenarPage', 'schedulesPage', 'visitorDetailsPage', 'confirmDetailsPage', 'thanksPage', 'redirectPage');
3562 for ($i = 0; $i < count($pages); $i++) {
3563
3564 $page = $pages[$i];
3565 if (intval( $_POST[$page] ) != 0) {
3566
3567 $_POST[$page] = intval( $_POST[$page] );
3568
3569 } else {
3570
3571 $_POST[$page] = null;
3572
3573 }
3574
3575 }
3576
3577 $limitNumberOfGuests = array(
3578 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3579 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3580 );
3581
3582 if (isset($_POST['minimumGuests'])) {
3583
3584 $limitNumberOfGuests['minimumGuests']['enabled'] = intval($_POST['minimumGuests']);
3585 $limitNumberOfGuests['minimumGuests']['included'] = intval($_POST['minimumGuestsRequiredNo']);
3586 $limitNumberOfGuests['minimumGuests']['number'] = intval($_POST['minimumGuestsOfValue']);
3587
3588 }
3589
3590 if (isset($_POST['maximumGuests'])) {
3591
3592 $limitNumberOfGuests['maximumGuests']['enabled'] = intval($_POST['maximumGuests']);
3593 $limitNumberOfGuests['maximumGuests']['included'] = intval($_POST['maximumGuestsRequiredNo']);
3594 $limitNumberOfGuests['maximumGuests']['number'] = intval($_POST['maximumGuestsOfValue']);
3595
3596 }
3597
3598 $_POST['displayRemainingCapacityHasMoreThenThreshold'] = stripslashes($_POST['displayRemainingCapacityHasMoreThenThreshold']);
3599 $_POST['displayRemainingCapacityHasLessThenThreshold'] = stripslashes($_POST['displayRemainingCapacityHasLessThenThreshold']);
3600 $_POST['displayRemainingCapacityHas0'] = stripslashes($_POST['displayRemainingCapacityHas0']);
3601
3602 $maxBookingSlotsPerDay = $this->updateMaxBookingSlotsPerDay('add', '[]');
3603
3604 $isExtensionsValid = $this->getExtensionsValid();
3605 $hotelCharges = array(
3606 'hotelChargeOnSunday',
3607 'hotelChargeOnMonday',
3608 'hotelChargeOnTuesday',
3609 'hotelChargeOnWednesday',
3610 'hotelChargeOnThursday',
3611 'hotelChargeOnFriday',
3612 'hotelChargeOnSaturday',
3613 'hotelChargeOnDayBeforeNationalHoliday',
3614 'hotelChargeOnNationalHoliday',
3615 );
3616
3617 for ($i = 0; $i < count($hotelCharges); $i++) {
3618
3619 $holidayKey = $hotelCharges[$i];
3620 if (isset($_POST[$holidayKey]) === false) {
3621
3622 $_POST[$holidayKey] = $_POST['cost'];
3623
3624 }
3625
3626 }
3627
3628 if ($isExtensionsValid == false) {
3629
3630 $_POST['hasMultipleServices'] = 0;
3631 $_POST['displayRemainingCapacity'] = 0;
3632 $_POST['enableSubscriptionForStripe'] = 0;
3633 $_POST['cancellationOfBooking'] = 0;
3634 $_POST['allowCancellationVisitor'] = 0;
3635 $_POST['allowCancellationUser'] = 0;
3636 $_POST['refuseCancellationOfBooking'] = "not_refuse";
3637 $_POST['preparationTime'] = 0;
3638 $_POST['positionPreparationTime'] = 'before_after';
3639 $_POST['hotelChargeOnDayBeforeNationalHoliday'] = 0;
3640 $_POST['hotelChargeOnNationalHoliday'] = 0;
3641 $_POST['maximumNights'] = 0;
3642 $_POST['minimumNights'] = 0;
3643 $_POST['schedulesSharing'] = 0;
3644 $_POST['targetSchedules'] = 0;
3645 $_POST['blockSameTimeBookingByUser'] = 0;
3646 $_POST['bookingVerificationCode'] = 'false';
3647 $_POST['bookingVerificationCodeToUser'] = 'false';
3648 $_POST['bookingReminder'] = 60;
3649 $_POST['insertConfirmedPage'] = 0;
3650 $_POST['autoPublish'] = 0;
3651 $limitNumberOfGuests = array(
3652 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3653 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
3654 );
3655
3656 } else {
3657
3658 $_POST['maximumNights'] = $this->getOnlyNumbers($_POST['maximumNights']);
3659 $_POST['minimumNights'] = $this->getOnlyNumbers($_POST['minimumNights']);
3660
3661 }
3662
3663 $_POST['numberOfRoomsAvailable'] = $this->getOnlyNumbers($_POST['numberOfRoomsAvailable']);
3664 $_POST['numberOfPeopleInRoom'] = $this->getOnlyNumbers($_POST['numberOfPeopleInRoom']);
3665 $_POST['maxAccountScheduleDay'] = $this->getOnlyNumbers($_POST['maxAccountScheduleDay']);
3666
3667 $date = date('U');
3668 global $wpdb;
3669 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3670
3671 $wpdb->insert(
3672 $table_name,
3673 array(
3674 'name' => sanitize_text_field( wp_unslash( $_POST['name'] ) ),
3675 'type' => sanitize_text_field($_POST['type']),
3676 'status' => sanitize_text_field($_POST['status']),
3677 'courseTitle' => sanitize_text_field( __('Service', 'booking-package') ),
3678 'courseBool' => intval($_POST['courseBool']),
3679 'created' => sanitize_text_field($date),
3680 'uploadDate' => sanitize_text_field($date),
3681 'cost' => intval($_POST['cost']),
3682 'numberOfRoomsAvailable' => intval($_POST['numberOfRoomsAvailable']),
3683 'numberOfPeopleInRoom' => intval($_POST['numberOfPeopleInRoom']),
3684 'includeChildrenInRoom' => intval($_POST['includeChildrenInRoom']),
3685 'expressionsCheck' => intval($_POST['expressionsCheck']),
3686 'monthForFixCalendar' => intval($_POST['monthForFixCalendar']),
3687 'yearForFixCalendar' => intval($_POST['yearForFixCalendar']),
3688 'enableFixCalendar' => intval($_POST['enableFixCalendar']),
3689 'displayRemainingCapacity' => intval($_POST['displayRemainingCapacity']),
3690 'maxAccountScheduleDay' => intval($_POST['maxAccountScheduleDay']),
3691 'unavailableDaysFromToday' => intval($_POST['unavailableDaysFromToday']),
3692 'subscriptionIdForStripe' => sanitize_text_field($_POST['subscriptionIdForStripe']),
3693 'enableSubscriptionForStripe' => intval($_POST['enableSubscriptionForStripe']),
3694 'termsOfServiceForSubscription' => esc_url($_POST['termsOfServiceForSubscription']),
3695 'enableTermsOfServiceForSubscription' => intval($_POST['enableTermsOfServiceForSubscription']),
3696 'privacyPolicyForSubscription' => esc_url($_POST['privacyPolicyForSubscription']),
3697 'enablePrivacyPolicyForSubscription' => intval($_POST['enablePrivacyPolicyForSubscription']),
3698 'displayRemainingCapacityInCalendar' => intval($_POST['displayRemainingCapacityInCalendar']),
3699 'displayThresholdOfRemainingCapacity' => intval($_POST['displayThresholdOfRemainingCapacity']),
3700 'displayRemainingCapacityHasMoreThenThreshold' => sanitize_text_field($_POST['displayRemainingCapacityHasMoreThenThreshold']),
3701 'displayRemainingCapacityHasLessThenThreshold' => sanitize_text_field($_POST['displayRemainingCapacityHasLessThenThreshold']),
3702 'displayRemainingCapacityHas0' => sanitize_text_field($_POST['displayRemainingCapacityHas0']),
3703 'icalToken' => hash('ripemd160', date('U')),
3704 'cancellationOfBooking' => intval($_POST['cancellationOfBooking']),
3705 'allowCancellationVisitor' => intval($_POST['allowCancellationVisitor']),
3706 'allowCancellationUser' => intval($_POST['allowCancellationUser']),
3707 'refuseCancellationOfBooking' => sanitize_text_field($_POST['refuseCancellationOfBooking']),
3708 'preparationTime' => intval($_POST['preparationTime']),
3709 'positionPreparationTime' => sanitize_text_field($_POST['positionPreparationTime']),
3710 'displayDetailsOfCanceled' => intval($_POST['displayDetailsOfCanceled']),
3711 'timezone' => sanitize_text_field($_POST['timezone']),
3712 'displayRemainingCapacityInCalendarAsNumber' => intval($_POST['displayRemainingCapacityInCalendarAsNumber']),
3713 'hasMultipleServices' => intval($_POST['hasMultipleServices']),
3714 'flowOfBooking' => sanitize_text_field($_POST['flowOfBooking']),
3715 'paymentMethod' => sanitize_text_field($_POST['paymentMethod']),
3716 'email_from' => sanitize_text_field(trim($_POST['email_from'])),
3717 'email_to' => sanitize_text_field(trim($_POST['email_to'])),
3718 'email_from_title' => sanitize_text_field( wp_unslash( trim( $_POST['email_from_title'] ) ) ),
3719 'servicesPage' => $_POST['servicesPage'],
3720 'calenarPage' => $_POST['calenarPage'],
3721 'schedulesPage' => $_POST['schedulesPage'],
3722 'visitorDetailsPage' => $_POST['visitorDetailsPage'],
3723 'thanksPage' => $_POST['thanksPage'],
3724 'redirectPage' => $_POST['redirectPage'],
3725 'hotelChargeOnSunday' => intval($_POST['hotelChargeOnSunday']),
3726 'hotelChargeOnMonday' => intval($_POST['hotelChargeOnMonday']),
3727 'hotelChargeOnTuesday' => intval($_POST['hotelChargeOnTuesday']),
3728 'hotelChargeOnWednesday' => intval($_POST['hotelChargeOnWednesday']),
3729 'hotelChargeOnThursday' => intval($_POST['hotelChargeOnThursday']),
3730 'hotelChargeOnFriday' => intval($_POST['hotelChargeOnFriday']),
3731 'hotelChargeOnSaturday' => intval($_POST['hotelChargeOnSaturday']),
3732 'hotelChargeOnDayBeforeNationalHoliday' => intval($_POST['hotelChargeOnDayBeforeNationalHoliday']),
3733 'hotelChargeOnNationalHoliday' => intval($_POST['hotelChargeOnNationalHoliday']),
3734 'maximumNights' => intval($_POST['maximumNights']),
3735 'minimumNights' => intval($_POST['minimumNights']),
3736 'schedulesSharing' => intval($_POST['schedulesSharing']),
3737 'targetSchedules' => intval($_POST['targetSchedules']),
3738 'multipleRooms' => intval($_POST['multipleRooms']),
3739 'redirectURL' => sanitize_text_field($_POST['redirectURL']),
3740 'redirectMode' => sanitize_text_field($_POST['redirectMode']),
3741 'guestsBool' => intval(1),
3742 'limitNumberOfGuests' => sanitize_text_field( json_encode($limitNumberOfGuests) ),
3743 'blockSameTimeBookingByUser' => intval($_POST['blockSameTimeBookingByUser']),
3744 'bookingVerificationCode' => sanitize_text_field($_POST['bookingVerificationCode']),
3745 'bookingVerificationCodeToUser' => sanitize_text_field($_POST['bookingVerificationCodeToUser']),
3746 'bookingReminder' => intval($_POST['bookingReminder']),
3747 'insertConfirmedPage' => intval($_POST['insertConfirmedPage']),
3748 'confirmDetailsPage' => $_POST['confirmDetailsPage'],
3749 'formatNightDay' => intval($_POST['formatNightDay']),
3750 'messagingService' => sanitize_text_field($messagingService),
3751 'autoPublish' => intval($_POST['autoPublish']),
3752 'maxBookingSlotsPerDay' => sanitize_text_field( json_encode($maxBookingSlotsPerDay) ),
3753 ),
3754 array(
3755 '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%d', '%d',
3756 '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%d',
3757 '%s', '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%s', '%s',
3758 '%d', '%d', '%d', '%s', '%d', '%s', '%d', '%s', '%d', '%d',
3759 '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d',
3760 '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d',
3761 '%d', '%d', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%d',
3762 '%s', '%s', '%d', '%d', '%d', '%d', '%s', '%d', '%s',
3763 )
3764 );
3765
3766 $accountKey = $wpdb->insert_id;
3767 $this->addGuests($accountKey, $_POST['type']);
3768 if ($_POST['type'] == 'hotel') {
3769
3770 $this->insertAccountSchedule(date('m'), date('d'), date('Y'), $accountKey);
3771
3772 }
3773
3774 do_action('booking_package_add_calendar_account', $accountKey);
3775 return array('getCalendarAccountListData' => $this->getCalendarAccountListData(), 'accountKey' => $accountKey);
3776
3777 }
3778
3779 public function createCloneCalendar() {
3780
3781 global $wpdb;
3782 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3783 $tmp_table_name = $table_name."_tmp";
3784 #$sql = "CREATE TEMPORARY TABLE " . $tmp_table_name . " FROM " . $table_name . " WHERE `key` = %d;";
3785 $sql = $wpdb->prepare("CREATE TEMPORARY TABLE " . $tmp_table_name . " SELECT * FROM " . $table_name . " WHERE `key` = %d;", array(intval($_POST['accountKey'])));
3786 $wpdb->query($sql);
3787 $wpdb->query("ALTER TABLE " . $tmp_table_name . " drop `key`;");
3788 $wpdb->query("INSERT INTO " . $table_name . " SELECT 0," . $tmp_table_name . ".* FROM " . $tmp_table_name . ";");
3789 $wpdb->query("DROP TABLE " . $tmp_table_name . ";");
3790 $accountKey = $wpdb->insert_id;
3791
3792 $targetList = array(
3793 'schedules' => 'booking_package_template_schedules',
3794 'form' => 'booking_package_form',
3795 'services' => 'booking_package_services',
3796 'guests' => 'booking_package_guests',
3797 'taxes' => 'booking_package_taxes',
3798 'emails' => 'booking_package_email_settings',
3799 'subscriptions' => 'booking_package_subscriptions'
3800 );
3801
3802 foreach ((array) $targetList as $key => $table) {
3803
3804 if (isset($_POST[$key]) && intval($_POST[$key]) == 1) {
3805
3806 $table_name = $wpdb->prefix.$table;
3807 $tmp_table_name = $table_name."_tmp";
3808 $sql = $wpdb->prepare("CREATE TEMPORARY TABLE " . $tmp_table_name . " SELECT * FROM " . $table_name . " WHERE `accountKey` = %d;", array(intval($_POST['accountKey'])));
3809 $wpdb->query($sql);
3810 $wpdb->query("ALTER TABLE " . $tmp_table_name . " drop `key`;");
3811 $wpdb->query("UPDATE " . $tmp_table_name . " SET `accountKey` = " . $accountKey . ";");
3812 $wpdb->query("INSERT INTO " . $table_name . " SELECT 0," . $tmp_table_name . ".* FROM " . $tmp_table_name . ";");
3813 $wpdb->query("DROP TABLE " . $tmp_table_name . ";");
3814
3815 }
3816
3817 }
3818
3819 do_action('booking_package_add_clone_calendar_account', $accountKey);
3820 return $this->getCalendarAccountListData();
3821
3822 }
3823
3824 public function getIcalToken($accountKey){
3825
3826 $calendarAccount = $this->getCalendarAccount($accountKey);
3827 return array("status" => "success", "ical" => $calendarAccount['ical'], "syncPastCustomersForIcal" => $calendarAccount['syncPastCustomersForIcal'], "icalToken" => $calendarAccount['icalToken'], 'home' => get_home_url());
3828
3829 }
3830
3831 public function updateIcalToken(){
3832
3833 if (isset($_POST['accountKey']) && isset($_POST['ical'])) {
3834
3835 global $wpdb;
3836 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3837 try {
3838
3839 $wpdb->query("START TRANSACTION");
3840 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
3841 $bool = $wpdb->update(
3842 $table_name,
3843 array(
3844 'ical' => intval($_POST['ical']),
3845 'syncPastCustomersForIcal' => intval($_POST['syncPastCustomersForIcal']),
3846 ),
3847 array('key' => intval($_POST['accountKey'])),
3848 array('%d', '%d'),
3849 array('%d')
3850 );
3851 $wpdb->query('COMMIT');
3852 $wpdb->query('UNLOCK TABLES');
3853
3854 } catch (Exception $e) {
3855
3856 $wpdb->query('ROLLBACK');
3857 $wpdb->query('UNLOCK TABLES');
3858
3859 }/** finally {
3860
3861 $wpdb->query('UNLOCK TABLES');
3862
3863 }**/
3864
3865 return array('status' => 'success', 'key' => $_POST['accountKey']);
3866
3867 } else {
3868
3869 return array('status' => 'error', 'key' => $_POST['accountKey']);
3870
3871 }
3872
3873
3874 }
3875
3876 public function refreshIcalToken($key, $home = false){
3877
3878 $key = intval($key);
3879 $token = hash('ripemd160', date('U').$key);
3880 global $wpdb;
3881 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
3882 try {
3883
3884 $wpdb->query("START TRANSACTION");
3885 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
3886 $bool = $wpdb->update(
3887 $table_name,
3888 array(
3889 'icalToken' => $token,
3890 ),
3891 array('key' => $key),
3892 array('%s'),
3893 array('%d')
3894 );
3895 $wpdb->query('COMMIT');
3896 $wpdb->query('UNLOCK TABLES');
3897
3898 } catch (Exception $e) {
3899
3900 $wpdb->query('ROLLBACK');
3901 $wpdb->query('UNLOCK TABLES');
3902
3903 }/** finally {
3904
3905 $wpdb->query('UNLOCK TABLES');
3906
3907 }**/
3908
3909 return array('status' => 'success', 'token' => $token, 'key' => $key);
3910
3911 }
3912
3913 public function updateCalendarAccount(){
3914
3915 $deleteSchedules = false;
3916 $postList = array('cost' => 0, 'numberOfRoomsAvailable' => 1, 'numberOfPeopleInRoom' => 2, 'includeChildrenInRoom' => 0);
3917 foreach ((array) $postList as $key => $value) {
3918
3919 if (!isset($_POST[$key])) {
3920
3921 $_POST[$key] = $value;
3922
3923 }
3924
3925 }
3926
3927 if (isset($_POST['displayRemainingSlotsInCalendar']) === true) {
3928
3929 $_POST['displayRemainingCapacityInCalendar'] = 0;
3930 $_POST['displayRemainingCapacityInCalendarAsNumber'] = 0;
3931 if ($_POST['displayRemainingSlotsInCalendar'] == 'int') {
3932
3933 $_POST['displayRemainingCapacityInCalendar'] = 1;
3934 $_POST['displayRemainingCapacityInCalendarAsNumber'] = 1;
3935
3936 } else if ($_POST['displayRemainingSlotsInCalendar'] == 'text') {
3937
3938 $_POST['displayRemainingCapacityInCalendar'] = 1;
3939
3940 }
3941
3942 }
3943
3944 $defaultKeys = array('timezone' => 'none', 'blockSameTimeBookingByUser' => 0, 'allowCancellationUser' => 0, 'bookingReminder' => 60, 'insertConfirmedPage' => 0, 'autoPublish' => 0, 'flowOfBooking' => 'calendar', 'multipleRooms' => 0, 'bookingVerificationCode' => 'false', 'bookingVerificationCodeToUser' => 'false', 'type' => 'day');
3945 foreach ($defaultKeys as $key => $value) {
3946
3947 if (array_key_exists($key, $_POST) === false) {
3948
3949 $_POST[$key] = $value;
3950
3951 }
3952
3953 }
3954
3955 $calendarAccount = $this->getCalendarAccount($_POST['accountKey']);
3956
3957 $messagingService = $calendarAccount['messagingService'];
3958 if (array_key_exists('messagingService', $_POST) === true) {
3959
3960 $messagingService = $_POST['messagingService'];
3961
3962 }
3963
3964 if ($_POST['timezone'] != 'none' && $_POST['timezone'] != $calendarAccount['timezone']) {
3965
3966 $this->updateUnixTimeOnBookingData($_POST['accountKey'], $_POST['timezone']);
3967
3968 }
3969
3970 if (!isset($_POST['enableSubscriptionForStripe'])) {
3971
3972 $_POST['subscriptionIdForStripe'] = "";
3973 $_POST['enableSubscriptionForStripe'] = 0;
3974 $_POST['termsOfServiceForSubscription'] = "";
3975 $_POST['enableTermsOfServiceForSubscription'] = 0;
3976 $_POST['privacyPolicyForSubscription'] = "";
3977 $_POST['enablePrivacyPolicyForSubscription'] = 0;
3978
3979 }
3980
3981 if (!isset($_POST['displayRemainingCapacityInCalendar'])) {
3982
3983 $_POST['displayRemainingCapacityInCalendar'] = 0;
3984 $_POST['displayThresholdOfRemainingCapacity'] = 50;
3985 $_POST['displayRemainingCapacityHasMoreThenThreshold'] = "";
3986 $_POST['displayRemainingCapacityHasLessThenThreshold'] = "";
3987 $_POST['displayRemainingCapacityHas0'] = "";
3988
3989 }
3990
3991 if (!isset($_POST['cancellationOfBooking'])) {
3992
3993 $_POST['cancellationOfBooking'] = 0;
3994 $_POST['allowCancellationVisitor'] = 0;
3995 $_POST['allowCancellationUser'] = 0;
3996 $_POST['refuseCancellationOfBooking'] = "not_refuse";
3997
3998 }
3999
4000 if (!isset($_POST['preparationTime'])) {
4001
4002 $_POST['preparationTime'] = 0;
4003 $_POST['positionPreparationTime'] = 'before_after';
4004
4005 }
4006
4007 $pages = array('servicesPage', 'calenarPage', 'schedulesPage', 'visitorDetailsPage', 'confirmDetailsPage', 'thanksPage', 'redirectPage');
4008 for ($i = 0; $i < count($pages); $i++) {
4009
4010 $page = $pages[$i];
4011 if (intval( $_POST[$page] ) != 0) {
4012
4013 $_POST[$page] = intval( $_POST[$page] );
4014
4015 } else {
4016
4017 $_POST[$page] = null;
4018
4019 }
4020
4021 }
4022
4023 $limitNumberOfGuests = array(
4024 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
4025 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
4026 );
4027
4028 if (isset($_POST['minimumGuests'])) {
4029
4030 $limitNumberOfGuests['minimumGuests']['enabled'] = intval($_POST['minimumGuests']);
4031 $limitNumberOfGuests['minimumGuests']['included'] = intval($_POST['minimumGuestsRequiredNo']);
4032 $limitNumberOfGuests['minimumGuests']['number'] = intval($_POST['minimumGuestsOfValue']);
4033
4034 }
4035
4036 if (isset($_POST['maximumGuests'])) {
4037
4038 $limitNumberOfGuests['maximumGuests']['enabled'] = intval($_POST['maximumGuests']);
4039 $limitNumberOfGuests['maximumGuests']['included'] = intval($_POST['maximumGuestsRequiredNo']);
4040 $limitNumberOfGuests['maximumGuests']['number'] = intval($_POST['maximumGuestsOfValue']);
4041
4042 }
4043
4044 $_POST['displayRemainingCapacityHasMoreThenThreshold'] = stripslashes($_POST['displayRemainingCapacityHasMoreThenThreshold']);
4045 $_POST['displayRemainingCapacityHasLessThenThreshold'] = stripslashes($_POST['displayRemainingCapacityHasLessThenThreshold']);
4046 $_POST['displayRemainingCapacityHas0'] = stripslashes($_POST['displayRemainingCapacityHas0']);
4047 $maxBookingSlotsPerDay = $this->updateMaxBookingSlotsPerDay('add', '[]');
4048
4049 $isExtensionsValid = $this->getExtensionsValid();
4050 $hotelCharges = array(
4051 'hotelChargeOnSunday',
4052 'hotelChargeOnMonday',
4053 'hotelChargeOnTuesday',
4054 'hotelChargeOnWednesday',
4055 'hotelChargeOnThursday',
4056 'hotelChargeOnFriday',
4057 'hotelChargeOnSaturday',
4058 'hotelChargeOnDayBeforeNationalHoliday',
4059 'hotelChargeOnNationalHoliday',
4060 );
4061
4062 for ($i = 0; $i < count($hotelCharges); $i++) {
4063
4064 $holidayKey = $hotelCharges[$i];
4065 if (isset($_POST[$holidayKey]) === false) {
4066
4067 $_POST[$holidayKey] = $_POST['cost'];
4068
4069 }
4070
4071 }
4072
4073 if ($isExtensionsValid === false) {
4074
4075 $_POST['hasMultipleServices'] = 0;
4076 $_POST['displayRemainingCapacity'] = 0;
4077 $_POST['enableSubscriptionForStripe'] = 0;
4078 $_POST['cancellationOfBooking'] = 0;
4079 $_POST['allowCancellationVisitor'] = 0;
4080 $_POST['allowCancellationUser'] = 0;
4081 $_POST['refuseCancellationOfBooking'] = "not_refuse";
4082 $_POST['preparationTime'] = 0;
4083 $_POST['positionPreparationTime'] = 'before_after';
4084 $_POST['hotelChargeOnDayBeforeNationalHoliday'] = 0;
4085 $_POST['hotelChargeOnNationalHoliday'] = 0;
4086 $_POST['maximumNights'] = 0;
4087 $_POST['minimumNights'] = 0;
4088 $_POST['blockSameTimeBookingByUser'] = 0;
4089 $_POST['bookingVerificationCode'] = 'false';
4090 $_POST['bookingVerificationCodeToUser'] = 'false';
4091 $_POST['bookingReminder'] = 60;
4092 $_POST['insertConfirmedPage'] = 0;
4093 $limitNumberOfGuests = array(
4094 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
4095 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
4096 );
4097
4098 } else {
4099
4100 $_POST['maximumNights'] = $this->getOnlyNumbers($_POST['maximumNights']);
4101 $_POST['minimumNights'] = $this->getOnlyNumbers($_POST['minimumNights']);
4102
4103 }
4104
4105 $_POST['numberOfRoomsAvailable'] = $this->getOnlyNumbers($_POST['numberOfRoomsAvailable']);
4106 $_POST['numberOfPeopleInRoom'] = $this->getOnlyNumbers($_POST['numberOfPeopleInRoom']);
4107
4108 $date = date('U');
4109 global $wpdb;
4110 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
4111
4112 try {
4113
4114 $wpdb->query("START TRANSACTION");
4115 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
4116 $bool = $wpdb->update(
4117 $table_name,
4118 array(
4119 'name' => sanitize_text_field( wp_unslash( $_POST['name'] ) ),
4120 'status' => sanitize_text_field($_POST['status']),
4121 'courseTitle' => sanitize_text_field( __('Service', 'booking-package') ),
4122 'courseBool' => intval($_POST['courseBool']),
4123 'uploadDate' => date('U'),
4124 'cost' => intval($_POST['cost']),
4125 'numberOfRoomsAvailable' => intval($_POST['numberOfRoomsAvailable']),
4126 'numberOfPeopleInRoom' => intval($_POST['numberOfPeopleInRoom']),
4127 'includeChildrenInRoom' => intval($_POST['includeChildrenInRoom']),
4128 'expressionsCheck' => intval($_POST['expressionsCheck']),
4129 'monthForFixCalendar' => intval($_POST['monthForFixCalendar']),
4130 'yearForFixCalendar' => intval($_POST['yearForFixCalendar']),
4131 'maxAccountScheduleDay' => intval($_POST['maxAccountScheduleDay']),
4132 'unavailableDaysFromToday' => intval($_POST['unavailableDaysFromToday']),
4133 'enableFixCalendar' => intval($_POST['enableFixCalendar']),
4134 'displayRemainingCapacity' => intval($_POST['displayRemainingCapacity']),
4135 'subscriptionIdForStripe' => sanitize_text_field($_POST['subscriptionIdForStripe']),
4136 'enableSubscriptionForStripe' => intval($_POST['enableSubscriptionForStripe']),
4137 'termsOfServiceForSubscription' => esc_url($_POST['termsOfServiceForSubscription']),
4138 'enableTermsOfServiceForSubscription' => intval($_POST['enableTermsOfServiceForSubscription']),
4139 'privacyPolicyForSubscription' => esc_url($_POST['privacyPolicyForSubscription']),
4140 'enablePrivacyPolicyForSubscription' => intval($_POST['enablePrivacyPolicyForSubscription']),
4141 'displayRemainingCapacityInCalendar' => intval($_POST['displayRemainingCapacityInCalendar']),
4142 'displayThresholdOfRemainingCapacity' => intval($_POST['displayThresholdOfRemainingCapacity']),
4143 'displayRemainingCapacityHasMoreThenThreshold' => sanitize_text_field($_POST['displayRemainingCapacityHasMoreThenThreshold']),
4144 'displayRemainingCapacityHasLessThenThreshold' => sanitize_text_field($_POST['displayRemainingCapacityHasLessThenThreshold']),
4145 'displayRemainingCapacityHas0' => sanitize_text_field($_POST['displayRemainingCapacityHas0']),
4146 'startOfWeek' => intval($_POST['startOfWeek']),
4147 'cancellationOfBooking' => intval($_POST['cancellationOfBooking']),
4148 'allowCancellationVisitor' => intval($_POST['allowCancellationVisitor']),
4149 'allowCancellationUser' => intval($_POST['allowCancellationUser']),
4150 'refuseCancellationOfBooking' => sanitize_text_field($_POST['refuseCancellationOfBooking']),
4151 'preparationTime' => intval($_POST['preparationTime']),
4152 'positionPreparationTime' => sanitize_text_field($_POST['positionPreparationTime']),
4153 'displayDetailsOfCanceled' => intval($_POST['displayDetailsOfCanceled']),
4154 'displayRemainingCapacityInCalendarAsNumber' => intval($_POST['displayRemainingCapacityInCalendarAsNumber']),
4155 'hasMultipleServices' => intval($_POST['hasMultipleServices']),
4156 'flowOfBooking' => sanitize_text_field($_POST['flowOfBooking']),
4157 'paymentMethod' => sanitize_text_field($_POST['paymentMethod']),
4158 'email_from' => sanitize_text_field(trim($_POST['email_from'])),
4159 'email_to' => sanitize_text_field(trim($_POST['email_to'])),
4160 'email_from_title' => sanitize_text_field( wp_unslash( trim( $_POST['email_from_title'] ) ) ),
4161 'servicesPage' => $_POST['servicesPage'],
4162 'calenarPage' => $_POST['calenarPage'],
4163 'schedulesPage' => $_POST['schedulesPage'],
4164 'visitorDetailsPage' => $_POST['visitorDetailsPage'],
4165 'thanksPage' => $_POST['thanksPage'],
4166 'redirectPage' => $_POST['redirectPage'],
4167 'hotelChargeOnSunday' => intval($_POST['hotelChargeOnSunday']),
4168 'hotelChargeOnMonday' => intval($_POST['hotelChargeOnMonday']),
4169 'hotelChargeOnTuesday' => intval($_POST['hotelChargeOnTuesday']),
4170 'hotelChargeOnWednesday' => intval($_POST['hotelChargeOnWednesday']),
4171 'hotelChargeOnThursday' => intval($_POST['hotelChargeOnThursday']),
4172 'hotelChargeOnFriday' => intval($_POST['hotelChargeOnFriday']),
4173 'hotelChargeOnSaturday' => intval($_POST['hotelChargeOnSaturday']),
4174 'hotelChargeOnDayBeforeNationalHoliday' => intval($_POST['hotelChargeOnDayBeforeNationalHoliday']),
4175 'hotelChargeOnNationalHoliday' => intval($_POST['hotelChargeOnNationalHoliday']),
4176 'maximumNights' => intval($_POST['maximumNights']),
4177 'minimumNights' => intval($_POST['minimumNights']),
4178 'multipleRooms' => intval($_POST['multipleRooms']),
4179 'redirectURL' => sanitize_text_field($_POST['redirectURL']),
4180 'redirectMode' => sanitize_text_field($_POST['redirectMode']),
4181 'limitNumberOfGuests' => sanitize_text_field( json_encode($limitNumberOfGuests) ),
4182 'blockSameTimeBookingByUser' => intval($_POST['blockSameTimeBookingByUser']),
4183 'bookingVerificationCode' => sanitize_text_field($_POST['bookingVerificationCode']),
4184 'bookingVerificationCodeToUser' => sanitize_text_field($_POST['bookingVerificationCodeToUser']),
4185 'bookingReminder' => intval($_POST['bookingReminder']),
4186 'insertConfirmedPage' => intval($_POST['insertConfirmedPage']),
4187 'confirmDetailsPage' => $_POST['confirmDetailsPage'],
4188 'formatNightDay' => intval($_POST['formatNightDay']),
4189 'messagingService' => sanitize_text_field($messagingService),
4190 'autoPublish' => intval($_POST['autoPublish']),
4191 'maxBookingSlotsPerDay' => sanitize_text_field( json_encode($maxBookingSlotsPerDay) ),
4192 ),
4193 array('key' => intval($_POST['accountKey'])),
4194 array(
4195 '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d',
4196 '%d', '%d', '%d', '%d', '%s', '%d', '%s', '%d', '%s', '%d',
4197 '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d',
4198 '%d', '%s', '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%s',
4199 '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d',
4200 '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d',
4201 '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%d', '%d', '%d',
4202 '%s', '%d', '%s',
4203 ),
4204 array('%d')
4205 );
4206
4207 $wpdb->query('COMMIT');
4208 $wpdb->query('UNLOCK TABLES');
4209
4210 } catch (Exception $e) {
4211
4212 $wpdb->query('ROLLBACK');
4213 $wpdb->query('UNLOCK TABLES');
4214
4215 }/** finally {
4216
4217 $wpdb->query('UNLOCK TABLES');
4218
4219 }**/
4220
4221 if ($bool === 1) {
4222
4223 return $this->getCalendarAccountListData();
4224
4225 } else {
4226
4227 return array("status" => $bool);
4228
4229 }
4230
4231 }
4232
4233 public function updateAccountFunction($accountKey, $name, $value) {
4234
4235 $date = date('U');
4236 global $wpdb;
4237 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
4238 try {
4239
4240 $wpdb->query("START TRANSACTION");
4241 #$wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
4242 $bool = $wpdb->update(
4243 $table_name,
4244 array(
4245 sanitize_text_field($name) => intval($value),
4246 'uploadDate' => date('U'),
4247 ),
4248 array('key' => intval($accountKey)),
4249 array(
4250 '%d', '%d'
4251 ),
4252 array('%d')
4253 );
4254
4255 $wpdb->query('COMMIT');
4256 #$wpdb->query('UNLOCK TABLES');
4257
4258 } catch (Exception $e) {
4259
4260 $wpdb->query('ROLLBACK');
4261 #$wpdb->query('UNLOCK TABLES');
4262
4263 }/** finally {
4264
4265 $wpdb->query('UNLOCK TABLES');
4266
4267 }**/
4268
4269 return $this->getCalendarAccountListData();
4270
4271 }
4272
4273 public function updateUnixTimeOnBookingData($accountKey = null, $timezone = null) {
4274
4275 if (is_null($accountKey)) {
4276
4277 return false;
4278
4279 }
4280
4281 #var_dump($timezone);
4282 if (date_default_timezone_set($timezone)) {
4283
4284 global $wpdb;
4285 $table_name = $wpdb->prefix . "booking_package_schedules";
4286 $sql = $wpdb->prepare("SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `status` = 'open';", array($accountKey));
4287 $rows = $wpdb->get_results($sql, ARRAY_A);
4288 foreach ((array) $rows as $row) {
4289
4290 $unixTime = date('U', mktime($row['hour'], $row['min'], 0, $row['month'], $row['day'], $row['year']));
4291 $bool = $wpdb->update(
4292 $table_name,
4293 array(
4294 'unixTime' => intval($unixTime),
4295 ),
4296 array('key' => intval($row['key'])),
4297 array('%d'),
4298 array('%d')
4299 );
4300
4301 $table_userPraivateData = $wpdb->prefix . "booking_package_booked_customers";
4302 $bool = $wpdb->update(
4303 $table_userPraivateData,
4304 array(
4305 'scheduleUnixTime' => intval($unixTime),
4306 ),
4307 array('scheduleKey' => intval($row['key'])),
4308 array('%d'),
4309 array('%d')
4310 );
4311
4312 }
4313
4314 return true;
4315
4316 }
4317
4318 return false;
4319
4320 }
4321
4322 public function updateCalendarAccountForGoogleWebhook($accountKey, $idForGoogleWebhook, $expirationForGoogleWebhook){
4323
4324 global $wpdb;
4325 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
4326
4327 $bool = $wpdb->update(
4328 $table_name,
4329 array(
4330 'idForGoogleWebhook' => sanitize_text_field($idForGoogleWebhook),
4331 'expirationForGoogleWebhook' => sanitize_text_field($expirationForGoogleWebhook)
4332 ),
4333 array('key' => intval($accountKey)),
4334 array('%s', '%s', '%s'),
4335 array('%d')
4336 );
4337
4338 if($bool === 1){
4339
4340 $key = $this->prefix."id_for_google_webhook";
4341 if(get_option($key) === false){
4342
4343 add_option($key, sanitize_text_field($idForGoogleWebhook));
4344
4345 }else{
4346
4347 update_option($key, sanitize_text_field($idForGoogleWebhook));
4348
4349 }
4350
4351 return $this->getCalendarAccountListData();
4352
4353 }else{
4354
4355 return array("status" => $bool);
4356
4357 }
4358
4359
4360 }
4361
4362
4363
4364 public function lookingForGoogleCalendarId($googleCalendarId = false){
4365
4366 global $wpdb;
4367 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
4368 if($googleCalendarId != false){
4369
4370 $sql = $wpdb->prepare(
4371 "SELECT `key`,`type`,`googleCalendarID`,`idForGoogleWebhook`,`expirationForGoogleWebhook` FROM ".$table_name." WHERE `idForGoogleWebhook` = %s;",
4372 array(sanitize_text_field($googleCalendarId))
4373 );
4374 $row = $wpdb->get_row($sql, ARRAY_A);
4375 if(strlen($row['type']) == 0 || is_null($row['type'])){
4376
4377 $row['type'] = 'day';
4378
4379 }
4380
4381 return $row;
4382
4383 }
4384
4385 return null;
4386
4387 }
4388
4389 public function deleteCalendarAccount(){
4390
4391 global $wpdb;
4392
4393 $response = array();
4394 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
4395 $sql = $wpdb->prepare("SELECT * FROM `".$table_name."` WHERE `schedulesSharing` = %d AND `targetSchedules` = %d;", array(1, $_POST['accountKey']));
4396 $rows = $wpdb->get_results($sql, ARRAY_A);
4397 if (count($rows) == 0) {
4398
4399 $table_name = $wpdb->prefix . "booking_package_form";
4400 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4401
4402 $table_name = $wpdb->prefix . "booking_package_services";
4403 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4404
4405 $table_name = $wpdb->prefix . "booking_package_schedules";
4406 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4407
4408 $table_name = $wpdb->prefix . "booking_package_template_schedules";
4409 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4410
4411 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
4412 $wpdb->delete($table_name, array('key' => intval($_POST['accountKey'])), array('%d'));
4413
4414 $table_name = $wpdb->prefix . "booking_package_email_settings";
4415 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4416
4417 $table_name = $wpdb->prefix . "booking_package_guests";
4418 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4419
4420 $table_name = $wpdb->prefix . "booking_package_booked_customers";
4421 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4422
4423 $table_name = $wpdb->prefix . "booking_package_taxes";
4424 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4425
4426 $table_name = $wpdb->prefix . "booking_package_subscriptions";
4427 $wpdb->delete($table_name, array('accountKey' => intval($_POST['accountKey'])), array('%d'));
4428
4429 $response = $this->getCalendarAccountListData();
4430
4431 } else {
4432
4433 $calendarNameList = array();
4434 foreach ((array) $rows as $key => $row) {
4435
4436 array_push($calendarNameList, $row['name']);
4437
4438 }
4439 $calendarName = implode("\n", $calendarNameList);
4440 $response = array('error' => 1, 'message' => __('If you want to delete this calendar, delete the calendar sharing the schedules.', 'booking-package') . "\n" . $calendarName);
4441
4442 }
4443
4444 do_action('booking_package_deleted_calendar_account', intval($_POST['accountKey']));
4445 return $response;
4446
4447 }
4448
4449 public function addGuests($accountKey, $type = 'day') {
4450
4451 global $wpdb;
4452
4453 $setting = new booking_package_setting($this->prefix, $this->pluginName);
4454 $numberKeys = $setting->getListOfDaysOfWeek();
4455
4456 $table_name = $wpdb->prefix . "booking_package_guests";
4457 if ($type == 'day') {
4458
4459 $guestsList = array(
4460 0 => array("number" => 1, "price" => 0, "name" => "1 person"),
4461 1 => array("number" => 2, "price" => 0, "name" => "2 persons"),
4462 2 => array("number" => 3, "price" => 0, "name" => "3 persons"),
4463 3 => array("number" => 4, "price" => 0, "name" => "4 persons"),
4464 );
4465
4466 $wpdb->insert(
4467 $table_name,
4468 array(
4469 'accountKey' => intval($accountKey),
4470 'name' => "Number of participants",
4471 'target' => "adult",
4472 'json' => json_encode($guestsList),
4473 'required' => 1,
4474 'ranking' => 1
4475 ),
4476 array('%d', '%s', '%s', '%s', '%d')
4477 );
4478
4479 } else {
4480
4481 $guestsList = array(
4482 0 => array("number" => 1, "price" => 0, "name" => "1 adult"),
4483 1 => array("number" => 2, "price" => 0, "name" => "2 adults"),
4484 );
4485
4486 for ($i = 0; $i < count($numberKeys); $i++) {
4487
4488 $guestsList[0][$numberKeys[$i]] = 0;
4489 $guestsList[1][$numberKeys[$i]] = 0;
4490
4491 }
4492
4493 $wpdb->insert(
4494 $table_name,
4495 array(
4496 'accountKey' => intval($accountKey),
4497 'name' => "Number of adults",
4498 'target' => "adult",
4499 'json' => json_encode($guestsList),
4500 'required' => 1,
4501 'ranking' => 1
4502 ),
4503 array('%d', '%s', '%s', '%s', '%d')
4504 );
4505
4506 $guestsList[0]['name'] = '1 child';
4507 $guestsList[1]['name'] = '2 children';
4508
4509 $wpdb->insert(
4510 $table_name,
4511 array(
4512 'accountKey' => intval($accountKey),
4513 'name' => "Number of children",
4514 'target' => "children",
4515 'json' => json_encode($guestsList),
4516 'required' => 0,
4517 'ranking' => 2
4518 ),
4519 array('%d', '%s', '%s', '%s', '%d')
4520 );
4521
4522 }
4523
4524 }
4525
4526 public function getAccountSchedule($key) {
4527
4528 global $wpdb;
4529 $table_name = $wpdb->prefix . "booking_package_schedules";
4530 $sql = $wpdb->prepare(
4531 "SELECT * FROM `" . $table_name . "` WHERE `key` = %d;",
4532 array(intval($key))
4533 );
4534 $row = $wpdb->get_row($sql, ARRAY_A);
4535 if (is_null($row)) {
4536
4537 return false;
4538
4539 }
4540
4541 return $row;
4542
4543 }
4544
4545 public function getAccountScheduleData($getDeletedDate = false){
4546
4547 global $wpdb;
4548 $accountKey = 1;
4549 if (isset($_POST['accountKey'])) {
4550
4551 $accountKey = $_POST['accountKey'];
4552
4553 }
4554
4555 $month = intval($_POST['month']);
4556 $day = intval($_POST['day']);
4557 $year = intval($_POST['year']);
4558
4559 $dateFormat = intval(get_option($this->prefix . "dateFormat", 0));
4560 $positionOfWeek = get_option($this->prefix . "positionOfWeek", "before");
4561
4562 $last_day = date('t', mktime(0, 0, 0, $month, $day, $year));
4563 $week_start_num = date('w', mktime(0, 0, 0, $month, $day, $year));
4564 $week_last_num = date('w', mktime(0, 0, 0, $month, $last_day, $year));
4565
4566 $scheduleData = array();
4567 $jsonAraay = array('completeFlag' => 'accountScheduleData', 'startDay' => 1, 'lastDay' => intval($last_day), 'startWeek' => intval($week_start_num), 'lastWeek' => intval($week_last_num), 'month' => intval($month), 'year' => intval($year), 'timestamp' => date('U'));
4568 $scheduleData['date'] = $jsonAraay;
4569
4570 $calendarAccount = $this->getCalendarAccount($accountKey);
4571 $calendarList = $this->getCalendarList($month, $day, $year, $calendarAccount['startOfWeek']);
4572
4573 $list = array();
4574 $deletedList = array();
4575 foreach ((array) $calendarList as $key => $value) {
4576
4577 for ($i = $value['startDay']; $i <= $value['lastDay']; $i++) {
4578
4579 $key = $value['year'].sprintf("%02d%02d", $value['month'], $i);
4580 $week = date('w', mktime(0, 0, 0, $value['month'], $i, $value['year']));
4581 $dayArray = array('year' => $value['year'], 'month' => $value['month'], 'day' => $i, 'week' => $week, 'count' => null, 'accountKey' => $accountKey, 'stop' => 0, 'status' => 0, 'publishingDate' => null);
4582 $list[$key] = $dayArray;
4583 $deletedList[$key] = $dayArray;
4584
4585 }
4586
4587 $table_name = $wpdb->prefix . "booking_package_schedules";
4588 $sql = $wpdb->prepare(
4589 "SELECT year,month,day,accountKey,stop,MAX(publishingDate),SUM(capacity),SUM(remainder),COUNT(day) FROM `" . $table_name . "` GROUP BY `year`,`month`,`day`,`holiday`,`accountKey`,`publishingDate`,`status` HAVING `accountKey` = %d AND `year` = %d AND `month` = %d AND (`day` >= %d AND `day` <= %d) AND `status` = 'open' AND `publishingDate` >= 0;",
4590 array(intval($accountKey), intval($value['year']), intval($value['month']), intval($value['startDay']), intval($value['lastDay']))
4591 );
4592 $calendarList[$key]['sql'] = $sql;
4593 $rows = $wpdb->get_results($sql, ARRAY_A);
4594 foreach ((array) $rows as $row) {
4595
4596 $key = $row['year'].sprintf("%02d%02d", $row['month'], $row['day']);
4597 $list[$key]['stop'] = 0;
4598 if ($row['stop'] === 'true') {
4599
4600 $list[$key]['stop'] = 1;
4601
4602 }
4603
4604 if (isset($list[$key])) {
4605
4606 $list[$key]['status'] = 1;
4607
4608 }
4609
4610 if (intval( $row['MAX(publishingDate)']) > 0) {
4611
4612 $list[$key]['publishingDate'] = array(
4613 'key' => date('YmdHi', $row['MAX(publishingDate)']),
4614 'date' => $this->dateFormat($dateFormat, $positionOfWeek, $row['MAX(publishingDate)'], '', true, true, 'text'),
4615 'month' => date('n', $row['MAX(publishingDate)']),
4616 'day' => date('j', $row['MAX(publishingDate)']),
4617 'year' => date('Y', $row['MAX(publishingDate)']),
4618 'hour' => date('H', $row['MAX(publishingDate)']),
4619 'min' => date('i', $row['MAX(publishingDate)']),
4620 );
4621
4622 }
4623
4624 }
4625
4626 if ($getDeletedDate === true) {
4627
4628 $table_name = $wpdb->prefix . 'booking_package_template_schedules';
4629 $sql = $wpdb->prepare(
4630 "SELECT `weekKey` FROM `" . $table_name . "` GROUP BY `weekKey`, `accountKey` HAVING `accountKey` = %d;",
4631 array(intval($accountKey))
4632 );
4633 $templateSchedule = array();
4634 $rows = $wpdb->get_results($sql, ARRAY_A);
4635 foreach ((array) $rows as $row) {
4636
4637 array_push($templateSchedule, intval($row['weekKey']));
4638
4639 }
4640 $scheduleData['templateSchedule'] = $templateSchedule;
4641
4642 $table_name = $wpdb->prefix . "booking_package_schedules";
4643 $sql = $wpdb->prepare(
4644 "SELECT year,month,day,accountKey,SUM(capacity),SUM(remainder),COUNT(day) FROM `" . $table_name . "` GROUP BY `year`,`month`,`day`,`holiday`,`accountKey`,`status` HAVING `accountKey` = %d AND `year` = %d AND `month` = %d AND (`day` >= %d AND `day` <= %d) AND `status` = 'deleted';",
4645 array(
4646 intval($accountKey),
4647 intval($value['year']),
4648 intval($value['month']),
4649 intval($value['startDay']),
4650 intval($value['lastDay'])
4651 )
4652 );
4653 $rows = $wpdb->get_results($sql, ARRAY_A);
4654 foreach ((array) $rows as $row) {
4655
4656 $key = $row['year'].sprintf("%02d%02d", $row['month'], $row['day']);
4657 if (isset($deletedList[$key])) {
4658
4659 $deletedList[$key]['status'] = 1;
4660
4661 }
4662
4663 if (is_bool(array_search(intval($deletedList[$key]['week']), $templateSchedule))) {
4664
4665 $deletedList[$key]['status'] = 0;
4666
4667 }
4668
4669 }
4670
4671 }
4672
4673 }
4674
4675 $scheduleData['calendarList'] = $calendarList;
4676 $scheduleData['calendar'] = $list;
4677 $scheduleData['deletedCalendar'] = $deletedList;
4678
4679 return $scheduleData;
4680
4681 }
4682
4683 public function getRangeOfSchedule($accountKey = false){
4684
4685 if ($accountKey != false) {
4686
4687 global $wpdb;
4688
4689 $dateFormat = intval(get_option($this->prefix . "dateFormat", 0));
4690 $positionOfWeek = get_option($this->prefix . "positionOfWeek", "before");
4691 $account = $this->getCalendarAccount($accountKey);
4692 $table_name = $wpdb->prefix . "booking_package_schedules";
4693 $scheduleList = array();
4694 $start_unixTime = strtotime($_POST['start']);
4695 $end_unixTime = strtotime($_POST['end']);
4696
4697 $datetime1 = new DateTime(intval($_POST['start']));
4698 $datetime2 = new DateTime(intval($_POST['end']));
4699 $interval = $datetime1->diff($datetime2);
4700 $days_difference = $interval->days;
4701
4702 #for ($i = intval($start_unixTime); $i <= intval($end_unixTime); $i += (1440 * 60)) {
4703 for ($i = 0; $i <= $days_difference; $i++) {
4704
4705 $unixTime = strtotime("+" . $i . " days", intval($start_unixTime) );
4706 $key = date('Ymd', $unixTime);
4707 $date['month'] = date('m', $unixTime);
4708 $date['day'] = date('d', $unixTime);
4709 $date['year'] = date('Y', $unixTime);
4710
4711 /**
4712 $key = date('Ymd', $i);
4713 $date['month'] = date('m', $i);
4714 $date['day'] = date('d', $i);
4715 $date['year'] = date('Y', $i);
4716 **/
4717 $sql = $wpdb->prepare(
4718 "SELECT * FROM ".$table_name." WHERE `accountKey` = %d AND `year` = %d AND `month` = %d AND `day` = %d AND `status` = 'open' ORDER BY day ASC;",
4719 array(
4720 intval($accountKey),
4721 intval($date['year']),
4722 intval($date['month']),
4723 intval($date['day'])
4724 )
4725 );
4726 $row = $wpdb->get_row($sql);
4727 if (is_null($row)) {
4728
4729 $unixTime = date('U', mktime(0, 0, 0, intval($date['month']), $date['day'], intval($date['year'])));
4730 $week = date('w', mktime(0, 0, 0, intval($date['month']), $date['day'], intval($date['year'])));
4731 $scheduleList[$key] = array(
4732 "accountKey" => $accountKey,
4733 "unixTime" => $unixTime,
4734 "year" => intval($date['year']),
4735 "month" => intval($date['month']),
4736 "day" => $date['day'],
4737 "weekKey" => $week,
4738 "hour" => 0,
4739 "min" => 0,
4740 "title" => "",
4741 "stop" => "false",
4742 "holiday" => "false",
4743 "existence" => 0,
4744 "waitingRemainder" => 0,
4745 "uploadDate" => 0,
4746 "publishingDate" => 0,
4747 "publishingDateObjects" => null,
4748 "cost" => $account['cost'],
4749 "capacity" => $account['numberOfRoomsAvailable'],
4750 "remainder" => $account['numberOfRoomsAvailable'],
4751 );
4752
4753 } else {
4754
4755 $row->publishingDateObjects = null;
4756 if (intval($row->publishingDate) > 0) {
4757
4758 $publishingdate = $row->publishingDate;
4759
4760 $row->publishingDate = date('YmdHi', $publishingdate);
4761 $row->publishingDateObjects = array(
4762 'key' => date('YmdHi', $publishingdate),
4763 'date' => $this->dateFormat($dateFormat, $positionOfWeek, $publishingdate, '', true, true, 'text'),
4764 'month' => date('n', $publishingdate),
4765 'day' => date('j', $publishingdate),
4766 'year' => date('Y', $publishingdate),
4767 'hour' => date('H', $publishingdate),
4768 'min' => date('i', $publishingdate),
4769 'week' => date('w', $publishingdate),
4770 );
4771
4772 }
4773
4774
4775 $row->existence = 1;
4776 $scheduleList[$key] = $row;
4777
4778 }
4779
4780 }
4781
4782 return $scheduleList;
4783
4784 }
4785
4786 die();
4787
4788 }
4789
4790 public function getPublishedTimeSlots(){
4791
4792 $accountKey = 1;
4793 if (isset($_POST['accountKey'])) {
4794
4795 $accountKey = $_POST['accountKey'];
4796
4797 }
4798
4799 $dateFormat = intval(get_option($this->prefix . "dateFormat", 0));
4800 $positionOfWeek = get_option($this->prefix . "positionOfWeek", "before");
4801 $calendar = array();
4802
4803 global $wpdb;
4804 $table_name = $wpdb->prefix . "booking_package_schedules";
4805 $sql = $wpdb->prepare(
4806 "SELECT * FROM " . $table_name . " WHERE `accountKey` = %d AND `year` = %d AND `month` = %d AND `day` = %d AND `status` = 'open' ORDER BY weekKey, hour, min ASC;",
4807 array(intval($accountKey), intval($_POST['year']), intval($_POST['month']), intval($_POST['day']))
4808 );
4809 $rows = $wpdb->get_results($sql, ARRAY_A);
4810 return $rows;
4811
4812 }
4813
4814 public function getTemplateSchedule($weekKey){
4815
4816 $accountKey = 1;
4817 if (isset($_POST['accountKey'])) {
4818
4819 $accountKey = $_POST['accountKey'];
4820
4821 }
4822
4823 global $wpdb;
4824 $table_name = $wpdb->prefix."booking_package_template_schedules";
4825 $sql = $wpdb->prepare(
4826 "SELECT * FROM ".$table_name." WHERE `accountKey` = %d AND `weekKey` = %d ORDER BY weekKey, hour, min ASC;",
4827 array(intval($accountKey), intval($weekKey))
4828 );
4829 $rows = $wpdb->get_results($sql, ARRAY_A);
4830
4831 return $rows;
4832
4833 }
4834
4835 public function updateRangeOfSchedule($accountKey = false){
4836
4837 if ($accountKey != false && isset($_POST['json'])) {
4838
4839 global $wpdb;
4840 /**
4841 $timezone = get_option('timezone_string');
4842 date_default_timezone_set($timezone);
4843 **/
4844 $updateDate = date('U');
4845 $account = $this->getCalendarAccount($accountKey);
4846 $table_name = $wpdb->prefix . "booking_package_schedules";
4847 #$wpdb->query("START TRANSACTION");
4848 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
4849 try {
4850
4851 #$jsonList = json_decode(str_replace("\\", "", $_POST['json']));
4852 $jsonList = json_decode(stripslashes($_POST['json']));
4853 foreach ((array) $jsonList as $key => $value) {
4854
4855 $publishingDate = 0;
4856 if (!empty($value->publishingDate)) {
4857
4858 $publishingDate = strtotime($value->publishingDate);
4859
4860 }
4861
4862 if ($value->existence == 0) {
4863
4864 $sql = $wpdb->prepare(
4865 "SELECT * FROM ".$table_name." WHERE `accountKey` = %d AND `year` = %d AND `month` = %d AND `day` = %d AND `status` = 'open' ORDER BY day ASC;",
4866 array(
4867 intval($accountKey),
4868 intval($value->year),
4869 intval($value->month),
4870 intval($value->day),
4871 )
4872 );
4873 $row = $wpdb->get_row($sql);
4874 if (is_null($row)) {
4875
4876 $this->insertSchedule(
4877 $table_name, $accountKey, $value->unixTime, $value->month, $value->day,
4878 $value->year, $value->weekKey, $value->hour, $value->min, 0, $value->title,
4879 $value->cost, $value->capacity, $value->stop, $publishingDate, $updateDate
4880 );
4881
4882 }
4883
4884 } else {
4885
4886 $sql = $wpdb->prepare(
4887 "SELECT * FROM ".$table_name." WHERE `key` = %d;",
4888 array(
4889 intval($value->key)
4890 )
4891 );
4892 $row = $wpdb->get_row($sql);
4893
4894 if ($row->capacity != $value->capacity) {
4895
4896 //$value->remainder = $value->capacity - ($row->capacity - $row->remainder);
4897 /**
4898 if($row->capacity < $value->capacity){
4899
4900 $value->remainder = $value->remainder + ($value->capacity - $row->capacity);
4901
4902 }else{
4903
4904 $value->remainder = $value->remainder - $value->capacity;
4905
4906 }
4907 **/
4908 }
4909 /**
4910 $wpdb->update(
4911 $table_name,
4912 array(
4913 'cost' => intval($value->cost),
4914 'capacity' => intval($value->capacity),
4915 'remainder' => intval($value->remainder),
4916 'stop' => sanitize_text_field($value->stop),
4917 'publishingDate' => intval($publishingDate),
4918 ),
4919 array('key' => intval($value->key)),
4920 array('%d', '%d', '%d', '%s', '%d'),
4921 array('%d')
4922 );
4923 **/
4924 if ($account['type'] === 'day') {
4925
4926 $wpdb->update(
4927 $table_name,
4928 array(
4929 'cost' => intval($value->cost),
4930 'capacity' => intval($value->capacity),
4931 'remainder' => intval($value->remainder),
4932 'stop' => sanitize_text_field($value->stop),
4933 'publishingDate' => intval($publishingDate),
4934 ),
4935 array('key' => intval($value->key)),
4936 array('%d', '%d', '%d', '%s', '%d'),
4937 array('%d')
4938 );
4939
4940 } else {
4941
4942 $wpdb->update(
4943 $table_name,
4944 array(
4945 'cost' => intval($value->cost),
4946 'capacity' => intval($value->capacity),
4947 'remainder' => intval($value->remainder),
4948 'stop' => sanitize_text_field($value->stop),
4949 'publishingDate' => intval($publishingDate),
4950 ),
4951 array('accountKey' => intval($value->accountKey), 'year' => intval($value->year), 'month' => intval($value->month), 'day' => intval($value->day)),
4952 array('%d', '%d', '%d', '%s', '%d'),
4953 array('%d', '%d', '%d', '%d')
4954 );
4955
4956 }
4957
4958 }
4959
4960 }
4961
4962
4963 #$wpdb->query('COMMIT');
4964 $wpdb->query('UNLOCK TABLES');
4965
4966 } catch (Exception $e) {
4967
4968 #$wpdb->query('ROLLBACK');
4969 $wpdb->query('UNLOCK TABLES');
4970
4971 }/** finally {
4972
4973 $wpdb->query('UNLOCK TABLES');
4974
4975 }**/
4976
4977
4978
4979 $_POST['accountKey'] = $accountKey;
4980 $_POST['day'] = 1;
4981 $response = array();
4982 $response['getAccountScheduleData'] = $this->getAccountScheduleData();
4983 $response['getRangeOfSchedule'] = $this->getRangeOfSchedule($accountKey);
4984 $response['jsonList'] = $jsonList;
4985
4986 return $response;
4987
4988 }
4989
4990 die();
4991
4992 }
4993
4994 public function updateAccountTemplateSchedule() {
4995
4996 $accountKey = 1;
4997 if (isset($_POST['accountKey'])) {
4998
4999 $accountKey = $_POST['accountKey'];
5000
5001 }
5002
5003 global $wpdb;
5004 $array = array('completeFlag' => 'updateAccountTemplateSchedule');
5005 $sqlList = array();
5006 $valueList = array();
5007 $updateTime = date('U');
5008
5009 $continues = array();
5010 $schedules = array();
5011 $scheduleRead = array();
5012 $i = 0;
5013 for ($i = 0; $i < $_POST['timeCount']; $i++) {
5014
5015 #$schedule = json_decode(str_replace("\\", "", $_POST['schedule' . $i]), true);
5016 $schedule = json_decode(stripslashes($_POST['schedule' . $i]), true);
5017 $deadlineTime = 0;
5018 if (isset($schedule['deadlineTime'])) {
5019
5020 $deadlineTime = intval($schedule['deadlineTime']);
5021
5022 }
5023
5024 #$unixTime = mktime(intval($schedule['hour']), intval($schedule['min']), 0, intval($_POST['month']), intval($_POST['day0']), intval($_POST['year']));
5025
5026 $table_name = $wpdb->prefix . "booking_package_template_schedules";
5027 /**
5028 $valueArray = array($accountKey, intval($schedule['hour']), intval($schedule['min']), intval($_POST['weekKey']));
5029 $sql = $wpdb->prepare(
5030 "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `hour` = %d AND `min` = %d AND `weekKey` = %d;",
5031 $valueArray
5032 );
5033 **/
5034 $row = null;
5035 if (isset($schedule['scheduleKey'])) {
5036
5037 $sql = $wpdb->prepare(
5038 "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `key` = %d;",
5039 array($accountKey, intval($schedule['scheduleKey']))
5040 );
5041 $row = $wpdb->get_row($sql, ARRAY_A);
5042
5043 }
5044
5045 if (is_array($row)) {
5046
5047 if ($schedule['delete'] == 'true') {
5048
5049 array_push($sqlList, "DELETE FROM `".$table_name."` WHERE `key` = %d;");
5050 array_push($valueList, array(intval($row['key'])));
5051
5052 } else {
5053
5054 if ($schedule['delete'] == 'false') {
5055
5056 $sql = "UPDATE ".$table_name." SET `hour` = %d, `min` = %d, `title` = %s, `cost` = %d, `capacity` = %d, `stop` = %s, `deadlineTime` = %d WHERE `key` = %d;";
5057 $value = array(
5058 intval($schedule['hour']),
5059 intval($schedule['min']),
5060 sanitize_text_field($schedule['title']),
5061 intval($schedule['cost']),
5062 intval($schedule['capacity']),
5063 sanitize_text_field($schedule['stop']),
5064 intval($deadlineTime),
5065 intval($row['key'])
5066 );
5067
5068 } else {
5069
5070 $sql = "DELETE FORM ".$table_name." WHERE `key` = %d;";
5071 $value = array(
5072 intval($row['key'])
5073 );
5074
5075 }
5076
5077
5078 array_push($sqlList, $sql);
5079 array_push($valueList, $value);
5080
5081 }
5082
5083 } else {
5084
5085 if ($schedule['delete'] == 'true' || isset($schedules[sprintf('%02d', intval($schedule['hour'])) . sprintf('%02d', intval($schedule['min']))])) {
5086
5087 array_push($continues, $schedule);
5088 continue;
5089
5090 }
5091
5092 $sql = "INSERT INTO ".$table_name." (`accountKey`, `weekKey` ,`hour`, `min`, `title`, `cost`, `capacity`, `stop`, `holiday`, `uploadDate`, `deadlineTime`) VALUES (%d, %d, %d, %d, %s, %d, %d, %s, %s, %d, %d);";
5093 $value = array(
5094 intval($accountKey),
5095 intval($_POST['weekKey']),
5096 intval($schedule['hour']),
5097 intval($schedule['min']),
5098 sanitize_text_field($schedule['title']),
5099 intval($schedule['cost']),
5100 intval($schedule['capacity']),
5101 sanitize_text_field($schedule['stop']),
5102 'false',
5103 $updateTime,
5104 intval($deadlineTime),
5105 );
5106 array_push($sqlList, $sql);
5107 array_push($valueList, $value);
5108
5109 }
5110
5111 #$schedules[intval($schedule['hour']) . intval($schedule['min'])] = $schedule;
5112 $schedules[sprintf('%02d', intval($schedule['hour'])) . sprintf('%02d', intval($schedule['min']))] = $schedule;
5113
5114 }
5115
5116 $array['sql'] = $sqlList;
5117 $array['value'] = $valueList;
5118
5119 for ($i = 0; $i < count($sqlList); $i++) {
5120
5121 $sql = $wpdb->prepare($sqlList[$i], $valueList[$i]);
5122 $wpdb->query($sql);
5123
5124 }
5125
5126 $year = date('Y');
5127 $month = date('m');
5128 $day = date('d');
5129 #return array('sql' => $sqlList, 'values' => $valueList, 'continues' => $continues);
5130 $this->insertAccountSchedule($month, $day, $year, $accountKey);
5131
5132 }
5133
5134 public function insertSchedule($table_name, $accountKey, $unixTime, $month, $day, $year, $week, $hour, $min, $deadlineTime, $title, $cost, $capacity, $stop, $publishingDate, $uploadDate){
5135
5136 global $wpdb;
5137 $wpdb->insert(
5138 $table_name,
5139 array(
5140 'accountKey' => intval($accountKey),
5141 'unixTime' => intval($unixTime),
5142 'year' => intval($year),
5143 'month' => intval($month),
5144 'day' => intval($day),
5145 'weekKey' => intval($week),
5146 'hour' => intval($hour),
5147 'min' => intval($min),
5148 'title' => sanitize_text_field($title),
5149 'cost' => intval($cost),
5150 'capacity' => intval($capacity),
5151 'remainder' => intval($capacity),
5152 'stop' => sanitize_text_field($stop),
5153 'holiday' => 'false',
5154 'uploadDate' => intval($uploadDate),
5155 'deadlineTime' => intval($deadlineTime),
5156 'publishingDate' => intval($publishingDate),
5157 ),
5158 array('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%d', '%d')
5159 );
5160
5161
5162 }
5163
5164 public function updateHotelCharge($account){
5165
5166 global $wpdb;
5167
5168 if (
5169 isset($account['hotelChargeOnSunday']) === true &&
5170 isset($account['hotelChargeOnMonday']) === true &&
5171 isset($account['hotelChargeOnTuesday']) === true &&
5172 isset($account['hotelChargeOnWednesday']) === true &&
5173 isset($account['hotelChargeOnThursday']) === true &&
5174 isset($account['hotelChargeOnFriday']) === true &&
5175 isset($account['hotelChargeOnSaturday']) === true &&
5176 isset($account['hotelChargeOnDayBeforeNationalHoliday']) === true &&
5177 isset($account['hotelChargeOnNationalHoliday']) === true &&
5178 intval($account['hotelChargeOnSunday']) == 0 &&
5179 intval($account['hotelChargeOnMonday']) == 0 &&
5180 intval($account['hotelChargeOnTuesday']) == 0 &&
5181 intval($account['hotelChargeOnWednesday']) == 0 &&
5182 intval($account['hotelChargeOnThursday']) == 0 &&
5183 intval($account['hotelChargeOnFriday']) == 0 &&
5184 intval($account['hotelChargeOnSaturday']) == 0 &&
5185 intval($account['hotelChargeOnDayBeforeNationalHoliday']) == 0 &&
5186 intval($account['hotelChargeOnNationalHoliday']) == 0
5187 ) {
5188
5189 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
5190 try {
5191
5192 $wpdb->query("START TRANSACTION");
5193 #$wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
5194 $bool = $wpdb->update(
5195 $table_name,
5196 array(
5197 'hotelChargeOnSunday' => intval($account['cost']),
5198 'hotelChargeOnMonday' => intval($account['cost']),
5199 'hotelChargeOnTuesday' => intval($account['cost']),
5200 'hotelChargeOnWednesday' => intval($account['cost']),
5201 'hotelChargeOnThursday' => intval($account['cost']),
5202 'hotelChargeOnFriday' => intval($account['cost']),
5203 'hotelChargeOnSaturday' => intval($account['cost']),
5204 'hotelChargeOnDayBeforeNationalHoliday' => 0,
5205 'hotelChargeOnNationalHoliday' => 0,
5206 ),
5207 array('key' => intval($account['key'])),
5208 array(
5209 '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d',
5210 ),
5211 array('%d')
5212 );
5213
5214 $wpdb->query('COMMIT');
5215 #$wpdb->query('UNLOCK TABLES');
5216
5217 } catch (Exception $e) {
5218
5219 $wpdb->query('ROLLBACK');
5220 #$wpdb->query('UNLOCK TABLES');
5221
5222 }/** finally {
5223
5224 $wpdb->query('UNLOCK TABLES');
5225
5226 }**/
5227
5228 $account['hotelChargeOnSunday'] = intval($account['cost']);
5229 $account['hotelChargeOnMonday'] = intval($account['cost']);
5230 $account['hotelChargeOnTuesday'] = intval($account['cost']);
5231 $account['hotelChargeOnWednesday'] = intval($account['cost']);
5232 $account['hotelChargeOnThursday'] = intval($account['cost']);
5233 $account['hotelChargeOnFriday'] = intval($account['cost']);
5234 $account['hotelChargeOnSaturday'] = intval($account['cost']);
5235 $account['hotelChargeOnDayBeforeNationalHoliday'] = 0;
5236 $account['hotelChargeOnNatiohotelChargeOnNationalHolidaynalHoliday'] = 0;
5237
5238 } else {
5239
5240 //var_dump($account);
5241
5242 }
5243
5244 return $account;
5245
5246 }
5247
5248 public function insertAccountSchedule($month, $day, $year, $accountKey = false) {
5249
5250 if ($accountKey === false) {
5251
5252 return false;
5253
5254 }
5255
5256 global $wpdb;
5257 $isExtensionsValid = $this->getExtensionsValid();
5258 $uploadDate = date('U');
5259 $const_unixTime = date('U', mktime(0, 0, 0, $month, $day, $year));
5260 $maxAccountScheduleDay = intval(get_option($this->prefix.'maxAccountScheduleDay', 7));
5261
5262 /** Get Holidays **/
5263 $nationalHolidays = array();
5264 $table_name = $wpdb->prefix . 'booking_package_regular_holidays';
5265 $sql = $wpdb->prepare(
5266 "SELECT `month`, `day`, `year`, `unixTime` FROM `".$table_name."` WHERE `accountKey` = 'national' AND `status` = 1 AND `unixTime` >= %d;",
5267 array(intval($const_unixTime))
5268 );
5269 $rows = $wpdb->get_results($sql, ARRAY_A);
5270 foreach ((array) $rows as $row) {
5271
5272 $nationalHolidays[$row['year'] . sprintf('%02d', $row['month']) . sprintf('%02d', $row['day'])] = $row;
5273
5274 }
5275 /** Get Holidays **/
5276
5277 $row = $this->getCalendarAccount($accountKey);
5278 if ($row === false) {
5279
5280 return false;
5281
5282 }
5283 $rows = array(intval($row['key']) => $row);
5284
5285 #$wpdb->query("START TRANSACTION");
5286 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE, `" . $wpdb->prefix . "booking_package_template_schedules" . "` WRITE");
5287 try {
5288
5289 foreach ((array) $rows as $row) {
5290
5291 date_default_timezone_set($row['timezone']);
5292 $timeZone = $row['timezone'];
5293 $maxAccountScheduleDay = intval($row['maxAccountScheduleDay']);
5294 $accountKey = $row['key'];
5295 $accountType = $row['type'];
5296 if ($accountType == 'hotel') {
5297
5298 $row = $this->updateHotelCharge($row);
5299
5300 }
5301
5302 $calendarAccount = $row;
5303 $unixTime = $const_unixTime;
5304 $hotelCharges = array(
5305 $calendarAccount['hotelChargeOnSunday'],
5306 $calendarAccount['hotelChargeOnMonday'],
5307 $calendarAccount['hotelChargeOnTuesday'],
5308 $calendarAccount['hotelChargeOnWednesday'],
5309 $calendarAccount['hotelChargeOnThursday'],
5310 $calendarAccount['hotelChargeOnFriday'],
5311 $calendarAccount['hotelChargeOnSaturday'],
5312 );
5313
5314 $addedSchedules = (function($wpdb, $calendarAccount, $accountKey, $unixTime) {
5315
5316 $addedSchedules = array();
5317 $table_name = $wpdb->prefix . "booking_package_schedules";
5318 if ($calendarAccount['type'] === 'day') {
5319
5320 $sql = $wpdb->prepare(
5321 "SELECT `year`, `month`, `day`, `accountKey` FROM `" . $table_name . "` GROUP BY `year`, `month`, `day`, `accountKey`, `status` HAVING `accountKey` = %d AND `year` >= %d AND (`status` = 'open' OR `status` = 'deleted');",
5322 array(intval($accountKey), intval( date('Y', $unixTime) ))
5323 );
5324
5325 } else {
5326
5327 $sql = $wpdb->prepare(
5328 "SELECT `year`, `month`, `day`, `accountKey`, `stop` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `year` >= %d AND (`status` = 'open' OR `status` = 'deleted') ORDER BY `unixTime` ASC;",
5329 array(intval($accountKey), intval( date('Y', $unixTime) ))
5330 );
5331
5332 }
5333
5334 $schedules = $wpdb->get_results($sql, ARRAY_A);
5335 foreach ($schedules as $schedule) {
5336
5337 $key = $schedule['year'] . sprintf('%02d', $schedule['month']) . sprintf('%02d', $schedule['day']);
5338 $addedSchedules[$key] = $schedule;
5339
5340 }
5341
5342 #var_dump($sql);
5343 return $addedSchedules;
5344
5345 })($wpdb, $calendarAccount, $accountKey, $unixTime);
5346
5347 for ($i = 0; $i < $maxAccountScheduleDay; $i++) {
5348
5349 $year = date('Y', $unixTime);
5350 $month = date('m', $unixTime);
5351 $day = date('d', $unixTime);
5352 $week = date('w', $unixTime);
5353
5354 $now = new DateTime("@$unixTime");
5355 $now->setTimezone(new DateTimeZone($timeZone));
5356 $now->modify('+1 day');
5357 $dayBeforeUnixTime = $now->getTimestamp();
5358 $unixTime = $now->getTimestamp();
5359
5360 #$dayBeforeUnixTime = $unixTime + (1440 * 60);
5361 $dayBeforeNationalHolidayKey = date('Y', $dayBeforeUnixTime) . date('m', $dayBeforeUnixTime) . date('d', $dayBeforeUnixTime);
5362 $nationalHolidayKey = $year . sprintf('%02d', $month) . sprintf('%02d', $day);
5363 #$unixTime += 1440 * 60;
5364 $table_name = $wpdb->prefix . "booking_package_schedules";
5365
5366 $hasSchedules = (function($year, $month, $day, $addedSchedules) {
5367
5368 $key = $year . sprintf('%02d', $month) . sprintf('%02d', $day);
5369 if (array_key_exists($key, $addedSchedules) === false) {
5370
5371 return false;
5372
5373 }
5374
5375 return true;
5376
5377 })($year, $month, $day, $addedSchedules);
5378
5379 if ($hasSchedules === false) {
5380 //if (is_null($row)) {
5381
5382 if ($calendarAccount['type'] == 'day') {
5383
5384 $table_name = $wpdb->prefix . "booking_package_template_schedules";
5385 $sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `weekKey` = %d ORDER BY `weekKey`, `hour`, `min` ASC;";
5386 $template_rows = $wpdb->get_results($wpdb->prepare($sql, array(intval($accountKey), intval($week))), ARRAY_A);
5387 foreach ((array) $template_rows as $template_row) {
5388
5389 $time = date('U', mktime($template_row['hour'], $template_row['min'], 0, $month, $day, $year));
5390 $table_name = $wpdb->prefix . "booking_package_schedules";
5391
5392 $this->insertSchedule(
5393 $table_name, $accountKey, $time, $month, $day, $year, $week,
5394 $template_row['hour'], $template_row['min'], $template_row['deadlineTime'], $template_row['title'],
5395 $template_row['cost'], $template_row['capacity'], $template_row['stop'], 0,
5396 $uploadDate
5397 );
5398
5399 }
5400
5401 } else {
5402
5403 $cost = $calendarAccount['cost'];
5404 $hotelCharges = array(
5405 $calendarAccount['hotelChargeOnSunday'],
5406 $calendarAccount['hotelChargeOnMonday'],
5407 $calendarAccount['hotelChargeOnTuesday'],
5408 $calendarAccount['hotelChargeOnWednesday'],
5409 $calendarAccount['hotelChargeOnThursday'],
5410 $calendarAccount['hotelChargeOnFriday'],
5411 $calendarAccount['hotelChargeOnSaturday'],
5412 );
5413
5414 if (isset($nationalHolidays[intval($nationalHolidayKey)]) && intval($calendarAccount['hotelChargeOnNationalHoliday']) > 0) {
5415
5416 $cost = $calendarAccount['hotelChargeOnNationalHoliday'];
5417
5418 } else if (isset($nationalHolidays[intval($dayBeforeNationalHolidayKey)]) && intval($calendarAccount['hotelChargeOnDayBeforeNationalHoliday']) > 0) {
5419
5420 $cost = $calendarAccount['hotelChargeOnDayBeforeNationalHoliday'];
5421
5422 } else {
5423
5424 $cost = $hotelCharges[intval($week)];
5425
5426 }
5427
5428 $capacity = $calendarAccount['numberOfRoomsAvailable'];
5429 $time = date('U', mktime(0, 0, 0, $month, $day, $year));
5430 $table_name = $wpdb->prefix . "booking_package_schedules";
5431
5432 $wpdb->insert(
5433 $table_name,
5434 array(
5435 'accountKey' => intval($accountKey),
5436 'unixTime' => intval($time),
5437 'year' => intval($year),
5438 'month' => intval($month),
5439 'day' => intval($day),
5440 'weekKey' => intval($week),
5441 'hour' => 0,
5442 'min' => 0,
5443 'title' => '',
5444 'cost' => intval($cost),
5445 'capacity' => intval($capacity),
5446 'remainder' => intval($capacity),
5447 'stop' => 'false',
5448 'holiday' => 'false',
5449 'uploadDate' => $uploadDate
5450 ),
5451 array(
5452 '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%d',
5453 '%d', '%d', '%s', '%s', '%d'
5454 )
5455 );
5456
5457 }
5458
5459 } else {
5460
5461 if ($isExtensionsValid === true) {
5462
5463 if ($calendarAccount['type'] === 'hotel' && intval($calendarAccount['autoPublish']) === 1 && $row->stop === 'auto_publish') {
5464
5465 $table_name = $wpdb->prefix . "booking_package_schedules";
5466 $bool = $wpdb->update(
5467 $table_name,
5468 array(
5469 'stop' => 'false',
5470 ),
5471 array('key' => intval($row->key)),
5472 array('%s'),
5473 array('%d')
5474 );
5475
5476 }
5477
5478 }
5479
5480 }
5481
5482 }
5483
5484 }
5485
5486 if ($isExtensionsValid === true) {
5487
5488 $unixTime = date('U', mktime(date('H'), 0, 0, date('m'), date('d'), date('Y')));
5489 $table_name = $wpdb->prefix . "booking_package_schedules";
5490 $sql = $wpdb->prepare(
5491 "UPDATE " . $table_name . " SET `publishingDate` = 0 WHERE (`publishingDate` > 0 AND `publishingDate` <= %d) AND `accountKey` = %d",
5492 array(intval($unixTime), intval($accountKey))
5493 );
5494 $wpdb->query($sql);
5495
5496 }
5497
5498 #$wpdb->query('COMMIT');
5499 $wpdb->query('UNLOCK TABLES');
5500
5501 } catch (Exception $e) {
5502
5503 #$wpdb->query('ROLLBACK');
5504 $wpdb->query('UNLOCK TABLES');
5505
5506 }/** finally {
5507
5508 $wpdb->query('UNLOCK TABLES');
5509
5510 }**/
5511
5512
5513
5514 }
5515
5516 public function addAccountSchedule() {
5517
5518 $accountKey = 1;
5519 if (isset($_POST['accountKey'])) {
5520
5521 $accountKey = $_POST['accountKey'];
5522
5523 }
5524
5525 $publishingDate = 0;
5526 if (isset($_POST['publishingDate']) === true) {
5527
5528 $publishingDate = strtotime($_POST['publishingDate']);
5529
5530 }
5531
5532 global $wpdb;
5533 $multipleDays = explode(',', $_POST['multipleDays']);
5534 for ($i = 0; $i < count($multipleDays); $i++) {
5535
5536 $year = substr($multipleDays[$i], 0, 4);
5537 $month = substr($multipleDays[$i], 4, 2);
5538 $day = substr($multipleDays[$i], 6, 2);
5539 $addedSchedules = (function($year, $month, $day, $publishingDate, $accountKey) {
5540
5541 global $wpdb;
5542 $table_name = $wpdb->prefix . "booking_package_schedules";
5543
5544 try {
5545
5546 $wpdb->query("START TRANSACTION");
5547 $wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
5548 for ($i = 0; $i < $_POST['timeCount']; $i++) {
5549
5550 $schedule = json_decode(stripslashes($_POST['schedule' . $i]), true);
5551 $unixTime = intval(date('U', mktime($schedule['hour'], $schedule['min'], 0, $month, $day, $year)));
5552 $weekKey = intval(date('w', mktime($schedule['hour'], $schedule['min'], 0, $month, $day, $year)));
5553
5554 if ($schedule['delete'] === 'true') {
5555
5556 continue;
5557
5558 }
5559
5560 $sql = $wpdb->prepare(
5561 "SELECT * FROM `" . $table_name . "` WHERE `accountKey` = %d AND `unixTime` = %d AND `status` = 'open';",
5562 array(
5563 intval($accountKey),
5564 intval($unixTime)
5565 )
5566 );
5567 $row = $wpdb->get_row($sql, ARRAY_A);
5568
5569 if (is_null($row)) {
5570
5571 $sql = $wpdb->prepare(
5572 "INSERT INTO `" . $table_name . "` (`accountKey`,`unixTime`,`year`,`month`,`day`, `weekKey`, `hour`,`min`,`title`,`capacity`,`remainder`,`stop`,`holiday`,`cost`,`deadlineTime`, `publishingDate`) VALUES (%d, %d, %d, %d, %d, %d, %d, %d, %s, %d, %d, %s, %s, %d, %d, %d);",
5573 array(
5574 intval($accountKey),
5575 $unixTime,
5576 intval($year),
5577 intval($month),
5578 intval($day),
5579 intval($weekKey),
5580 intval($schedule['hour']),
5581 intval($schedule['min']),
5582 sanitize_text_field($schedule['title']),
5583 intval($schedule['capacity']),
5584 intval($schedule['remainder']),
5585 sanitize_text_field($schedule['stop']),
5586 "false",
5587 intval(0),
5588 intval($schedule['deadlineTime']),
5589 intval($publishingDate),
5590 )
5591 );
5592 $wpdb->query($sql);
5593
5594 }
5595
5596 }
5597
5598 $wpdb->query('COMMIT');
5599 $wpdb->query('UNLOCK TABLES');
5600 return true;
5601
5602 } catch (Exception $e) {
5603
5604 #$wpdb->query('ROLLBACK');
5605 $wpdb->query('UNLOCK TABLES');
5606 return false;
5607
5608 }/** finally {
5609
5610 $wpdb->query('UNLOCK TABLES');
5611
5612 }**/
5613
5614 })($year, $month, $day, $publishingDate, $accountKey);
5615
5616 }
5617
5618 }
5619
5620 public function updateAccountSchedule(){
5621
5622 $accountKey = 1;
5623 if (isset($_POST['accountKey'])) {
5624
5625 $accountKey = $_POST['accountKey'];
5626
5627 }
5628
5629 global $wpdb;
5630 $sql = '';
5631 $courseTime = 0;
5632 $maintenanceTime = 0;
5633 $publishingDate = 0;
5634 if (isset($_POST['publishingDate']) === true) {
5635
5636 $publishingDate = strtotime($_POST['publishingDate']);
5637
5638 }
5639
5640 $array = array();
5641 $value_array = array();
5642 $rpeatList = array();
5643 $schedules = array();
5644 $prepareForRpeatReservation = array();
5645
5646 $table_name = $wpdb->prefix . "booking_package_services";
5647 $sql = "SELECT `key`,max(`time`) FROM `".$table_name."` WHERE `accountKey` = %d;";
5648 $row = $wpdb->get_row(
5649 $wpdb->prepare(
5650 $sql,
5651 array(intval($accountKey))
5652 ),
5653 ARRAY_A
5654 );
5655 if (is_null($row)) {
5656
5657 $courseTime = 0;
5658
5659 } else {
5660
5661 $courseTime = intval($row["max(`time`)"]);
5662
5663 }
5664
5665 #$wpdb->query("START TRANSACTION");
5666 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE, `" . $wpdb->prefix . "booking_package_booked_customers" . "` WRITE");
5667 try {
5668
5669 for ($i = 0; $i < $_POST['timeCount']; $i++) {
5670
5671 $updateBool = false;
5672 $sql = null;
5673 $updateArray = array();
5674 #$schedule = json_decode(str_replace("\\", "", $_POST['schedule' . $i]), true);
5675 $schedule = json_decode(stripslashes($_POST['schedule' . $i]), true);
5676 $unixTime = intval(date('U', mktime($schedule['hour'], $schedule['min'], 0, $_POST['month'], $_POST['day'], $_POST['year'])));
5677 $weekKey = intval(date('w', mktime($schedule['hour'], $schedule['min'], 0, $_POST['month'], $_POST['day'], $_POST['year'])));
5678
5679 $deadlineTime = 0;
5680 if (isset($schedule['deadlineTime'])) {
5681
5682 $deadlineTime = intval($schedule['deadlineTime']);
5683
5684 }
5685
5686 if (isset($schedule['key'])) {
5687
5688 $table_name = $wpdb->prefix . "booking_package_schedules";
5689 $sql = "SELECT * FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';";
5690 $row = $wpdb->get_row(
5691 $wpdb->prepare($sql, array(intval($schedule['key']))),
5692 ARRAY_A
5693 );
5694
5695 if (!is_null($row)) {
5696
5697 $updateBool = true;
5698 if ($schedule['delete'] == 'true') {
5699
5700 /**
5701 $sql = "DELETE FROM `".$table_name."` WHERE `capacity` = `remainder` AND `key` = %d;";
5702 $updateArray = array(intval($schedule['key']));
5703 **/
5704 $sql = "UPDATE `".$table_name."` SET `status` = %s WHERE `capacity` = `remainder` AND `key` = %d;";
5705 $updateArray = array('deleted', intval($schedule['key']));
5706
5707 } else {
5708
5709 $capacity = $schedule['capacity'];
5710 $remainder = $schedule['remainder'];
5711
5712 $sql = "UPDATE `".$table_name."` SET `unixTime` = %d, `year` = %d, `month` = %d, `day` = %d, ";
5713 $sql .= "`hour` = %d, `min` = %d, `title` = %s, `capacity` = %d, `remainder` = %d, `stop` = %s, `cost` = %d , `deadlineTime` = %d, `publishingDate` = %d ";
5714 $sql .= "WHERE `key` = %d;";
5715 $updateArray = array(
5716 $unixTime,
5717 intval($_POST['year']),
5718 intval($_POST['month']),
5719 intval($_POST['day']),
5720 intval($schedule['hour']),
5721 intval($schedule['min']),
5722 sanitize_text_field($schedule['title']),
5723 intval($capacity),
5724 intval($remainder),
5725 sanitize_text_field($schedule['stop']),
5726 intval(0),
5727 intval($deadlineTime),
5728 intval($publishingDate),
5729 intval($schedule['key'])
5730 );
5731
5732 }
5733
5734 }
5735
5736 } else {
5737
5738 $remainder = $schedule['capacity'];
5739 $remainder = $schedule['remainder'];
5740 $reserveRemainder = 0;
5741
5742 $table_name = $wpdb->prefix . "booking_package_booked_customers";
5743 $serch_sql = "SELECT * FROM `".$table_name."` WHERE `scheduleUnixTime` > %d AND `scheduleUnixTime` < %d AND `accountKey` = %d;";
5744 $valueArray = array(($unixTime - ($courseTime * 60) - ($maintenanceTime * 60)), $unixTime, intval($accountKey));
5745 #var_dump($valueArray);
5746 $sql = $wpdb->prepare($serch_sql, $valueArray);
5747 $rows = $wpdb->get_results($sql, ARRAY_A);
5748 foreach ((array) $rows as $row) {
5749
5750 $reserveUnixTime = $row['scheduleUnixTime'] + ($row['courseTime'] * 60);
5751 if($unixTime < $reserveUnixTime){
5752 $remainder--;
5753 $reserveRemainder++;
5754 }
5755
5756 }
5757
5758 if ($remainder < 0) {
5759
5760 $updateBool = false;
5761
5762 } else {
5763
5764 $updateBool = true;
5765
5766 }
5767
5768 if ($updateBool == true) {
5769
5770 if ($schedule['delete'] == 'true') {
5771
5772 continue;
5773
5774 }
5775
5776 $table_name = $wpdb->prefix . "booking_package_schedules";
5777 $sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `unixTime` = %d AND `status` = 'open';";
5778 $row = $wpdb->get_row($wpdb->prepare($sql, array(intval($accountKey), $unixTime)), ARRAY_A);
5779 if (is_null($row)) {
5780
5781 $sql = "INSERT INTO `".$table_name."` (`accountKey`,`unixTime`,`year`,`month`,`day`, `weekKey`, `hour`,`min`,`title`,`capacity`,`remainder`,`stop`,`holiday`,`cost`,`deadlineTime`, `publishingDate`) ";
5782 $sql .= "VALUES (%d, %d, %d, %d, %d, %d, %d, %d, %s, %d, %d, %s, %s, %d, %d, %d);";
5783 $updateArray = array(
5784 intval($accountKey),
5785 $unixTime,
5786 intval($_POST['year']),
5787 intval($_POST['month']),
5788 intval($_POST['day']),
5789 intval($weekKey),
5790 intval($schedule['hour']),
5791 intval($schedule['min']),
5792 sanitize_text_field($schedule['title']),
5793 intval($schedule['capacity']),
5794 intval($remainder),
5795 sanitize_text_field($schedule['stop']),
5796 "false",
5797 intval(0),
5798 intval($deadlineTime),
5799 intval($publishingDate),
5800 );
5801
5802 }
5803
5804 }
5805
5806 }
5807
5808 if ($updateBool == true && !isset($schedules[$unixTime])) {
5809
5810 array_push($array, $sql);
5811 array_push($value_array, $updateArray);
5812
5813 }
5814
5815 $schedules[$unixTime] = $schedule;
5816
5817 }
5818
5819 for ($i = 0; $i < count($array); $i++) {
5820
5821 $sql = $wpdb->prepare($array[$i], $value_array[$i]);
5822 $wpdb->query($sql);
5823
5824 }
5825
5826 #$wpdb->query('COMMIT');
5827 $wpdb->query('UNLOCK TABLES');
5828
5829
5830 } catch (Exception $e) {
5831
5832 #$wpdb->query('ROLLBACK');
5833 $wpdb->query('UNLOCK TABLES');
5834
5835 }/** finally {
5836
5837 $wpdb->query('UNLOCK TABLES');
5838
5839 }**/
5840
5841 }
5842
5843 public function deletePerfectPublicSchedule(){
5844
5845 global $wpdb;
5846 $table_name = $wpdb->prefix . "booking_package_schedules";
5847 $sql = $wpdb->prepare(
5848 "DELETE FROM `".$table_name."` WHERE `year` = %d AND `month` = %d AND `day` = %d AND `accountKey` = %d AND `status` = 'deleted';",
5849 array(
5850 intval($_POST['year']),
5851 intval($_POST['month']),
5852 intval($_POST['day']),
5853 intval($_POST['accountKey']),
5854 )
5855 );
5856 $wpdb->query($sql);
5857 return $sql;
5858
5859 }
5860
5861 public function deleteOldDaysInSchedules(){
5862
5863 global $wpdb;
5864 /**
5865 $timezone = get_option('timezone_string');
5866 date_default_timezone_set($timezone);
5867 **/
5868 $unixTime = date('U') - (14 * 24 * 3600);
5869 $unixTime = date('U', mktime(0, 0, 0, date('m', $unixTime), date('d', $unixTime), date('Y', $unixTime)));
5870
5871 $table_name = $wpdb->prefix . "booking_package_schedules";
5872 $sql = $wpdb->prepare("DELETE FROM `".$table_name."` WHERE `unixTime` < %d;", array($unixTime));
5873 $wpdb->query($sql);
5874 return $sql;
5875
5876 }
5877
5878 public function deletePublishedSchedules($accountKey = 1, $type = 'day') {
5879
5880 $response = array("status" => "error", "request" => $_POST);
5881 if (isset($_POST['deletePublishedSchedules_from_month']) && isset($_POST['deletePublishedSchedules_from_day']) && isset($_POST['deletePublishedSchedules_from_year'])) {
5882
5883 if (
5884 checkdate($_POST['deletePublishedSchedules_from_month'], $_POST['deletePublishedSchedules_from_day'], $_POST['deletePublishedSchedules_from_year']) === false ||
5885 checkdate($_POST['deletePublishedSchedules_to_month'], $_POST['deletePublishedSchedules_to_day'], $_POST['deletePublishedSchedules_to_year']) === false
5886 ) {
5887
5888 return $response;
5889
5890 }
5891
5892 $unixTime_from = date('U', mktime(0, 0, 0, $_POST['deletePublishedSchedules_from_month'], $_POST['deletePublishedSchedules_from_day'], $_POST['deletePublishedSchedules_from_year']));
5893 $unixTime_to = date('U', mktime(23, 59, 0, $_POST['deletePublishedSchedules_to_month'], $_POST['deletePublishedSchedules_to_day'], $_POST['deletePublishedSchedules_to_year']));
5894 global $wpdb;
5895 $accountKeys = array($accountKey);
5896 $calendarAccounts = $this->getCalendarAccountsWithHavingSchedulesSharing($accountKey);
5897 foreach ($calendarAccounts as $key => $value) {
5898
5899 array_push($accountKeys, $value['key']);
5900
5901 }
5902
5903 $customers = array();
5904 $schedulesSQL = null;
5905 $customerSQL = array();
5906 $schedules_table_name = $wpdb->prefix . "booking_package_schedules";
5907 $customer_table_name = $wpdb->prefix . "booking_package_booked_customers";
5908 if ($_POST['delete_action'] == 'delete') {
5909
5910 if ($_POST['deletionType'] == 'perfect') {
5911
5912 $schedulesSQL = $wpdb->prepare(
5913 "DELETE FROM `" . $schedules_table_name . "` WHERE `accountKey` = %d;",
5914 array($accountKey)
5915 );
5916
5917 if ($_POST['period'] == 'period_after') {
5918
5919 $schedulesSQL = $wpdb->prepare(
5920 "DELETE FROM `" . $schedules_table_name . "` WHERE `accountKey` = %d AND `unixTime` >= %d;",
5921 array($accountKey, intval($unixTime_from))
5922 );
5923
5924 }
5925
5926 if ($_POST['period'] == 'period_within') {
5927
5928 $schedulesSQL = $wpdb->prepare(
5929 "DELETE FROM `" . $schedules_table_name . "` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d);",
5930 array($accountKey, intval($unixTime_from), intval($unixTime_to))
5931 );
5932
5933 }
5934
5935 } else if ($_POST['deletionType'] == 'incomplete') {
5936
5937 $schedulesSQL = $wpdb->prepare(
5938 "UPDATE `" . $schedules_table_name . "` SET `status` = 'deleted' WHERE `accountKey` = %d;",
5939 array($accountKey)
5940 );
5941
5942 if ($_POST['period'] == 'period_after') {
5943
5944 $schedulesSQL = $wpdb->prepare(
5945 "UPDATE `" . $schedules_table_name . "` SET `status` = 'deleted' WHERE `accountKey` = %d AND `unixTime` >= %d;",
5946 array($accountKey, intval($unixTime_from))
5947 );
5948
5949 }
5950
5951 if ($_POST['period'] == 'period_within') {
5952
5953 $schedulesSQL = $wpdb->prepare(
5954 "UPDATE `" . $schedules_table_name . "` SET `status` = 'deleted' WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d);",
5955 array($accountKey, intval($unixTime_from), intval($unixTime_to))
5956 );
5957
5958 }
5959
5960 }
5961
5962 for ($i = 0; $i < count($accountKeys); $i++) {
5963
5964 $SQL = $wpdb->prepare(
5965 "UPDATE `" . $customer_table_name . "` SET `status`= 'canceled' WHERE `accountKey` = %d;",
5966 array($accountKeys[$i])
5967 );
5968
5969 if ($_POST['period'] == 'period_after') {
5970
5971 $SQL = $wpdb->prepare(
5972 "UPDATE `" . $customer_table_name . "` SET `status`= 'canceled' WHERE `accountKey` = %d AND `scheduleUnixTime` > %d;",
5973 array($accountKeys[$i], intval($unixTime_from))
5974 );
5975
5976 if ($type == 'hotel') {
5977
5978 $SQL = $wpdb->prepare(
5979 "SELECT `key`, `accountKey`, `cancellationToken`, `checkin`, `checkout` FROM `" . $customer_table_name . "` WHERE `status` != 'canceled' AND `accountKey` = %d AND (`checkin` > %d OR `checkout` > %d);",
5980 array($accountKeys[$i], intval($unixTime_from), intval($unixTime_from))
5981 );
5982
5983 }
5984
5985 } else if ($_POST['period'] == 'period_within') {
5986
5987 $SQL = $wpdb->prepare(
5988 "UPDATE `" . $customer_table_name . "` SET `status`= 'canceled' WHERE `accountKey` = %d AND (`scheduleUnixTime` > %d AND `scheduleUnixTime` < %d);",
5989 array($accountKeys[$i], intval($unixTime_from), intval($unixTime_to))
5990 );
5991
5992 if ($type == 'hotel') {
5993
5994 $SQL = $wpdb->prepare(
5995 "SELECT `key`, `accountKey`, `cancellationToken`, `checkin`, `checkout` FROM `" . $customer_table_name . "` WHERE `accountKey` = %d AND (`checkOut` >= %d AND `checkOut` < %d) OR (`checkIn` >= %d AND `checkIn` < %d);",
5996 array($accountKeys[$i], intval($unixTime_from), intval($unixTime_to), intval($unixTime_from), intval($unixTime_to))
5997 );
5998
5999 }
6000
6001 }
6002
6003 array_push($customerSQL, $SQL);
6004
6005 }
6006
6007
6008 #$wpdb->query("START TRANSACTION");
6009 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE, `" . $wpdb->prefix . "booking_package_booked_customers" . "` WRITE");
6010 try {
6011
6012 if ($type == 'day') {
6013
6014 $wpdb->query($schedulesSQL);
6015 #$wpdb->query($customerSQL);
6016 for ($i = 0; $i < count($customerSQL); $i++) {
6017
6018 $wpdb->query($customerSQL[$i]);
6019
6020 }
6021
6022 } else if ($type == 'hotel') {
6023
6024 $wpdb->query($schedulesSQL);
6025 for ($i = 0; $i < count($customerSQL); $i++) {
6026
6027 $rows = $wpdb->get_results($customerSQL[$i], ARRAY_A);
6028 foreach ((array) $rows as $key => $row) {
6029
6030 array_push($customers, $row);
6031
6032 }
6033
6034 }
6035
6036 }
6037
6038 #$wpdb->query('COMMIT');
6039 $wpdb->query('UNLOCK TABLES');
6040
6041 } catch (Exception $e) {
6042
6043 #$wpdb->query('ROLLBACK');
6044 $wpdb->query('UNLOCK TABLES');
6045
6046 }/** finally {
6047
6048 $wpdb->query('UNLOCK TABLES');
6049
6050 }**/
6051
6052 } else {
6053
6054 #$wpdb->query("START TRANSACTION");
6055 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE");
6056 try {
6057
6058 $schedulesSQL = $wpdb->prepare(
6059 "UPDATE `" . $schedules_table_name . "` SET `stop` = 'true' WHERE `accountKey` = %d;",
6060 array($accountKey)
6061 );
6062
6063 if ($_POST['period'] == 'period_after') {
6064
6065 $schedulesSQL = $wpdb->prepare(
6066 "UPDATE `" . $schedules_table_name . "` SET `stop` = 'true' WHERE `accountKey` = %d AND `unixTime` > %d;",
6067 array($accountKey, intval($unixTime_from))
6068 );
6069
6070 }
6071
6072 if ($_POST['period'] == 'period_within') {
6073
6074 $schedulesSQL = $wpdb->prepare(
6075 "UPDATE `".$schedules_table_name."` SET `stop` = 'true' WHERE `accountKey` = %d AND (`unixTime` > %d AND `unixTime` < %d);",
6076 array($accountKey, intval($unixTime_from), intval($unixTime_to))
6077 );
6078
6079 }
6080
6081 $wpdb->query($schedulesSQL);
6082 #$wpdb->query('COMMIT');
6083 $wpdb->query('UNLOCK TABLES');
6084
6085 } catch (Exception $e) {
6086
6087 #$wpdb->query('ROLLBACK');
6088 $wpdb->query('UNLOCK TABLES');
6089
6090 }/** finally {
6091
6092 $wpdb->query('UNLOCK TABLES');
6093
6094 }**/
6095
6096 }
6097
6098 for ($i = 0; $i < count($customers); $i++) {
6099
6100 $_POST['sendEmail'] = 0;
6101 $this->updateStatus($customers[$i]['key'], $customers[$i]['cancellationToken'], 'canceled');
6102
6103 }
6104
6105 $response['schedulesSQL'] = $schedulesSQL;
6106 $response['customerSQL'] = $customerSQL;
6107 $response['status'] = 'success';
6108
6109 }
6110
6111 if ($type === 'hotel') {
6112
6113 $this->insertAccountSchedule(date('m'), date('d'), date('Y'), $accountKey);
6114
6115 }
6116
6117 return $response;
6118
6119 }
6120
6121 public function getReservationUsersData($calendarAccount, $month, $day, $year){
6122
6123 date_default_timezone_set($calendarAccount['timezone']);
6124 $start = strtotime($year . '-' . $month . '-' . $day . ' 00:00:00');
6125 $end = strtotime($year . '-' . $month . '-' . $day . ' 23:59:59');
6126 $response = array();
6127 global $wpdb;
6128 $table_name = $wpdb->prefix . "booking_package_booked_customers";
6129 $sql = $wpdb->prepare(
6130 "SELECT `key`,`accountKey`,`status`,`scheduleUnixTime`,`courseName`,`praivateData`,`accommodationDetails`, `cancellationToken` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` <= %d ORDER BY `scheduleUnixTime` ASC;",
6131 array(intval($calendarAccount['key']), intval($start), intval($end))
6132 );
6133 #var_dump($sql);
6134 $rows = $wpdb->get_results($sql, ARRAY_A);
6135 foreach ((array) $rows as $row) {
6136
6137 $row['praivateData'] = json_decode($row['praivateData'], true);
6138 $row['accommodationDetails'] = json_decode($row['accommodationDetails'], true);
6139 array_push($response, $row);
6140
6141 }
6142
6143 /**
6144 *
6145 date_default_timezone_set($calendarAccount['timezone']);
6146 $start = strtotime($year . '-' . $month . '-' . $day . ' 00:00:00');
6147 $end = strtotime($year . '-' . $month . '-' . $day . ' 23:59:59');
6148 $response = array();
6149 global $wpdb;
6150 $table_name = $wpdb->prefix . "booking_package_booked_customers";
6151 $sql = $wpdb->prepare(
6152 "SELECT `key`,`accountKey`,`status`,`scheduleUnixTime`,`courseName`,`praivateData`,`accommodationDetails`, `cancellationToken` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` <= %d ORDER BY `scheduleUnixTime` ASC;",
6153 array(intval($calendarAccount), intval($start), intval($end))
6154 );
6155 var_dump($sql);
6156 $rows = $wpdb->get_results($sql, ARRAY_A);
6157 foreach ((array) $rows as $row) {
6158
6159 if(!isset($response[$row['accountKey']])){
6160
6161 $response[$row['accountKey']] = array();
6162
6163 }
6164
6165 $row['praivateData'] = json_decode($row['praivateData'], true);
6166 $row['accommodationDetails'] = json_decode($row['accommodationDetails'], true);
6167 array_push($response[$row['accountKey']], $row);
6168
6169 }
6170 */
6171
6172 return $response;
6173
6174 }
6175
6176 public function getCalendarList($month, $day, $year, $startOfWeek = 0){
6177
6178 #$month = 4;
6179 $weeks = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
6180 $timestamp = date('U');
6181 $last_day = date('t', mktime(0, 0, 0, $month, $day, $year));
6182 #$week_start_num = intval(date('w', mktime(0, 0, 0, $month, 1, $year))) - $startOfWeek;
6183 #$week_last_num = intval(date('w', mktime(0, 0, 0, $month, $last_day, $year))) - $startOfWeek;
6184 $week_start_num = intval(date('w', mktime(0, 0, 0, $month, 1, $year)));
6185 $week_last_num = intval(date('w', mktime(0, 0, 0, $month, $last_day, $year)));
6186
6187 $calendarList = array();
6188 if(intval($week_start_num) != $startOfWeek){
6189
6190 #$lastUnixTime = date('U', mktime(0, 0, 0, $month, 1, $year)) - 1;
6191 $lastUnixTime = intval(date('U', mktime(0, 0, 0, $month, 1, $year))) - 60;
6192 $lastYear = date('Y', $lastUnixTime);
6193 $lastMonth = date('m', $lastUnixTime);
6194 $endDay = intval(date('t', $lastUnixTime));
6195 $startDay = $endDay - intval(date('w', $lastUnixTime)) + $startOfWeek;
6196 #$startDay = date('j', strtotime("last ".$weeks[$startOfWeek]." of ".date('F', $lastUnixTime)." ".date('Y', $lastUnixTime)));
6197 for ($i = $endDay; $i > 0; $i--) {
6198
6199 if (date('w', mktime(0, 0, 0, date('n', $lastUnixTime), $i, date('Y', $lastUnixTime))) == $startOfWeek) {
6200
6201 $startDay = $i;
6202 break;
6203
6204 }
6205
6206 }
6207
6208 $key = intval($lastYear.$lastMonth);
6209 $calendarList[$key] = array(
6210 'startDay' => $startDay,
6211 'lastDay' => $endDay,
6212 'startWeek' => intval(date('w', mktime(0, 0, 0, $lastMonth, $startDay, $lastYear))),
6213 'lastWeek' => intval(date('w', $lastUnixTime)),
6214 'year' => $lastYear,
6215 'month' => intval($lastMonth),
6216 'day' => $startDay,
6217 'timestamp' => $timestamp
6218 );
6219
6220 }
6221
6222 $calendarList[intval($year.sprintf('%02d', $month))] = array('startDay' => 1, 'lastDay' => $last_day, 'startWeek' => $week_start_num, 'lastWeek' => $week_last_num, 'year' => $year, 'month' => intval($month), 'day' => 1, 'timestamp' => $timestamp);
6223
6224 #if(intval($week_last_num) >= $startOfWeek){
6225
6226 $lastUnixTime = intval(date('U', mktime(23, 60, 0, $month, $last_day, $year)));
6227 $lastYear = date('Y', $lastUnixTime);
6228 $lastMonth = date('m', $lastUnixTime);
6229 $endDay = 7 - intval(date('w', $lastUnixTime)) + $startOfWeek;
6230 #$endDay = date('j', strtotime("first ".$weeks[$startOfWeek]." of ".date('F', $lastUnixTime)." ".date('Y', $lastUnixTime))) - 1;
6231 $startOfWeek--;
6232 if ($startOfWeek < 0) {
6233
6234 $startOfWeek = 6;
6235
6236 }
6237
6238 for ($i = 1; $i <= intval(date('t', $lastUnixTime)); $i++) {
6239
6240 if (date('w', mktime(0, 0, 0, date('n', $lastUnixTime), $i, date('Y', $lastUnixTime))) == $startOfWeek) {
6241
6242 if ($i == 7) {
6243
6244 $endDay = 0;
6245
6246 } else {
6247
6248 $endDay = $i;
6249
6250 }
6251
6252 break;
6253
6254 }
6255
6256 }
6257
6258 $startDay = 1;
6259 $key = intval($lastYear.$lastMonth);
6260 $calendarList[$key] = array(
6261 'startDay' => $startDay,
6262 'lastDay' => $endDay,
6263 'startWeek' => intval(date('w', $lastUnixTime)),
6264 'lastWeek' => 6,
6265 'year' => $lastYear,
6266 'month' => intval($lastMonth),
6267 'day' => $startDay,
6268 'timestamp' => $timestamp,
6269 );
6270
6271 #}
6272
6273 return $calendarList;
6274
6275 }
6276
6277 public function fixUnixTimeShift($schedule, $timezone) {
6278
6279 global $wpdb;
6280 date_default_timezone_set($timezone);
6281 $trueUnixTime = date('U', mktime($schedule['hour'], $schedule['min'], 0, $schedule['month'], $schedule['day'], $schedule['year']));
6282 if (intval($trueUnixTime) != intval($schedule['unixTime'])) {
6283
6284 #$wpdb->query("START TRANSACTION");
6285 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE, `" . $wpdb->prefix . "booking_package_booked_customers" . "` WRITE");
6286 try {
6287
6288 $wpdb->update(
6289 $wpdb->prefix . "booking_package_schedules",
6290 array(
6291 'unixTime' => intval($trueUnixTime),
6292 ),
6293 array('key' => intval($schedule['key'])),
6294 array('%d'),
6295 array('%d')
6296 );
6297
6298 $wpdb->update(
6299 $wpdb->prefix . "booking_package_booked_customers",
6300 array(
6301 'scheduleUnixTime' => intval($trueUnixTime),
6302 ),
6303 array('scheduleKey' => intval($schedule['key'])),
6304 array('%d'),
6305 array('%d')
6306 );
6307
6308 #$wpdb->query('COMMIT');
6309 $wpdb->query('UNLOCK TABLES');
6310 $schedule['trueUnixTime'] = $trueUnixTime;
6311 $schedule['fixedUnixTime'] = true;
6312 $schedule['unixTime'] = $trueUnixTime;
6313 return $schedule;
6314
6315 } catch (Exception $e) {
6316
6317 #$wpdb->query('ROLLBACK');
6318 $wpdb->query('UNLOCK TABLES');
6319 $error = json_decode($e->getMessage(), true);
6320 return $error;
6321
6322 }
6323 /** finally {
6324
6325 $wpdb->query('UNLOCK TABLES');
6326
6327 }
6328 **/
6329
6330 } else {
6331
6332 return $schedule;
6333
6334 }
6335
6336 }
6337
6338 public function getCalendarAccountsWithHavingSchedulesSharing($accountKey) {
6339
6340 global $wpdb;
6341 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
6342 $sql = $wpdb->prepare(
6343 "SELECT `key`, `targetSchedules` FROM `" . $table_name . "` WHERE `targetSchedules` = %d AND `schedulesSharing` = 1;",
6344 array(intval($accountKey))
6345 );
6346 $rows = $wpdb->get_results($sql, ARRAY_A);
6347 return $rows;
6348
6349 }
6350
6351 public function getReservationData($month, $day, $year, $ical = false, $public = false) {
6352
6353 $accountKey = 1;
6354 $accountCalendarKey = 1;
6355 if(isset($_POST['accountKey'])){
6356
6357 $accountKey = $_POST['accountKey'];
6358 $accountCalendarKey = $_POST['accountKey'];
6359
6360 }
6361
6362 global $wpdb;
6363 $account = $this->getCalendarAccount($accountKey);
6364 date_default_timezone_set($account['timezone']);
6365 if (intval($account['schedulesSharing']) == 1) {
6366
6367 $accountCalendarKey = intval($account['targetSchedules']);
6368
6369 }
6370
6371 $reserveData = array();
6372 $changeMonth = false;
6373
6374 if ($ical === false) {
6375
6376 if (is_null($month) && is_null($day) !== true && is_null($year)) {
6377
6378 $month = date('m');
6379 $day = date('d');
6380 $year = date('Y');
6381
6382 }
6383
6384 if ($month != date('m') || $year != date('Y')) {
6385
6386 $day = 1;
6387
6388 } else {
6389
6390 $day = date('d');
6391
6392 }
6393
6394 if ($public !== false) {
6395
6396 #$unavailableDaysFromToday = get_option($this->prefix."unavailableDaysFromToday", 0) * (1440 * 60);
6397 $unavailableDaysFromToday = intval($account['unavailableDaysFromToday']) * (1440 * 60);
6398 $unixTime = date('U') + $unavailableDaysFromToday;
6399
6400 //if(date('U', mktime(0, 0, 0, $month, 1, $year)) < $unixTime){
6401 if (date('U', mktime(0, 0, 0, date('n'), 1, date('Y'))) < $unixTime) {
6402
6403 $changeMonth = true;
6404 $startMonth = date('m', $unixTime);
6405 $startDay = date('d', $unixTime);
6406 $startYear = date('Y', $unixTime);
6407
6408 if (date('U', mktime(0, 0, 0, $month, 1, $year)) < $unixTime) {
6409
6410 $month = date('m', $unixTime);
6411 $day = date('d', $unixTime);
6412 $year = date('Y', $unixTime);
6413
6414 }
6415
6416 }
6417
6418 }
6419
6420 }
6421
6422 $nationalHoliday = $this->getRegularHolidays($month, $year, 'national', $account['startOfWeek'], false);
6423 $regularHoliday = $this->getRegularHolidays($month, $year, $accountKey, $account['startOfWeek'], true);
6424
6425 $last_day = date('t', mktime(0, 0, 0, $month, $day, $year));
6426 $week_start_num = intval(date('w', mktime(0, 0, 0, $month, 1, $year)));
6427 $week_last_num = intval(date('w', mktime(0, 0, 0, $month, $last_day, $year)));
6428
6429 $maxDeadlineDay = date('U') + (BOOKING_PACKAGE_MAX_DEADLINE_TIME * 60);
6430
6431 if ($ical === false) {
6432
6433 $arrayValue = array(
6434 'startDay' => 1,
6435 'lastDay' => $last_day,
6436 'startWeek' => $week_start_num,
6437 'lastWeek' => $week_last_num,
6438 'year' => $year,
6439 'month' => intval($month),
6440 'day' => 1,
6441 'timestamp' => date('U'),
6442 'today' => intval(date('Ymd')),
6443 'maxDeadlineDay' => intval(date('Ymd', date('U') + (BOOKING_PACKAGE_MAX_DEADLINE_TIME * 60))),
6444 'firstMonth' => intval(date('U', mktime(0, 0, 0, $month, 1, $year))),
6445 'endMonth' => intval(date('U', mktime(23, 59, 59, $month, $last_day, $year)))
6446 );
6447 $reserveData['date'] = $arrayValue;
6448
6449 $calendarList = $this->getCalendarList($month, $day, $year, $account['startOfWeek']);
6450 $reserveData['calendarList'] = $calendarList;
6451 $days = array();
6452 $reservation = array();
6453 $reservationForHotel = array();
6454 $bookedHotel = array();
6455 $schedule = array();
6456 $bookedServices = array();
6457 $schedule_start_day = null;
6458 if ($public !== false && $changeMonth === true /**$month == date('n')**/) {
6459
6460 $schedule_start_day = intval(date('Ymd', mktime(0, 0, 0, $startMonth, $startDay, $startYear)));
6461 //$schedule_start_day = intval(date('Ymd', mktime(0, 0, 0, date('n'), date('j'), date('Y'))));
6462
6463 }
6464
6465 $reserveData['schedule_start_day'] = $schedule_start_day;
6466
6467 $override_date = null;
6468 $override_last_day = apply_filters( 'booking_package_frontend_available_days_from_today', intval($account['maxAccountScheduleDay']), intval($accountCalendarKey) );
6469 if (empty($override_last_day) === false && intval($override_last_day) < intval($account['maxAccountScheduleDay']) && $public !== false) {
6470
6471 $override_last_day = ( $override_last_day * (1440 * 60) ) + date('U');
6472 $override_date = intval( date('Ymd', $override_last_day) );
6473
6474 }
6475
6476 $visitorList = array();
6477 $number = 0;
6478 foreach ((array) $calendarList as $key => $value) {
6479
6480 for ($i = $value['startDay']; $i <= $value['lastDay']; $i++) {
6481
6482 $calendarUnixTime = date('U', mktime(0, 0, 0, $value['month'], $i, $value['year']));
6483 $week = date('w', mktime(0, 0, 0, $value['month'], $i, $value['year']));
6484 $scheduleKey = $value['year'] . sprintf("%02d%02d", $value['month'], $i);
6485 $arrayValue = array('key' => $scheduleKey, 'number' => $number, 'year' => $value['year'], 'month' => $value['month'], 'day' => $i, 'week' => $week, 'select' => 'false');
6486 $number++;
6487 $days[$scheduleKey] = $arrayValue;
6488
6489 $table_name = $wpdb->prefix . "booking_package_schedules";
6490 $sql = $wpdb->prepare(
6491 "SELECT *, `unixTime` - (`deadlineTime` * 60) as `unixTimeDeadline` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `year` = %d AND `month` = %d AND `day` = %d AND `holiday` = 'false' AND `status` = 'open' AND `publishingDate` = 0 AND (`stop` = 'false' OR `stop` = 'true') ORDER BY `unixTime`, `key` ASC;",
6492 array(intval($accountCalendarKey), intval($value['year']), intval($value['month']), intval($i))
6493 );
6494
6495 if ($public === false) {
6496
6497 $sql = $wpdb->prepare(
6498 "SELECT *, `unixTime` - (`deadlineTime` * 60) as `unixTimeDeadline` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `year` = %d AND `month` = %d AND `day` = %d AND `holiday` = 'false' AND `status` = 'open' AND (`stop` = 'false' OR `stop` = 'true') ORDER BY `unixTime`, `key` ASC;",
6499 array(intval($accountCalendarKey), intval($value['year']), intval($value['month']), intval($i))
6500 );
6501
6502 }
6503
6504 $key = intval($value['year'].sprintf("%02d%02d", $value['month'], $i));
6505 $rows = null;
6506 if (is_null($override_date) === true) {
6507
6508 $rows = $wpdb->get_results($sql, ARRAY_A);
6509
6510 } else if ($override_date > $key) {
6511
6512 $rows = $wpdb->get_results($sql, ARRAY_A);
6513
6514 }
6515
6516 #$rows = $wpdb->get_results($sql, ARRAY_A);
6517 if (is_null($rows)) {
6518
6519 $rows = array();
6520
6521 }
6522
6523 foreach ((array) $rows as $scheduleKey => $scheduleData) {
6524
6525 $rows[$scheduleKey] = $this->fixUnixTimeShift($scheduleData, $account['timezone']);
6526 $rows[$scheduleKey]['ymd'] = $key;
6527 $rows[$scheduleKey]['priceKeyByDayOfWeek'] = $nationalHoliday['calendar'][$key]['priceKeyByDayOfWeek'];
6528
6529 }
6530
6531 $schedule[$key] = $rows;
6532 if ($account['type'] == "hotel" && count($rows) > 0) {
6533
6534 $schedule[$key] = array($rows[0]);
6535
6536 }
6537
6538 if (isset($regularHoliday['calendar'][$key]) && intval($regularHoliday['calendar'][$key]['status']) == 1) {
6539
6540 if ($account['type'] == "hotel") {
6541
6542 if (isset($rows[0])) {
6543
6544 $schedule[$key][0]['remainder'] = 0;
6545
6546 }
6547
6548 } else {
6549
6550 $schedule[$key] = array();
6551
6552 }
6553
6554 }
6555
6556 if (count($rows) == 0 && $account['type'] == "hotel") {
6557
6558 #$schedule[$key] = array('unixTime' => date('U', mktime(0, 0, 0, $value['month'], $i, $value['year'])), "remainder" => 0);
6559 $schedule[$key] = array();
6560
6561 }
6562
6563 if (!is_null($schedule_start_day) && intval(date('Ymd', mktime(0, 0, 0, $value['month'], $i, $value['year']))) < $schedule_start_day) {
6564
6565 $schedule[$key] = array();
6566
6567 }
6568
6569 $startUnixTime = date('U', mktime(0, 0, 0, $value['month'], $i, $value['year']));
6570 $stopUnixTime = $startUnixTime + (1440 * 60);
6571 if ($public == false) {
6572
6573 $setting = new booking_package_setting($this->prefix, $this->pluginName);
6574 $numberKeys = $setting->getListOfDaysOfWeek();
6575
6576 $targetSchedules = array();
6577 if ($this->targetSchedules == 1) {
6578
6579 $rows = $this->getCalendarAccountsWithHavingSchedulesSharing($accountKey);
6580 if (is_null($rows) === false && count($rows) != 0) {
6581
6582 $deleteList = array();
6583 for ($row = 0; $row < count($rows); $row++) {
6584
6585 array_push($targetSchedules, '`accountKey` = ' . intval($rows[$row]['key']));
6586
6587 }
6588
6589 }
6590
6591 }
6592
6593 if (count($targetSchedules) > 0) {
6594
6595 $targetSchedules = ' || ' . implode(' || ', $targetSchedules);
6596
6597 } else {
6598
6599 $targetSchedules = '';
6600
6601 }
6602
6603 $reserveData['targetSchedules'] = $targetSchedules;
6604
6605 $visitorStatus = "";
6606 if (intval($account['displayDetailsOfCanceled']) == 0) {
6607
6608 $visitorStatus = "`status` != 'canceled' AND ";
6609 }
6610
6611 $table_name = $wpdb->prefix . "booking_package_booked_customers";
6612 $sql = $wpdb->prepare(
6613 "SELECT * FROM `" . $table_name . "` WHERE " . $visitorStatus . " (`accountKey` = %d" . $targetSchedules . ") AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` < %d ORDER BY `scheduleUnixTime` ASC;",
6614 array(intval($accountKey), $startUnixTime, $stopUnixTime)
6615 );
6616 if ($account['type'] == 'hotel') {
6617
6618 $sql = $wpdb->prepare(
6619 "SELECT * FROM `" . $table_name . "` WHERE " . $visitorStatus . " `accountKey` = %d AND `checkOut` >= %d AND `checkIn` < %d ORDER BY `scheduleUnixTime` ASC;",
6620 array(intval($accountKey), $startUnixTime, $stopUnixTime)
6621 );
6622
6623 }
6624
6625 $rows = $wpdb->get_results($sql, ARRAY_A);
6626 if (is_null($rows) === false && count($rows) != 0) {
6627
6628 $deleteList = array();
6629 for ($row = 0; $row < count($rows); $row++) {
6630 /**
6631 if ($account['type'] == 'hotel') {
6632
6633 $bookedHotel = $this->getBookedHotelDays($rows[$row], $bookedHotel);
6634
6635 }
6636 **/
6637 if (!isset($visitorList[$rows[$row]['key']])) {
6638
6639 $visitorList[$rows[$row]['key']] = 1;
6640 if ($rows[$row]['type'] == 'hotel' && intval($rows[$row]['checkIn']) != $startUnixTime) {
6641
6642 #continue;
6643 array_push($deleteList, $row);
6644
6645 }
6646
6647 } else {
6648
6649 $visitorList[$rows[$row]['key']]++;
6650 array_push($deleteList, $row);
6651
6652 }
6653
6654 $response = $this->getVistorsBookedList($rows[$row], $account['type'], $reservationForHotel, $numberKeys);
6655
6656 $response = apply_filters('booking_package_get_booked_customer', $response);
6657
6658 $rows[$row] = $response['bookedData'];
6659 $reservationForHotel = $response['reservationForHotel'];
6660
6661 }
6662
6663 arsort($deleteList);
6664 for ($deleteKey = 0; $deleteKey < count($deleteList); $deleteKey++) {
6665
6666 unset($rows[$deleteKey]);
6667
6668 }
6669
6670 if (count($rows) > 0) {
6671
6672 $reservation[$key] = $rows;
6673
6674 }
6675
6676 }
6677
6678 } else {
6679
6680 }
6681
6682 }
6683
6684 $table_name = $wpdb->prefix . "booking_package_schedules";
6685 $sql = $wpdb->prepare(
6686 "SELECT year,month,day,accountKey,SUM(capacity),SUM(remainder),COUNT(day) FROM `".$table_name."` GROUP BY `year`,`month`,`day`,`holiday`,`accountKey`,`status` HAVING `accountKey` = %d AND `year` = %d AND `month` = %d AND `day` >= %d AND `holiday` = 'false' AND `status` = 'open';",
6687 array(intval($accountCalendarKey), intval($value['year']), intval($value['month']), intval($day))
6688 );
6689
6690 if ($account['type'] == 'day' && intval($account['courseBool']) == 1) {
6691
6692 $bookedServices = $this->getBookedServices(
6693 $bookedServices,
6694 date('U', mktime(0, 0, 0, $value['month'], $value['startDay'], $value['year'])),
6695 date('U', mktime(23, 59, 0, $value['month'], $value['lastDay'], $value['year'])),
6696 $accountKey,
6697 $accountCalendarKey
6698 );
6699
6700 /**
6701 $table_name = $wpdb->prefix . "booking_package_booked_customers";
6702 $sql = $wpdb->prepare(
6703 "SELECT `accountKey`, `scheduleUnixTime`, `status`, `options` FROM `" . $table_name . "` WHERE (`accountKey` = %d OR `accountKey` = %d) AND (`scheduleUnixTime` >= %d AND `scheduleUnixTime` <= %d) AND (`status` = 'pending' OR `status` = 'approved') ORDER BY `scheduleUnixTime` ASC;",
6704 array(
6705 intval($accountKey),
6706 intval($accountCalendarKey),
6707 intval(date('U', mktime(0, 0, 0, $value['month'], $value['startDay'], $value['year']))),
6708 intval(date('U', mktime(23, 59, 0, $value['month'], $value['lastDay'], $value['year'])))
6709 )
6710 );
6711 $bookedRows = $wpdb->get_results($sql, ARRAY_A);
6712 foreach ((array) $bookedRows as $bookedKey => $bookedValue) {
6713
6714 $durationTime = 0;
6715 $dayKey = date('Ymd', $bookedValue['scheduleUnixTime']);
6716 $timeKey = date('Hi', $bookedValue['scheduleUnixTime']);
6717 $services = json_decode($bookedValue['options'], true);
6718 for ($i = 0; $i < count($services); $i++) {
6719
6720
6721 $service = $services[$i];
6722 $durationTime += intval($service['time']);
6723 $options = $service['options'];
6724 for ($o = 0; $o < count($options); $o++) {
6725
6726 if (intval($options[$o]['selected']) == 1) {
6727
6728 $durationTime += intval($options[$o]['time']);
6729
6730 }
6731
6732 }
6733
6734
6735 if (isset($bookedServices[$dayKey])) {
6736
6737 if (isset($bookedServices[$dayKey][$timeKey])) {
6738
6739 if (isset($bookedServices[$dayKey][$timeKey][$service['key']])) {
6740
6741 $bookedServices[$dayKey][$timeKey][$service['key']]['count']++;
6742 array_push($bookedServices[$dayKey][$timeKey][$service['key']]['durationTimes'], $durationTime);
6743 if ($bookedServices[$dayKey][$timeKey][$service['key']]['maximumDurationTime'] < $durationTime) {
6744
6745 $bookedServices[$dayKey][$timeKey][$service['key']]['maximumDurationTime'] = $durationTime;
6746
6747 }
6748
6749 } else {
6750
6751 $bookedServices[$dayKey][$timeKey][$service['key']] = array(
6752 'count' => 1,
6753 'maximumDurationTime' => $durationTime,
6754 'durationTimes' => array($durationTime)
6755 );
6756
6757 }
6758
6759 } else {
6760
6761 $bookedServices[$dayKey][$timeKey] = array(
6762 intval($service['key']) => array(
6763 'count' => 1,
6764 'maximumDurationTime' => $durationTime,
6765 'durationTimes' => array($durationTime)
6766 ),
6767 );
6768
6769 }
6770
6771 } else {
6772
6773 $bookedServices[$dayKey] = array(
6774 $timeKey => array(
6775 intval($service['key']) => array(
6776 'count' => 1,
6777 'maximumDurationTime' => $durationTime,
6778 'durationTimes' => array($durationTime)
6779 ),
6780 ),
6781 );
6782
6783 }
6784
6785 }
6786
6787 }
6788 **/
6789
6790 }
6791
6792 }
6793
6794
6795 foreach ($bookedHotel as $bookedHotelKey => $bookedHotelValue) {
6796
6797 $bookedHotel[$bookedHotelKey] = count($bookedHotelValue);
6798
6799 }
6800
6801 $reserveData['calendar'] = $days;
6802 $reserveData['schedule'] = $schedule;
6803 $reserveData['reservation'] = $reservation;
6804 $reserveData['reservationForHotel'] = $reservationForHotel;
6805 $reserveData['bookedHotel'] = $bookedHotel;
6806 $reserveData['regularHoliday'] = $regularHoliday;
6807 $reserveData['nationalHoliday'] = $nationalHoliday;
6808 $reserveData['bookedServices'] = $bookedServices;
6809
6810 /**
6811 if($public == false && $account->type == "hotel"){
6812
6813
6814
6815 }
6816 **/
6817
6818 }else{
6819
6820 $startUnixTime = date('U', mktime(0, 0, 0, $month, $day, $year));
6821 #echo $month.'/'.$day.'/'.$year."\n";
6822 #var_dump($startUnixTime);
6823 $table_name = $wpdb->prefix . "booking_package_booked_customers";
6824 $sql = $wpdb->prepare(
6825 "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `scheduleUnixTime` >= %d ORDER BY `scheduleUnixTime` ASC;",
6826 array(intval($accountKey), $startUnixTime)
6827 );
6828
6829 if (intval($account['displayDetailsOfCanceled']) == 0) {
6830
6831 $sql = $wpdb->prepare(
6832 "SELECT * FROM `".$table_name."` WHERE `status` != 'canceled' AND `accountKey` = %d AND `scheduleUnixTime` >= %d ORDER BY `scheduleUnixTime` ASC;",
6833 array(intval($accountKey), $startUnixTime)
6834 );
6835
6836 }
6837
6838 $rows = $wpdb->get_results($sql, ARRAY_A);
6839 if(is_null($rows) === false && count($rows) != 0){
6840
6841 for($row = 0; $row < count($rows); $row++){
6842
6843 $json = json_decode($rows[$row]['praivateData'], true);
6844 $rows[$row]['praivateData'] = $json;
6845 $unixTime = $rows[$row]['scheduleUnixTime'];
6846 $rows[$row]['date'] = array('unixTime' => $unixTime, 'month' => date('m', $unixTime), 'day' => date('d', $unixTime), 'year' => date('Y', $unixTime), 'week' => date('w', $unixTime), 'hour' => date('H', $unixTime), 'min' => date('i', $unixTime), 'timeZone' => date('e', $unixTime));
6847
6848 }
6849
6850 $reserveData = $rows;
6851
6852 }
6853
6854 }
6855
6856 return $reserveData;
6857
6858 }
6859
6860 public function getBookedHotelDays($customer, $bookedHotel) {
6861
6862 $checkIn = $customer['checkIn'];
6863 $checkOut = $customer['checkOut'];
6864 for ($dayCount = $checkIn; $dayCount < $checkOut; $dayCount += (1440 * 60)) {
6865
6866 $dateKey = date('Ymd', $dayCount);
6867 if (!isset($bookedHotel[$dateKey])) {
6868
6869 $bookedHotel[$dateKey] = array($customer['key']);
6870
6871 } else {
6872
6873 if (array_search($customer['key'], $bookedHotel[$dateKey]) === false) {
6874
6875 array_push($bookedHotel[$dateKey], $customer['key']);
6876
6877 }
6878
6879 }
6880
6881 }
6882
6883 return $bookedHotel;
6884
6885 }
6886
6887 public function getBookedServices($bookedServices, $start, $end, $accountKey, $accountCalendarKey = null) {
6888
6889 global $wpdb;
6890 $sql = null;
6891 $table_name = $wpdb->prefix . "booking_package_booked_customers";
6892 if (!is_null($accountCalendarKey)) {
6893
6894 $sql = $wpdb->prepare(
6895 "SELECT `accountKey`, `scheduleUnixTime`, `status`, `options` FROM `" . $table_name . "` WHERE (`accountKey` = %d OR `accountKey` = %d) AND (`scheduleUnixTime` >= %d AND `scheduleUnixTime` <= %d) AND (`status` = 'pending' OR `status` = 'approved') ORDER BY `scheduleUnixTime` ASC;",
6896 array(
6897 intval($accountKey),
6898 intval($accountCalendarKey),
6899 intval($start),
6900 intval($end)
6901 )
6902 );
6903
6904 } else {
6905
6906 $sql = $wpdb->prepare(
6907 "SELECT `accountKey`, `scheduleUnixTime`, `status`, `options` FROM `" . $table_name . "` WHERE `accountKey` = %d AND (`scheduleUnixTime` >= %d AND `scheduleUnixTime` <= %d) AND (`status` = 'pending' OR `status` = 'approved') ORDER BY `scheduleUnixTime` ASC;",
6908 array(
6909 intval($accountKey),
6910 intval($start),
6911 intval($end)
6912 )
6913 );
6914
6915 }
6916
6917 $bookedRows = $wpdb->get_results($sql, ARRAY_A);
6918 foreach ((array) $bookedRows as $bookedKey => $bookedValue) {
6919
6920 $durationTime = 0;
6921 $dayKey = date('Ymd', $bookedValue['scheduleUnixTime']);
6922 $timeKey = date('Hi', $bookedValue['scheduleUnixTime']);
6923 $services = json_decode($bookedValue['options'], true);
6924 for ($i = 0; $i < count($services); $i++) {
6925
6926
6927 $service = $services[$i];
6928 $durationTime += intval($service['time']);
6929 $options = $service['options'];
6930 for ($o = 0; $o < count($options); $o++) {
6931
6932 if (intval($options[$o]['selected']) == 1) {
6933
6934 $durationTime += intval($options[$o]['time']);
6935
6936 }
6937
6938 }
6939
6940
6941 if (isset($bookedServices[$dayKey])) {
6942
6943 if (isset($bookedServices[$dayKey][$timeKey])) {
6944
6945 if (isset($bookedServices[$dayKey][$timeKey][$service['key']])) {
6946
6947 $bookedServices[$dayKey][$timeKey][$service['key']]['count']++;
6948 array_push($bookedServices[$dayKey][$timeKey][$service['key']]['durationTimes'], $durationTime);
6949 if ($bookedServices[$dayKey][$timeKey][$service['key']]['maximumDurationTime'] < $durationTime) {
6950
6951 $bookedServices[$dayKey][$timeKey][$service['key']]['maximumDurationTime'] = $durationTime;
6952
6953 }
6954
6955 } else {
6956
6957 $bookedServices[$dayKey][$timeKey][$service['key']] = array(
6958 'count' => 1,
6959 'maximumDurationTime' => $durationTime,
6960 'durationTimes' => array($durationTime)
6961 );
6962
6963 }
6964
6965 } else {
6966
6967 $bookedServices[$dayKey][$timeKey] = array(
6968 intval($service['key']) => array(
6969 'count' => 1,
6970 'maximumDurationTime' => $durationTime,
6971 'durationTimes' => array($durationTime)
6972 ),
6973 );
6974
6975 }
6976
6977 } else {
6978
6979 $bookedServices[$dayKey] = array(
6980 $timeKey => array(
6981 intval($service['key']) => array(
6982 'count' => 1,
6983 'maximumDurationTime' => $durationTime,
6984 'durationTimes' => array($durationTime)
6985 ),
6986 ),
6987 );
6988
6989 }
6990
6991 }
6992
6993 }
6994
6995 return $bookedServices;
6996
6997 }
6998
6999
7000 public function getUsersBookedList($user_id, $locale = 'en_US', $offset = 0, $cancel = false) {
7001
7002 global $wpdb;
7003
7004 $setting = new booking_package_setting($this->prefix, $this->pluginName);
7005 $numberKeys = $setting->getListOfDaysOfWeek();
7006
7007 $limit = 20;
7008 $table_name = $wpdb->prefix . "booking_package_booked_customers";
7009 $sql = $wpdb->prepare(
7010 "SELECT * FROM `" . $table_name . "` WHERE `user_id` = %d ORDER BY `scheduleUnixTime` DESC, `key` DESC LIMIT %d, %d;",
7011 array(intval($user_id), intval($offset), intval($limit))
7012 );
7013
7014 $rows = $wpdb->get_results($sql, ARRAY_A);
7015 if(is_null($rows) === false && count($rows) != 0){
7016
7017 $deleteList = array();
7018 for($row = 0; $row < count($rows); $row++){
7019
7020 $response = $this->getVistorsBookedList($rows[$row], $rows[$row]['type'], array(), $numberKeys);
7021 if ($cancel === true) {
7022
7023 $response['bookedData']['cancel'] = 0;
7024 $cancelFlag = $this->verifyCancellation($response['bookedData'], true, $user_id);
7025 if ($cancelFlag['cancel'] === true) {
7026
7027 $response['bookedData']['cancel'] = 1;
7028
7029 }
7030
7031 }
7032 $rows[$row] = $response['bookedData'];
7033
7034 }
7035
7036 }
7037
7038 $size = count(array_keys($rows));
7039 $next = 1;
7040 if ($size < $limit) {
7041
7042 $next = 0;
7043
7044 }
7045
7046 $formFields = $setting->getUserInputFields();
7047 for ($i = 0; $i < count($formFields); $i++) {
7048
7049 $formFields[$i] = $setting->getTranslateFormField($formFields[$i], null, $locale, 'user_profile');
7050
7051 }
7052
7053 return array('status' => 'success', 'bookedList' => $rows, 'limit' => intval($limit), 'offset' => intval($offset), 'size' => intval($size), 'next' => $next, 'formFields' => $formFields);
7054
7055 }
7056
7057 public function getVistorsBookedList($bookedData, $type, $reservationForHotel, $numberKeys) {
7058
7059 if (empty($bookedData['status'])) {
7060
7061 $bookedData['status'] = 'pending';
7062
7063 }
7064
7065 if (empty($bookedData['guests'])) {
7066
7067 $bookedData['guests'] = array();
7068
7069 } else {
7070
7071 $guests = json_decode($bookedData['guests'], true);
7072 $bookedData['guests'] = $guests;
7073
7074 }
7075
7076 if (empty($bookedData['coupon'])) {
7077
7078 $bookedData['coupon'] = array();
7079
7080 } else {
7081
7082 $coupon = json_decode($bookedData['coupon'], true);
7083 $bookedData['coupon'] = $coupon;
7084
7085 }
7086
7087 $json = json_decode($bookedData['praivateData'], true);
7088 $bookedData['praivateData'] = $json;
7089
7090 $json = json_decode($bookedData['options'], true);
7091 $bookedData['options'] = $json;
7092
7093 #$bookedData['taxes'] = json_decode($bookedData['taxes'], true);
7094 $taxes = json_decode($bookedData['taxes'], true);
7095 if ($taxes === false || is_null($taxes)) {
7096
7097 $bookedData['taxes'] = array();
7098
7099 } else {
7100
7101 $bookedData['taxes'] = $taxes;
7102
7103 }
7104
7105
7106 $unixTime = $bookedData['scheduleUnixTime'];
7107 $bookedData['date'] = array(
7108 'month' => date('n', $unixTime),
7109 'day' => date('d', $unixTime),
7110 'year' => date('Y', $unixTime),
7111 'week' => date('w', $unixTime),
7112 'hour' => date('H', $unixTime),
7113 'min' => date('i', $unixTime),
7114 'timeZone' => date('e', $unixTime),
7115 'checkIn' => 0,
7116 'checkOut' => 0,
7117 'key' => date('Y', $unixTime) . date('m', $unixTime) . date('d', $unixTime)
7118 );
7119
7120 $timestamp = $bookedData['reserveTime'];
7121 $bookedData['timestamp'] = array(
7122 'month' => date('n', $timestamp),
7123 'day' => date('d', $timestamp),
7124 'year' => date('Y', $timestamp),
7125 'week' => date('w', $timestamp),
7126 'hour' => date('H', $timestamp),
7127 'min' => date('i', $timestamp),
7128 'timeZone' => date('e', $timestamp),
7129 );
7130
7131 if ($type == "hotel") {
7132
7133 $bookedData['date']['checkIn'] = date('Ymd', $bookedData['checkIn']);
7134 $bookedData['date']['checkOut'] = date('Ymd', $bookedData['checkOut']);
7135 $bookedData['date']['checkIn_month'] = date('n', $bookedData['checkIn']);
7136 $bookedData['date']['checkIn_day'] = date('j', $bookedData['checkIn']);
7137 $bookedData['date']['checkIn_year'] = date('Y', $bookedData['checkIn']);
7138 $bookedData['date']['checkIn_week'] = date('w', $bookedData['checkIn']);
7139 $bookedData['date']['checkOut_month'] = date('n', $bookedData['checkOut']);
7140 $bookedData['date']['checkOut_day'] = date('j', $bookedData['checkOut']);
7141 $bookedData['date']['checkOut_year'] = date('Y', $bookedData['checkOut']);
7142 $bookedData['date']['checkOut_week'] = date('w', $bookedData['checkOut']);
7143
7144 $bookedData['accommodationDetails'] = json_decode($bookedData['accommodationDetails'], true);
7145 if (isset($bookedData['accommodationDetails']['rooms']) === false) {
7146
7147 $bookedData['accommodationDetails']['rooms'] = null;
7148
7149 }
7150 if (!isset($bookedData['accommodationDetails']['taxesFee'])) {
7151
7152 $bookedData['accommodationDetails']['taxesFee'] = 0;
7153
7154 }
7155
7156 if (is_null($bookedData['accommodationDetails']['rooms'])) {
7157
7158 $bookedData['accommodationDetails']['applicantCount'] = 1;
7159 $bookedData['accommodationDetails']['rooms'] = $this->createRooms($bookedData['accommodationDetails']);
7160
7161 } else {
7162 #var_dump($bookedData['accommodationDetails']['rooms']);
7163 for ($i = 0; $i < count($bookedData['accommodationDetails']['rooms']); $i++) {
7164
7165 $guests = $bookedData['accommodationDetails']['rooms'][$i]['guests'];
7166 $guestsList = $bookedData['accommodationDetails']['rooms'][$i]['guestsList'];
7167 foreach ((array) $guestsList as $key => $guest) {
7168
7169 $guests[$key] = $this->updatePricesForGuest(array($guests[$key]), $numberKeys);
7170 $guestsList[$key]['json'] = $this->updatePricesForGuest($guestsList[$key]['json'], $numberKeys);
7171 $bookedData['accommodationDetails']['rooms'][$i]['guests'][$key] = $guests[$key][0];
7172 $bookedData['accommodationDetails']['rooms'][$i]['guestsList'][$key]['json'] = $guestsList[$key]['json'];
7173
7174 }
7175
7176 }
7177
7178 }
7179
7180 $start_timestamp = strtotime( date('Y-m-d', $bookedData['checkIn']) );
7181 $end_timestamp = strtotime( date('Y-m-d', $bookedData['checkOut']) );
7182 $days_difference = ($end_timestamp - $start_timestamp) / (60 * 60 * 24);
7183 $days_diff = (strtotime( date('Y-m-d', $bookedData['checkOut']) ) - strtotime( date('Y-m-d', $bookedData['checkIn']) ) ) / (60 * 60 * 24);
7184 $days_diff = round($days_diff);
7185 for ($i = 0; $i <= $days_diff; $i++) {
7186
7187 #$new_unix_timestamp = strtotime(date('Y-m-d', $bookedData['checkIn'])) + ($i * 24 * 60 * 60);
7188 #$dateKey = date('Ymd', $new_unix_timestamp);
7189
7190 $n_days_later_timestamp = strtotime("+" . $i . " days", $start_timestamp);
7191 $dateKey = date('Ymd', $n_days_later_timestamp);
7192
7193 if (!isset($reservationForHotel[$dateKey])) {
7194
7195 $reservationForHotel[$dateKey] = array();
7196
7197 }
7198
7199 $reservationForHotel[$dateKey][$bookedData['key']] = $bookedData;
7200
7201 }
7202 /**
7203 $time = intval($bookedData['checkIn']);
7204 while ($time <= intval($bookedData['checkOut'])) {
7205
7206 $dateKey = date('Ymd', $time);
7207 if (!isset($reservationForHotel[$dateKey])) {
7208
7209 $reservationForHotel[$dateKey] = array();
7210
7211 }
7212
7213 $reservationForHotel[$dateKey][$bookedData['key']] = $bookedData;
7214 $time += 1440 * 60;
7215
7216 }
7217 **/
7218
7219 } else {
7220
7221 $bookedData = $this->updateVistorService($bookedData);
7222 $bookedData['test'] = 1;
7223
7224 }
7225
7226 return array('bookedData' => $bookedData, 'reservationForHotel' => $reservationForHotel);
7227 #return $bookedData;
7228
7229 }
7230
7231 public function createRooms($accommodationDetails) {
7232
7233 #$numberKeys = $setting->getListOfDaysOfWeek();
7234 $guests = array();
7235 $amount = 0;
7236 foreach ((array) $accommodationDetails['guestsList'] as $key => $guest) {
7237
7238 $guestList = $guest['json'];
7239 for ($i = 0; $i < count($guestList); $i++) {
7240
7241 $selected = intval($guestList[$i]['selected']);
7242 unset($guestList[$i]['selected']);
7243 if ($i == 0) {
7244
7245 $guests[$key] = $guestList[$i];
7246
7247 }
7248
7249 if ($selected == 1) {
7250
7251 $guests[$key] = $guestList[$i];
7252 $amount += intval($guestList[$i]['price']);
7253 break;
7254
7255 }
7256
7257 }
7258
7259 }
7260
7261 if (isset($accommodationDetails['adult']) === false) {
7262
7263 $accommodationDetails['adult'] = 0;
7264
7265 }
7266
7267 if (isset($accommodationDetails['children']) === false) {
7268
7269 $accommodationDetails['children'] = 0;
7270
7271 }
7272
7273 $room = array(
7274 'booking' => true,
7275 'requiredGuests' => true,
7276 'guests' => $guests,
7277 'adult' => $accommodationDetails['adult'],
7278 'children' => $accommodationDetails['children'],
7279 'person' => $accommodationDetails['adult'] + $accommodationDetails['children'],
7280 'amount' => $amount,
7281 'additionalFee' => $amount,
7282 'guestsList' => $accommodationDetails['guestsList'],
7283 'createdRoor' => 1,
7284 );
7285 $rooms = array($room);
7286 return $rooms;
7287
7288 }
7289
7290 public function updateVistorService($visitor) {
7291
7292 if (empty($visitor['courseKey']) === false) {
7293
7294 $service = array(
7295 "key" => $visitor['courseKey'],
7296 "accountKey" => $visitor['accountKey'],
7297 "name" => $visitor['courseName'],
7298 "time" => $visitor['courseTime'],
7299 "cost" => $visitor['courseCost'],
7300 "active" => "true",
7301 "service" => 1,
7302 "selected" => 1,
7303 "options" => array(),
7304 );
7305
7306 if (count($visitor['options']) > 0) {
7307
7308 $service["options"] = $visitor['options'];
7309
7310 }
7311
7312 $visitor['courseKey'] = null;
7313 $visitor['courseName'] = null;
7314 $visitor['courseTime'] = null;
7315 $visitor['courseCost'] = null;
7316
7317 $visitor['options'] = array($service);
7318
7319 }
7320
7321 if (isset($visitor['options']) === false) {
7322
7323 $visitor['options'] = array();
7324
7325 }
7326
7327 return $visitor;
7328
7329 }
7330
7331 public function getDownloadCSV(){
7332
7333 global $wpdb;
7334 $response = array("status" => "success", "csv" => null);
7335 $customersList = array();
7336 $csv = '';
7337 $calendarAccount = $this->getCalendarAccount($_POST['accountKey']);
7338 date_default_timezone_set($calendarAccount['timezone']);
7339 $currency = get_option($this->prefix."currency", 'usd');
7340 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
7341 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
7342
7343 $table_name = $wpdb->prefix . "booking_package_booked_customers";
7344 $startUnixTime = 0;
7345 $stopUnixTime = 0;
7346 if (isset($_POST['day']) && $_POST['day'] != '') {
7347
7348 $startUnixTime = date('U', mktime(0, 0, 0, intval($_POST['month']), intval($_POST['day']), intval($_POST['year'])));
7349 $stopUnixTime = date('U', mktime(23, 59, 59, intval($_POST['month']), intval($_POST['day']), intval($_POST['year'])));
7350
7351 } else {
7352
7353 $lastDay = date('t', mktime(0, 0, 0, intval($_POST['month']), 1, intval($_POST['year'])));
7354 $startUnixTime = date('U', mktime(0, 0, 0, intval($_POST['month']), 1, intval($_POST['year'])));
7355 $stopUnixTime = date('U', mktime(23, 59, 59, intval($_POST['month']), intval($lastDay), intval($_POST['year'])));
7356
7357 }
7358 $sql = $wpdb->prepare(
7359 "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` < %d ORDER BY `key` ASC;",
7360 array(intval($_POST['accountKey']), $startUnixTime, $stopUnixTime)
7361 );
7362 $rows = $wpdb->get_results($sql, ARRAY_A);
7363 foreach ((array) $rows as $row) {
7364
7365 $guestsList = array();
7366 $guests = json_decode($row['guests'], true);
7367 //if (is_null($guests) === false && isset($guests['guests'])) {
7368 if (is_null($guests) === false && array_key_exists('guests', $guests) === true && is_null($guests['guests']) === false ) {
7369
7370 $reflectAdditional = intval($guests['reflectAdditional']);
7371 $reflectAdditionalTitle = $guests['reflectAdditionalTitle'];
7372 $reflectService = intval($guests['reflectService']);
7373 $reflectServiceTitle = $guests['reflectServiceTitle'];
7374 $guestsList = $guests['guests'];
7375
7376 }
7377
7378 $customer = array(
7379 "key" => $row['key'],
7380 "status" => $row['status'],
7381 );
7382
7383 if ($calendarAccount['type'] == 'day') {
7384
7385 $customer['scheduleDate'] = $this->dateFormat($dateFormat, $positionOfWeek, $row['scheduleUnixTime'], $row['scheduleTitle'], true, false, 'text');
7386 $customer['services'] = array();
7387 $customer['guests'] = array();
7388 $customer['coupon'] = null;
7389 $customer['amount'] = 0;
7390
7391 $coupon = null;
7392 if (isset($row['coupon']) && !empty($row['coupon'])) {
7393
7394 $coupon = json_decode($row['coupon'], true);
7395 $customer['coupon'] = $coupon['name'] . ' (' . $coupon['id'] . ')';
7396
7397 }
7398
7399 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
7400 $selectedOptionsObject = $this->getSelectedOptions($calendarAccount, $row['options'], $responseGuests['guests']);
7401 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $row['applicantCount'], false);
7402 $services = $servicesDetails['object'];
7403 $customer['amount'] += $servicesDetails['cost'];
7404
7405 foreach ((array) $services as $service) {
7406
7407 array_push($customer['services'], $service['name']);
7408 foreach ((array) $service['options'] as $option) {
7409
7410 if (intval($option['selected']) == 1) {
7411
7412 #$amount += intval($option['cost']) * $reflectService;
7413 array_push($customer['services'], $option['name']);
7414
7415 }
7416
7417 }
7418
7419 }
7420
7421 $guestsList = array();
7422 if (is_null($responseGuests) === false && isset($responseGuests['guests'])) {
7423
7424 $guestsList = $responseGuests['guests'];
7425
7426 }
7427
7428 for ($i = 0; $i < count($guestsList); $i++) {
7429
7430 $guest = $guestsList[$i];
7431 $index = intval($guest['index']);
7432 if ($index > 0) {
7433
7434 array_push($customer['guests'], $guest['name'].": ".$guest['json'][$index]['name']);
7435
7436 }
7437
7438 }
7439
7440 $customer['services'] = implode(' ', $customer['services']);
7441 $customer['guests'] = implode(" ", $customer['guests']);
7442 $taxes = json_decode($row['taxes'], true);
7443 foreach ((array) $taxes as $tax) {
7444
7445 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_exclusive') {
7446
7447 $customer['amount'] += intval($tax['taxValue']);
7448
7449 } else if ($tax['type'] == 'surcharge') {
7450
7451 $customer['amount'] += intval($tax['taxValue']);
7452
7453 }
7454
7455 }
7456
7457 } else {
7458
7459 $customer['checkIn'] = $this->dateFormat($dateFormat, $positionOfWeek, $row['checkIn'], null, false, false, 'text');
7460 $customer['checkOut'] = $this->dateFormat($dateFormat, $positionOfWeek, $row['checkOut'], null, false, false, 'text');
7461 $accommodationDetails = json_decode($row['accommodationDetails'], true);
7462 $customer['adults'] = 0;
7463 $customer['children'] = 0;
7464 $customer['amount'] = intval($accommodationDetails['totalCost']);
7465
7466 for ($i = 0; $i < count($accommodationDetails['rooms']); $i++) {
7467
7468 $customer = (function($guests, $customer) {
7469
7470 foreach ((array) $guests as $guest) {
7471
7472 foreach ((array) $guest['json'] as $value) {
7473
7474 if (intval($value['selected']) == 1) {
7475
7476 if ($guest['target'] == 'adult') {
7477
7478 $customer['adults'] += intval($value['number']);
7479
7480 } else {
7481
7482 $customer['children'] += intval($value['number']);
7483
7484 }
7485
7486 }
7487
7488 }
7489
7490 }
7491
7492 return $customer;
7493
7494 })($accommodationDetails['rooms'][$i]['guestsList'], $customer);
7495
7496 $customer = (function($options, $customer) {
7497
7498 foreach ((array) $options as $option) {
7499
7500 $name = $option['name'];
7501 foreach ((array) $option['json'] as $value) {
7502
7503 if (intval($value['selected']) == 1) {
7504
7505 $customer['option_' . $option['key']] = $option['name'] . ': ' . $value['name'];
7506 break;
7507
7508 }
7509
7510 }
7511
7512 }
7513
7514 return $customer;
7515
7516 })($accommodationDetails['rooms'][$i]['optionsList'], $customer);
7517
7518 }
7519
7520 /**
7521 foreach ((array) $accommodationDetails['guestsList'] as $guest) {
7522
7523 foreach ((array) $guest['json'] as $value) {
7524
7525 if (intval($value['selected']) == 1) {
7526
7527 if ($guest['target'] == 'adult') {
7528
7529 $customer['adults'] += intval($value['number']);
7530
7531 } else {
7532
7533 $customer['children'] += intval($value['number']);
7534
7535 }
7536
7537 }
7538
7539 }
7540
7541 }
7542 **/
7543
7544 $customer['adults'] = 'Adults: ' . $customer['adults'];
7545 $customer['children'] = 'Children: ' . $customer['children'];
7546
7547 }
7548
7549 $customer['amount'] = $this->formatCost($customer['amount'], $currency);
7550 $praivateData = json_decode($row['praivateData'], true);
7551 for ($i = 0; $i < count($praivateData); $i++) {
7552
7553 $id = "form_".$praivateData[$i]['id'];
7554 if (is_string($praivateData[$i]['value'])) {
7555
7556 $customer[$id] = $praivateData[$i]['value'];
7557
7558 } else if (is_array($praivateData[$i]['value'])) {
7559
7560 $customer[$id] = implode(' ', $praivateData[$i]['value']);
7561
7562 }
7563
7564 }
7565
7566 $customer = apply_filters('booking_package_download_booked_customer', $customer);
7567 array_push($customersList, $customer);
7568 $csv .= implode(",", $customer) . "\r\n";
7569
7570 }
7571
7572 $lineBreakCodes = get_option($this->prefix . 'lineBreakCodesInCsv', 'LF');
7573
7574 $temp = tmpfile();
7575 $path = stream_get_meta_data($temp)['uri'];
7576 $fp = fopen($path, 'w');
7577 foreach ((array) $customersList as $key => $value) {
7578
7579
7580 if ($lineBreakCodes === 'LF') {
7581
7582 fputcsv($fp, $value);
7583
7584 } else {
7585
7586 #$value = implode(',', $value) . "\r\n";
7587 #fwrite($fp, $value);
7588 fwrite($fp, rtrim(fputcsv($fp, $value, ',', "\"", "\\", "")) . "\r\n");
7589
7590 }
7591
7592 }
7593 fseek($fp, 0);
7594 $csv = file_get_contents($path);
7595 fclose($temp);
7596
7597
7598 $response['rows'] = $rows;
7599 $response['customersList'] = $customersList;
7600 $response['calendarAccount'] = $calendarAccount;
7601 $response['csv'] = $csv;
7602 return $response;
7603
7604 }
7605
7606 public function serachCoupons($unixTime, $couponID, $accountKey) {
7607
7608 #$currentDate = intval(date('Ymd'));
7609 $currentDate = intval(date('Ymd', $unixTime));
7610 $response = array('status' => 0, 'coupon' => array(), 'currentDate' => $currentDate, 'message' => '');
7611 global $wpdb;
7612 $table_name = $wpdb->prefix . "booking_package_coupons";
7613 $sql = $wpdb->prepare(
7614 "SELECT * FROM " . $table_name . " WHERE `active` = 1 AND `status` = 'active' AND `accountKey` = %d AND `id` = %s;",
7615 array(
7616 intval($accountKey),
7617 sanitize_text_field(trim($couponID))
7618 )
7619 );
7620 $coupon = $wpdb->get_row($sql, ARRAY_A);
7621 if (!empty($coupon)) {
7622
7623 if ($coupon['target'] == 'users') {
7624
7625 $user = $this->get_user();
7626 if (intval($user['status']) == 1) {
7627
7628 $user_login = $user['user']['user_login'];
7629 if ($coupon['limited'] == 'limited') {
7630
7631 $table_name = $wpdb->prefix . "booking_package_booked_customers";
7632 $sql = $wpdb->prepare(
7633 "SELECT COUNT(`key`) FROM " . $table_name . " WHERE `user_login` = %s AND `couponKey` = %d;",
7634 array(
7635 sanitize_text_field($user_login),
7636 intval($coupon['key']),
7637 )
7638 );
7639 $usedCoupon = $wpdb->get_row($sql, ARRAY_A);
7640 $response['usedCoupon'] = intval($usedCoupon['COUNT(`key`)']);
7641 if (intval($usedCoupon['COUNT(`key`)']) > 0) {
7642
7643 $response['message'] = sprintf(__('You have already used the coupon code of "%s".', 'booking-package'), esc_html($couponID));
7644 return $response;
7645
7646 }
7647
7648 }
7649
7650 } else {
7651
7652 $response['message'] = sprintf(__('Not found the coupon code of "%s".', 'booking-package'), esc_html($couponID)) . " \nCause: 1";
7653 return $response;
7654
7655 }
7656
7657 }
7658
7659 if (intval($coupon['expirationDateStatus']) == 1) {
7660
7661 $isBooking = $this->validExpirationDate($currentDate, $coupon['expirationDateStatus'], $coupon['expirationDateFrom'], $coupon['expirationDateTo']);
7662 $response['isBooking'] = $isBooking;
7663 if ($isBooking === false) {
7664
7665 $response['message'] = sprintf(__('Not found the coupon code of "%s".', 'booking-package'), esc_html($couponID) ) . " \nCause: 2";
7666 return $response;
7667
7668 }
7669
7670 }
7671
7672 $string_array = array('name' => $coupon['name'], 'description' => $coupon['description'], 'options' => array() );
7673 $translated_texts = apply_filters('booking_package_get_translate_text', $string_array, 'coupon', $coupon['id'], intval($accountKey), get_locale() );
7674 if (is_array($translated_texts) && array_key_exists('name', $translated_texts) && array_key_exists('description', $translated_texts) ) {
7675
7676 $coupon['name'] = $translated_texts['name'];
7677 $coupon['description'] = $translated_texts['description'];
7678
7679 }
7680
7681 $response['status'] = 1;
7682 $response['coupon'] = $coupon;
7683
7684 } else {
7685
7686 $response['message'] = sprintf(__('Not found the coupon code of "%s".', 'booking-package'), esc_html($couponID) ) . " \nCause: 3";
7687
7688 }
7689
7690 return $response;
7691
7692 }
7693
7694 public function serachCourse($accountKey, $scheduleKey, $key = false, $servicesDetails = null, $bookingYMD = null, $time = false, $bookingID = null){
7695
7696 global $wpdb;
7697
7698 $table_name = $wpdb->prefix . "booking_package_schedules";
7699 $sql = $wpdb->prepare(
7700 "SELECT * FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
7701 array(intval($scheduleKey))
7702 );
7703 $schedule = $wpdb->get_row($sql, ARRAY_A);
7704
7705 $table_name = $wpdb->prefix . "booking_package_services";
7706 if ($key !== false) {
7707
7708 $sql = $wpdb->prepare(
7709 "SELECT `key`, `name`, `time`, `cost`, `expirationDateStatus`, `expirationDateFrom`, `expirationDateTo`, `stopServiceUnderFollowingConditions`, `doNotStopServiceAsException`, `stopServiceForDayOfTimes`, `stopServiceForSpecifiedNumberOfTimes` FROM `".$table_name."` WHERE `accountKey` = %d AND `key` = %d LIMIT 0, 1;",
7710 array(intval($accountKey), intval($key))
7711 );
7712
7713 }
7714
7715 if ($time !== false) {
7716
7717 $sql = $wpdb->prepare(
7718 "SELECT `key`, `name`, `time`, `cost`, `expirationDateStatus`, `expirationDateFrom`, `expirationDateTo`, `stopServiceUnderFollowingConditions`, `doNotStopServiceAsException`, `stopServiceForDayOfTimes`, `stopServiceForSpecifiedNumberOfTimes` FROM `".$table_name."` WHERE `accountKey` = %d AND `time` = %d LIMIT 0, 1;",
7719 array(intval($accountKey), intval($time))
7720 );
7721
7722 }
7723 $row = $wpdb->get_row($sql, ARRAY_A);
7724 if (is_null($row)) {
7725
7726 return array('status' => 'error', 'message' => sprintf(__('%s was not found', 'booking-package'), 'Service'));
7727
7728 } else {
7729
7730 $isExtensionsValid = $this->getExtensionsValid();
7731 if ($isExtensionsValid !== true) {
7732
7733 $row['stopServiceUnderFollowingConditions'] = 'doNotStop';
7734
7735 }
7736
7737 $isBooking = $this->validExpirationDate(intval($bookingYMD), intval($row['expirationDateStatus']), intval($row['expirationDateFrom']), intval($row['expirationDateTo']));
7738 if ($isBooking === false) {
7739
7740 return array('status' => 'error', 'message' => sprintf(__('%s was not found', 'booking-package'), $row['name']));
7741
7742 }
7743
7744 $stopServiceUnderFollowingConditions = $this->stopServiceUnderFollowingConditions($accountKey, $scheduleKey, $schedule, $row, $servicesDetails, $bookingYMD, $bookingID);
7745 if ($stopServiceUnderFollowingConditions['status'] === false) {
7746
7747 #return array('status' => 'error', 'message' => sprintf(__('%s was not found', 'booking-package'), $row['name']) . " #2");
7748 return array('status' => 'error', 'message' => __('Error', 'booking-package') . "\n" . __('Service', 'booking-package') . ': ' . $row['name'] . "\n" . $stopServiceUnderFollowingConditions['message'] . ' #2');
7749
7750 }
7751
7752 return $row;
7753
7754 }
7755
7756 }
7757
7758 public function stopServiceUnderFollowingConditions($accountKey, $scheduleKey, $schedule, $requestService, $servicesDetails, $bookingYMD, $bookingID) {
7759
7760 global $wpdb;
7761 $response = array('status' => true, 'message' => '');
7762 $hasServices = array();
7763 $timeSlots = array();
7764 $bookingIDs = array();
7765 $table_name = $wpdb->prefix . "booking_package_booked_customers";
7766 if ($requestService['stopServiceUnderFollowingConditions'] == 'specifiedNumberOfTimes' && $requestService['stopServiceForDayOfTimes'] == 'timeSlot') {
7767
7768 $selectedService = $servicesDetails['object'][0];
7769 $start_unixTime = $schedule['unixTime'];
7770 $end_unixTime = intval($start_unixTime) + ($servicesDetails['time'] * 60);
7771 $sql = $wpdb->prepare(
7772 "SELECT `accountKey`, `status`, `scheduleUnixTime`, `options` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` < %d AND `status` != 'canceled' ORDER BY `scheduleUnixTime` ASC;",
7773 array(intval($accountKey), intval($start_unixTime), intval($end_unixTime) )
7774 );
7775
7776 if (is_null($bookingID) === false) {
7777
7778 $sql = $wpdb->prepare(
7779 "SELECT `accountKey`, `status`, `scheduleUnixTime`, `options` FROM `" . $table_name . "` WHERE `key` != %d AND `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` < %d AND `status` != 'canceled' ORDER BY `scheduleUnixTime` ASC;",
7780 array(intval($bookingID), intval($accountKey), intval($start_unixTime), intval($end_unixTime) )
7781 );
7782
7783 }
7784
7785 $rows = $wpdb->get_results($sql, ARRAY_A);
7786 foreach ((array) $rows as $row) {
7787
7788 $scheduleUnixTime = intval($row['scheduleUnixTime']);
7789 #var_dump($scheduleUnixTime);
7790 $services = json_decode($row['options'], true);
7791 for ($i = 0; $i < count($services); $i++) {
7792
7793 $serviceKey = intval($services[$i]['key']);
7794 if (intval($selectedService['key']) === $serviceKey) {
7795
7796 if (isset($timeSlots[$scheduleUnixTime])) {
7797
7798 $timeSlots[$scheduleUnixTime]++;
7799
7800 } else {
7801
7802 $timeSlots[$scheduleUnixTime] = 1;
7803
7804 }
7805
7806 }
7807
7808 }
7809
7810 }
7811
7812 } else {
7813
7814
7815 $sql = $wpdb->prepare(
7816 "SELECT `key`, `accountKey`, `status`, `options` FROM `" . $table_name . "` WHERE `scheduleKey` = %d AND `status` != 'canceled';",
7817 array(intval($scheduleKey))
7818 );
7819
7820 if (is_null($bookingID) === false) {
7821
7822 $sql = $wpdb->prepare(
7823 "SELECT `key`, `accountKey`, `status`, `options` FROM `" . $table_name . "` WHERE `key` != %d AND `scheduleKey` = %d AND `status` != 'canceled';",
7824 array(intval($bookingID), intval($scheduleKey))
7825 );
7826
7827 }
7828
7829 $rows = $wpdb->get_results($sql, ARRAY_A);
7830 foreach ((array) $rows as $row) {
7831
7832 array_push($bookingIDs, intval($row['key']));
7833 $services = json_decode($row['options'], true);
7834 for ($i = 0; $i < count($services); $i++) {
7835
7836 $serviceKey = intval($services[$i]['key']);
7837 if (isset($hasServices[$serviceKey])) {
7838
7839 $hasServices[$serviceKey]++;
7840
7841 } else {
7842
7843 $hasServices[$serviceKey] = 1;
7844
7845 }
7846
7847 }
7848
7849 }
7850
7851 }
7852
7853 if (empty($bookingID) === false) {
7854
7855 $bookingIDs = array_diff($bookingIDs, array($bookingID));
7856 $bookingIDs = array_values($bookingIDs);
7857
7858 }
7859
7860 if ($requestService['stopServiceUnderFollowingConditions'] == 'isNotEqual' || $requestService['stopServiceUnderFollowingConditions'] == 'isEqual') {
7861
7862 if ($requestService['stopServiceUnderFollowingConditions'] == 'isNotEqual') {
7863
7864 if (count($rows) != 0) {
7865
7866 $response['status'] = false;
7867 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . sprintf( __("When the '%s' and '%s' values for the time slot do not match.", 'booking-package'), __('Available Slots', 'booking-package'), __('Remaining Slots', 'booking-package') );
7868
7869 }
7870
7871 if ($requestService['doNotStopServiceAsException'] == 'sameServiceIsNotStopped') {
7872
7873 if (isset($hasServices[intval($requestService['key'])])) {
7874
7875 $response['status'] = true;
7876 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . __('Allow booking this service if its start time overlaps with the start time of an existing booking for the same service.', 'booking-package');
7877
7878 }
7879
7880 }
7881
7882 } else if ($requestService['stopServiceUnderFollowingConditions'] == 'isEqual') {
7883
7884 if (count($rows) == 0) {
7885
7886 $response['status'] = false;
7887 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . sprintf( __("When the '%s' and '%s' values for the time slot are equal.", 'booking-package'), __('Available Slots', 'booking-package'), __('Remaining Slots', 'booking-package') );
7888
7889 }
7890
7891 }
7892
7893 } else if ($requestService['stopServiceUnderFollowingConditions'] == 'specifiedNumberOfTimes') {
7894
7895 if ($requestService['stopServiceForDayOfTimes'] == 'startTimeSlot') {
7896
7897 if (isset($hasServices[intval($requestService['key'])]) && $hasServices[intval($requestService['key'])] >= intval($requestService['stopServiceForSpecifiedNumberOfTimes'])) {
7898
7899 $response['status'] = false;
7900 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . __('Target', 'booking-package') . ' > ' . __('Maximum bookings per start time slot', 'booking-package');
7901
7902 }
7903
7904 } else if ($requestService['stopServiceForDayOfTimes'] == 'timeSlot') {
7905
7906 foreach ($timeSlots as $time => $slot) {
7907
7908 if ( intval($slot) >= intval($requestService['stopServiceForSpecifiedNumberOfTimes']) ) {
7909
7910 $response['status'] = false;
7911 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . __('Target', 'booking-package') . ' > ' . __('Bookings per time slot', 'booking-package');
7912 break;
7913
7914 }
7915
7916 }
7917
7918 } else if ($requestService['stopServiceForDayOfTimes'] == 'day') {
7919
7920 $accountCalendarKey = null;
7921 $calendarAccount = $this->getCalendarAccount($accountKey);
7922 if (intval($calendarAccount['schedulesSharing']) == 1) {
7923
7924 $accountCalendarKey = intval($calendarAccount['targetSchedules']);
7925
7926 }
7927
7928 $schedule = $this->getAccountSchedule($scheduleKey);
7929 if ($schedule === false) {
7930
7931 $response['status'] = false;
7932 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . __('Target', 'booking-package') . ' > ' . __('Total bookings per day', 'booking-package');
7933 return $response;
7934
7935 }
7936
7937 $bookedServices = $this->getBookedServices(
7938 array(),
7939 date('U', mktime(0, 0, 0, $schedule['month'], $schedule['day'], $schedule['year'])),
7940 date('U', mktime(23, 59, 0, $schedule['month'], $schedule['day'], $schedule['year'])),
7941 $accountKey,
7942 $accountCalendarKey
7943 );
7944
7945 $count = 0;
7946 if (count($bookedServices) > 0) {
7947
7948 foreach (reset($bookedServices) as $time => $services) {
7949
7950 foreach ($services as $servceKey => $service) {
7951
7952 if (intval($requestService['key']) === $servceKey) {
7953
7954 $count++;
7955
7956 }
7957
7958 }
7959
7960 }
7961
7962 }
7963
7964 if ($count >= intval($requestService['stopServiceForSpecifiedNumberOfTimes'])) {
7965
7966 $response['status'] = false;
7967 $response['message'] = __('Stop Offering This Service Under the Following Conditions', 'booking-package') .': ' . __('Target', 'booking-package') . ' > ' . __('Total bookings per day', 'booking-package');
7968 return $response;
7969
7970 }
7971
7972 }
7973
7974 }
7975
7976
7977 return $response;
7978
7979 }
7980
7981 public function validExpirationDate($bookingYMD, $expirationDateStatus, $expirationDateFrom, $expirationDateTo) {
7982
7983 $isBooking = true;
7984 if (is_int($bookingYMD) && intval($expirationDateStatus) == 1 && $expirationDateFrom != 0 && $expirationDateTo != 0 && (($expirationDateFrom <= $bookingYMD && $expirationDateTo < $bookingYMD) || ($expirationDateFrom > $bookingYMD && $expirationDateTo >= $bookingYMD))) {
7985
7986 $isBooking = false;
7987
7988 }
7989
7990 return $isBooking;
7991
7992 }
7993
7994 public function getStatus($userDetail = false){
7995
7996 #$this->automaticApprove = boolval(intval(get_option($this->prefix."automaticApprove", 0)));
7997 $this->automaticApprove = intval(get_option($this->prefix."automaticApprove", 0));
7998 if ($this->automaticApprove == 0) {
7999
8000 $this->automaticApprove = false;
8001
8002 } else {
8003
8004 $this->automaticApprove = true;
8005
8006 }
8007 $status = "pending";
8008 if ($userDetail !== false) {
8009
8010 if (isset($userDetail['status'])) {
8011
8012 return $userDetail['status'];
8013
8014 } else {
8015
8016 if ($this->automaticApprove === true) {
8017
8018 $status = "approved";
8019
8020 }
8021
8022 }
8023
8024 } else {
8025
8026 if ($this->automaticApprove === true) {
8027
8028 $status = "approved";
8029
8030 }
8031
8032 }
8033
8034 return $status;
8035
8036 }
8037
8038 public function serachSchedule($unixTime, $accountKey = 1){
8039
8040 global $wpdb;
8041 $table_name = $wpdb->prefix . "booking_package_schedules";
8042 $sql = $wpdb->prepare(
8043 "SELECT `key`,`unixTime`,`title`,`capacity`,`remainder`,`stop` FROM `".$table_name."` WHERE `accountKey` = %d AND `unixTime` = %d AND `status` = 'open' LIMIT 0, 1;",
8044 array(intval($accountKey), intval($unixTime))
8045 );
8046 $row = $wpdb->get_row($sql, ARRAY_A);
8047 if (is_null($row)) {
8048
8049 return array('status' => 'error');
8050
8051 } else {
8052
8053 return $row;
8054
8055 }
8056
8057 }
8058
8059 public function updatePricesForGuest($guests, $numberKeys) {
8060
8061 for ($a = 0; $a < count($guests); $a++) {
8062
8063 for ($i = 0; $i < count($numberKeys); $i++) {
8064
8065 if (isset($guests[$a][$numberKeys[$i]]) === false) {
8066
8067 $guests[$a][$numberKeys[$i]] = $guests[$a]['price'];
8068
8069 }
8070
8071 }
8072
8073 }
8074
8075 return $guests;
8076
8077 }
8078
8079 public function getExtraChargeForHotelOption($options, $selectedOption, $nights, $adults, $children) {
8080
8081 $extraCharge = 0;
8082 if ($options['range'] == 'oneBooking' && $options['target'] == 'guests') {
8083
8084 $extraCharge = ($adults * intval($selectedOption['adult'])) + ($children * intval($selectedOption['child']));
8085
8086 } else if ($options['range'] == 'oneBooking' && $options['target'] == 'room') {
8087
8088 $extraCharge = intval($selectedOption['room']);
8089
8090 } else if ($options['range'] == 'allDays' && $options['target'] == 'guests') {
8091
8092 $extraCharge = $nights * ( ($adults * intval($selectedOption['adult'])) + ($children * intval($selectedOption['child'])) );
8093
8094 } else if ($options['range'] == 'allDays' && $options['target'] == 'room') {
8095
8096 $extraCharge = $nights * intval($selectedOption['room']);
8097
8098 }
8099
8100 return $extraCharge;
8101
8102 }
8103
8104 public function summer_time_offset($unix_timestamp, $timeZone) {
8105
8106 $datetime = new DateTime();
8107 $datetime->setTimestamp($unix_timestamp);
8108 $timezone = $datetime->getTimezone();
8109
8110 $is_dst = $timezone->getTransitions($unix_timestamp, $unix_timestamp);
8111 $summer_time = $is_dst[0]['isdst'];
8112 $summer_time_offset_seconds = 0;
8113
8114 if ($summer_time) {
8115
8116 $summer_time_offset_seconds = $timezone->getOffset($datetime) - $timezone->getOffset(new DateTime('now', new DateTimeZone($timeZone)));
8117
8118 }
8119
8120 return $summer_time_offset_seconds;
8121
8122
8123 }
8124
8125 public function createAccommodationDetails($originCalendarKey, $calendarAccountKey, $json, $sql_start_unixTime, $applicantCount, $type, $accommodationDetails = null){
8126
8127 global $wpdb;
8128 $setting = new booking_package_setting($this->prefix, $this->pluginName);
8129 $numberKeys = $setting->getListOfDaysOfWeek();
8130 $calendarAccount = $this->getCalendarAccount($calendarAccountKey);
8131 $timeZone = $calendarAccount['timezone'];
8132 $accountKey = $calendarAccount['key'];
8133 $person = 0;
8134 $nights = 0;
8135 $additionalFee = 0;
8136 $totalCost = 0;
8137 $totalTax = 0;
8138 #$accommodationDetails['taxesFee']
8139 if (is_null($accommodationDetails)) {
8140
8141 $accommodationDetails = array("scheduleList" => array(), "guestsList" => array(), "optionsList" => array(), 'type' => $calendarAccount['type'], 'taxes' => array(), 'taxesFee' => 0, 'applicantCount' => $applicantCount);
8142
8143 } else {
8144
8145 $unixTimeEnd = $accommodationDetails['checkOut'];
8146 $nights = $accommodationDetails['nights'];
8147 $additionalFee = $accommodationDetails['additionalFee'];
8148 $totalCost = $accommodationDetails['accommodationFee'];
8149
8150 }
8151
8152 if (is_array($json)) {
8153
8154 $jsonList = $json;
8155
8156 } else {
8157
8158 #$jsonList = json_decode(str_replace("\\", "", $json), true);
8159 $jsonList = json_decode(stripslashes($json), true);
8160
8161 }
8162
8163 if (isset($jsonList['applicantCount'])) {
8164
8165 $accommodationDetails['applicantCount'] = intval($jsonList['applicantCount']);
8166 $applicantCount = intval($jsonList['applicantCount']);
8167
8168 }
8169
8170 if (intval($accommodationDetails['applicantCount']) === 0) {
8171
8172 $accommodationDetails['applicantCount'] = 1;
8173 $applicantCount = 1;
8174
8175 }
8176
8177 #$sql_start_unixTime += $this->summer_time_offset($sql_start_unixTime, $calendarAccount['timezone']);
8178 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
8179 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
8180 $scheduleList = array();
8181 if (array_key_exists('list', $jsonList) === true && empty($jsonList['list']) === false) {
8182
8183 $scheduleList = array_values($jsonList['list']);
8184
8185 }
8186
8187 $first = null;
8188 $last = null;
8189 if (count($scheduleList) != 0) {
8190
8191 $nights = count($scheduleList);
8192 $scheduleCount = 0;
8193 $totalCost = 0;
8194 $accommodationDetails['scheduleList'] = array();
8195 $accommodationDetails['scheduleDetails'] = array();
8196 $first = reset($scheduleList);
8197 $first_unixTime = $first['unixTime'];
8198 $last = array('unixTime' => strtotime("+" . $nights . " days", intval($first['unixTime']) ) );
8199 $table_name = $wpdb->prefix . "booking_package_schedules";
8200
8201 for ($i = 0; $i <= ($nights - 1); $i++) {
8202
8203 $check_in_date = new DateTime("@$first_unixTime");
8204 $check_in_date->setTimezone(new DateTimeZone($timeZone));
8205 $time = $check_in_date->modify('+' . $i . ' day')->getTimestamp();
8206 #$time = $time->getTimestamp();
8207 #echo $i . ' = ' . date('Y-m-d H:i', $time) . '<br>';
8208 $sql = $wpdb->prepare(
8209 "SELECT `key`, `month`, `day`, `year`, `title`, `stop`, `weekKey`, `unixTime`, `cost`, `remainder` FROM `" . $table_name . "` WHERE `accountKey` = %d AND `month` = %d AND `day` = %d AND `year` = %d AND `status` = 'open' ORDER BY `unixTime` ASC;",
8210 array(intval($accountKey), intval(date('n', $time)), intval(date('j', $time)), intval(date('Y', $time)))
8211 );
8212 $row = $wpdb->get_row($sql, ARRAY_A);
8213 if (is_null($row)) {
8214
8215 $date = $this->dateFormat($dateFormat, $positionOfWeek, $time, '', false, false, 'text');
8216 return array("status" => "error", "message" => sprintf(__("There is no vacancy in the room on %s", 'booking-package'), $date), 'applicantCount' => 0, );
8217
8218 } else {
8219
8220 $scheduleCount++;
8221 array_push($accommodationDetails['scheduleList'], $row['key']);
8222 $accommodationDetails['scheduleDetails'][$row['unixTime']] = $row;
8223 $date = $this->dateFormat($dateFormat, $positionOfWeek, $row['unixTime'], $row['title'], false, false, 'text');
8224 if ($type == 'book' && $row['remainder'] <= 0) {
8225
8226 return array("status" => "error", "message" => sprintf(__("There is no vacancy in the room on %s", 'booking-package'), $date));
8227
8228 }
8229
8230 if ($this->confirmRegularHolidays($accountKey, $row['month'], $row['day'], $row['year']) === true) {
8231
8232 return array("status" => "error", "message" => __("The requested schedule has been closed.", 'booking-package'));
8233
8234 }
8235
8236 if ($row['stop'] == 'true' || $row['stop'] == 'auto_publish') {
8237
8238 return array("status" => "error", "message" => sprintf(__("Booking of %s is suspended.", 'booking-package'), $date));
8239
8240 }
8241
8242 $totalCost += intval($row['cost']) * $applicantCount;
8243
8244 }
8245
8246 }
8247
8248 if ($scheduleCount != 0) {
8249
8250 ksort($accommodationDetails['scheduleDetails']);
8251
8252 $table_name = $wpdb->prefix . "booking_package_schedules";
8253 $sql = $wpdb->prepare(
8254 "SELECT `key`,`month`,`day`,`year`,`weekKey`,`unixTime` FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
8255 array(intval($jsonList['checkInKey']))
8256 );
8257 $row = $wpdb->get_row($sql, ARRAY_A);
8258 $checkInUnixTime = $row['unixTime'];
8259 $accommodationDetails['checkInSchedule'] = $row;
8260
8261 $sql = $wpdb->prepare(
8262 "SELECT `key`,`month`,`day`,`year`,`weekKey`,`unixTime` FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
8263 array(intval($jsonList['checkOutKey']))
8264 );
8265 $row = $wpdb->get_row($sql, ARRAY_A);
8266 $checkOutUnixTime = $row['unixTime'];
8267 $accommodationDetails['checkOutSchedule'] = $row;
8268
8269 $table_name = $wpdb->prefix . "booking_package_regular_holidays";
8270 $sql = $wpdb->prepare(
8271 "SELECT `month`,`day`,`year`,`unixTime`,`status` FROM `" . $table_name . "` WHERE `accountKey` = 'national' AND `status` = 1 AND `unixTime` >= %d AND `unixTime` < %d ORDER BY `unixTime` ASC;",
8272 array(
8273 intval($checkInUnixTime),
8274 intval($checkOutUnixTime),
8275 )
8276 );
8277
8278 $rows = $wpdb->get_results($sql, ARRAY_A);
8279 $rows = $this->addPriceKeyByDayOfWeek($rows, $numberKeys, true);
8280 $accommodationDetails['scheduleDetails'] = $this->addPriceKeyByDayOfWeek($accommodationDetails['scheduleDetails'], $numberKeys, false);
8281
8282 foreach ((array) $rows as $row) {
8283
8284 $key = date('U', mktime(0, 0, 0, intval($row['month']), intval($row['day']), intval($row['year'])));
8285 $accommodationDetails['scheduleDetails'][$key]['priceKeyByDayOfWeek'] = $row['priceKeyByDayOfWeek'];
8286
8287 }
8288 #var_dump($accommodationDetails['scheduleDetails']);
8289 foreach ((array) $accommodationDetails['scheduleDetails'] as $schedule) {
8290
8291 if ($schedule['priceKeyByDayOfWeek'] == 'priceOnNationalHoliday') {
8292
8293 $dayBeforeUnixTime = intval($schedule['unixTime']) - (1440 * 60);
8294 #$dayBeforeKey = date('Y', $dayBeforeUnixTime) . date('m', $dayBeforeUnixTime) . date('d', $dayBeforeUnixTime);
8295 if (isset($accommodationDetails['scheduleDetails'][$dayBeforeUnixTime]) && $accommodationDetails['scheduleDetails'][$dayBeforeUnixTime]['priceKeyByDayOfWeek'] != 'priceOnNationalHoliday') {
8296
8297 $accommodationDetails['scheduleDetails'][$dayBeforeUnixTime]['priceKeyByDayOfWeek'] = 'priceOnDayBeforeNationalHoliday';
8298
8299 }
8300
8301 }
8302
8303 }
8304
8305 $sql_max_unixTime = strtotime("+" . $nights . " days", intval($sql_start_unixTime) );
8306
8307 $accommodationDetails['checkIn'] = intval($sql_start_unixTime);
8308 $accommodationDetails['checkOut'] = intval($sql_max_unixTime);
8309 #$accommodationDetails['checkOut'] = intval($sql_max_unixTime) + (1440 * 60);
8310 $accommodationDetails['lastUnixTime'] = intval($sql_max_unixTime);
8311 $accommodationDetails['nights'] = $nights;
8312 $accommodationDetails['accommodationFee'] = $totalCost;
8313 $accommodationDetails['sql_max_unixTime'] = $sql_max_unixTime;
8314 $maintenanceTime = 0;
8315 $sql_max_unixTime += $maintenanceTime * 60;
8316 #$sql_max_unixTime = $sql_start_unixTime + ($courseTime * 60) + ($maintenanceTime * 60);
8317 $table_name = $wpdb->prefix . "booking_package_schedules";
8318 $account_sql = "SELECT * FROM `" . $table_name . "` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
8319 $valueArray = array(intval($accountKey), intval($sql_start_unixTime), intval($sql_max_unixTime));
8320 $accommodationDetails['sql'] = $account_sql;
8321 $accommodationDetails['valueArray'] = $valueArray;
8322 $jsonList['sql'] = $wpdb->prepare($account_sql, $valueArray);
8323
8324 } else {
8325
8326 return array("status" => "error", "message" => __("The requested schedule has been closed.", 'booking-package'));
8327
8328 }
8329
8330 }
8331
8332 $personAmount = 0;
8333 $optionsAmount = 0;
8334 if (count($jsonList['rooms']) != 0) {
8335
8336 $additionalFee = 0;
8337 $adult = 0;
8338 $children = 0;
8339 $rooms = array();
8340 foreach ((array) $jsonList['rooms'] as $roomKey => $room) {
8341
8342 $adultInRoom = 0;
8343 $childrenInRoom = 0;
8344 /** guests **/
8345 $table_name = $wpdb->prefix . "booking_package_guests";
8346 $selectedGuests = $room['guests'];
8347 $guestsDetails = array();
8348 $personAmount += intval($room['personAmount']);
8349 foreach ((array) $selectedGuests as $key => $value) {
8350
8351 $guests_row = array();
8352 $guestsArray = array();
8353 $guests = array();
8354 $selected = false;
8355 if ($type == 'book') {
8356
8357 $guestSql = $wpdb->prepare(
8358 "SELECT * FROM `".$table_name."` WHERE `key` = %d AND `accountKey` = %d;",
8359 array(intval($key), intval($originCalendarKey))
8360 );
8361 $guests_row = $wpdb->get_row($guestSql, ARRAY_A);
8362 $guestsArray = json_decode($guests_row['json'], true);
8363
8364 } else if ($type == 'update') {
8365
8366 $guests_row = $accommodationDetails['rooms'][$roomKey]['guestsList'][$key];
8367 $guestsArray = $guests_row['json'];
8368 array_shift($guestsArray);
8369
8370 }
8371
8372 $guestsArray = $this->updatePricesForGuest($guestsArray, $numberKeys);
8373 for ($i = 0; $i < count($guestsArray); $i++) {
8374
8375 if (intval($value['number']) == intval($guestsArray[$i]['number']) && $value['name'] == $guestsArray[$i]['name']) {
8376
8377 $additionalFee += intval($guestsArray[$i]['price']) * $nights;
8378 $selected = true;
8379 $guestsArray[$i]['selected'] = 1;
8380 $person += intval($guestsArray[$i]['number']);
8381 if ($guests_row['target'] == 'adult') {
8382
8383 $adult += intval($guestsArray[$i]['number']);
8384 $adultInRoom += intval($guestsArray[$i]['number']);
8385
8386 } else {
8387
8388 $children += intval($guestsArray[$i]['number']);
8389 $childrenInRoom += intval($guestsArray[$i]['number']);
8390
8391 }
8392
8393 } else {
8394
8395 $guestsArray[$i]['selected'] = 0;
8396
8397 }
8398
8399 }
8400
8401 if ($selected === false) {
8402
8403 array_unshift($guestsArray, array("number" => 0, "price" => 0, "name" => "SELECT", "selected" => 1));
8404
8405 } else {
8406
8407 array_unshift($guestsArray, array("number" => 0, "price" => 0, "name" => "SELECT", "selected" => 0));
8408
8409 }
8410
8411 $guestsArray = $this->updatePricesForGuest($guestsArray, $numberKeys);
8412 $guests_row['json'] = $guestsArray;
8413 $room['guestsList'][$key] = $guests_row;
8414
8415 }
8416 /** guests **/
8417
8418 /** options **/
8419
8420 $table_name = $wpdb->prefix . "booking_package_hotel_options";
8421 $totalNumberOfOptions = 0;
8422 $optionsList = $room['options'];
8423 $optionsAmount += intval($room['optionsAmount']);
8424 foreach ((array) $optionsList as $key => $value) {
8425
8426 $selected = false;
8427 if ($type == 'book') {
8428
8429 $optionSql = $wpdb->prepare(
8430 "SELECT * FROM `".$table_name."` WHERE `key` = %d AND `accountKey` = %d;",
8431 array(intval($key), intval($originCalendarKey))
8432 );
8433 $options = $wpdb->get_row($optionSql, ARRAY_A);
8434 $options = $setting->getTranslateOption($options, intval($originCalendarKey) );
8435 $optionsArray = json_decode($options['json'], true);
8436
8437 } else if ($type == 'update') {
8438
8439 $options = $accommodationDetails['rooms'][$roomKey]['optionsList'][$key];
8440 $optionsArray = (function($savedValuesWithOption) {
8441
8442 array_shift($savedValuesWithOption);
8443 foreach ((array) $savedValuesWithOption as $key => $value) {
8444
8445 $savedValuesWithOption[$key]['selected'] = 0;
8446
8447 }
8448 return $savedValuesWithOption;
8449
8450 })($options['json']);
8451
8452 if (isset($value['selected'])) {
8453
8454 unset($value['selected']);
8455
8456 }
8457
8458 }
8459
8460 if (intval($value['index']) > 0) {
8461
8462 $selected = true;
8463 $totalNumberOfOptions++;
8464 $index = intval($value['index']) - 1;
8465 $optionsArray[$index]['selected'] = 1;
8466
8467 $additionalFee += $this->getExtraChargeForHotelOption($options, $value, $nights, $adultInRoom, $childrenInRoom);
8468
8469 }
8470
8471 if ($selected === false) {
8472
8473 array_unshift($optionsArray, array("adult" => 0, "child" => 0, "room" => 0, "name" => "SELECT", "selected" => 1));
8474
8475 } else {
8476
8477 array_unshift($optionsArray, array("adult" => 0, "child" => 0, "room" => 0, "name" => "SELECT", "selected" => 0));
8478
8479 }
8480
8481 for ($i = 0; $i < count($optionsArray); $i++) {
8482
8483 $optionsArray[$i]['index'] = $i;
8484 if (isset($optionsArray[$i]['selected']) === false) {
8485
8486 $optionsArray[$i]['selected'] = 0;
8487
8488 }
8489
8490 }
8491
8492 $options['json'] = $optionsArray;
8493 $room['optionsList'][$key] = $options;
8494 $room['totalNumberOfOptions'] = $totalNumberOfOptions;
8495 }
8496
8497 if (isset($room['optionsList']) === false) {
8498
8499 $room['optionsList'] = array();
8500
8501 }
8502
8503 if (isset($room['totalNumberOfOptions']) === false) {
8504
8505 $room['totalNumberOfOptions'] = 0;
8506
8507 }
8508 /** options **/
8509
8510 array_push($rooms, $room);
8511
8512 }
8513
8514 $accommodationDetails['rooms'] = $rooms;
8515 $accommodationDetails['additionalFee'] = $additionalFee;
8516 $accommodationDetails['adult'] = intval($adult);
8517 $accommodationDetails['children'] = intval($children);
8518
8519 } else {
8520
8521 $accommodationDetails['additionalFee'] = 0;
8522
8523 }
8524
8525 if (is_null($jsonList['guestsList'])) {
8526
8527 $jsonList['guestsList'] = array();
8528
8529 }
8530
8531 if (count($jsonList['rooms']) == 0 && count($jsonList['guestsList']) != 0) {
8532
8533 $additionalFee = 0;
8534 $table_name = $wpdb->prefix."booking_package_guests";
8535 $guestsList = $jsonList['guestsList'];
8536 foreach ((array) $guestsList as $key => $value) {
8537
8538 $guestSql = $wpdb->prepare(
8539 "SELECT * FROM `".$table_name."` WHERE `key` = %d AND `accountKey` = %d;",
8540 array(intval($key), intval($originCalendarKey))
8541 );
8542 $guests_row = $wpdb->get_row($guestSql, ARRAY_A);
8543 $guests = array();
8544 $guestsArray = json_decode($guests_row['json'], true);
8545 for ($i = 0; $i < count($guestsArray); $i++) {
8546
8547 if (intval($value['number']) == intval($guestsArray[$i]['number']) && $value['name'] == $guestsArray[$i]['name']) {
8548
8549 $additionalFee += intval($guestsArray[$i]['price']) * $nights;
8550 $guestsArray[$i]['selected'] = 1;
8551
8552 } else {
8553
8554 $guestsArray[$i]['selected'] = 0;
8555
8556 }
8557
8558 }
8559
8560 array_unshift($guestsArray, array("number" => 0, "price" => 0, "name" => "SELECT", "selected" => 0));
8561 $guests_row['json'] = $guestsArray;
8562 $accommodationDetails['guestsList'][$key] = $guests_row;
8563
8564 }
8565
8566 } else {
8567
8568 //$accommodationDetails['additionalFee'] = 0;
8569
8570 }
8571
8572 if (count($jsonList['taxes']) != 0) {
8573
8574 #$totalTax = 0;
8575 $taxValue = 0;
8576 $extraChargeAmount = 0;
8577 $taxList = array();
8578 $table_name = $wpdb->prefix."booking_package_taxes";
8579 $sql = $wpdb->prepare("SELECT * FROM ".$table_name." WHERE `accountKey` = %d AND `active` = 'true' AND `type` = 'surcharge' AND `generation` = 2 ORDER BY ranking ASC;", array(intval($originCalendarKey)));
8580 $rows = $wpdb->get_results($sql, ARRAY_A);
8581 foreach ((array) $rows as $key => $extraCharge) {
8582
8583 $extraCharge = $setting->getTranslateTax($extraCharge, $originCalendarKey);
8584 $applicantCountForTax = $applicantCount;
8585 $nightsForTax = $nights;
8586 $value = intval($extraCharge['value']);
8587 if ($extraCharge['scope'] === 'day' && $extraCharge['target'] === 'room') {
8588
8589 $taxValue = ($applicantCountForTax * $nights) * $value;
8590
8591 } else if ($extraCharge['scope'] === 'day' && $extraCharge['target'] === 'guest') {
8592
8593 $taxValue = ($person * $nights) * $value;
8594
8595
8596 } else if ($extraCharge['scope'] === 'booking' && $extraCharge['target'] === 'room') {
8597
8598 $taxValue = $applicantCountForTax * $value;
8599
8600
8601 } else if ($extraCharge['scope'] === 'booking' && $extraCharge['target'] === 'guest') {
8602
8603 $taxValue = $person * $value;
8604
8605 }
8606 $taxValue = intval($taxValue);
8607 if ($extraCharge['method'] == "addition" && $extraCharge['type'] == "surcharge") {
8608
8609 $totalTax += $taxValue;
8610
8611 }
8612
8613 $extraChargeAmount += $taxValue;
8614 $extraCharge['taxValue'] = $taxValue;
8615 array_push($taxList, $extraCharge);
8616
8617 }
8618
8619 $sql = $wpdb->prepare("SELECT * FROM ".$table_name." WHERE `accountKey` = %d AND `active` = 'true' ORDER BY ranking ASC;", array(intval($originCalendarKey)));
8620 $rows = $wpdb->get_results($sql, ARRAY_A);
8621 foreach ((array) $rows as $key => $tax) {
8622
8623 $tax = $setting->getTranslateTax($tax, $originCalendarKey);
8624 $applicantCountForTax = $applicantCount;
8625 $nightsForTax = $nights;
8626 $value = intval($tax['value']);
8627 if ($tax['method'] == 'multiplication') {
8628
8629 $value = floatval($tax['value']);
8630
8631 }
8632
8633 if (intval($tax['expirationDateStatus']) == 1) {
8634
8635 if ($tax['expirationDateTrigger'] != 'dateBooked') {
8636
8637
8638
8639 } else {
8640
8641 $count = 0;
8642 foreach ($accommodationDetails['scheduleDetails'] as $scheduleKey => $schedule) {
8643
8644 $expirationDate = $schedule['year'] . sprintf('%02d%02d', $schedule['month'], $schedule['day']);
8645 $isTax = $this->validExpirationDate(intval($expirationDate), intval($tax['expirationDateStatus']), intval($tax['expirationDateFrom']), intval($tax['expirationDateTo']));
8646 if ($isTax === false) {
8647
8648 $count++;
8649
8650 }
8651
8652 }
8653
8654 if ($nightsForTax == $count) {
8655
8656 $applicantCountForTax = 0;
8657
8658 }
8659
8660 $nightsForTax -= $count;
8661
8662 }
8663
8664 }
8665
8666 if (intval($tax['generation']) === 1) {
8667
8668 if ($tax['target'] == 'room') {
8669
8670 if ($tax['scope'] == 'day') {
8671
8672 if ($tax['method'] == 'addition') {
8673
8674 $taxValue = ($nightsForTax * $applicantCountForTax) * $value;
8675
8676 } else if ($tax['method'] == 'multiplication') {
8677
8678 $taxValue = ($value / 100) * (($accommodationDetails['accommodationFee']) + $accommodationDetails['additionalFee']);
8679 if ($personAmount > 0 || $optionsAmount > 0) {
8680
8681 $taxValue = ($value / 100) * (($accommodationDetails['accommodationFee']) + $personAmount + $optionsAmount);
8682
8683 }
8684 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_inclusive') {
8685
8686 $taxValue = (($accommodationDetails['accommodationFee']) + $accommodationDetails['additionalFee']) * ($value / (100 + $value));
8687 if ($personAmount > 0 || $optionsAmount > 0) {
8688
8689 $taxValue = ($accommodationDetails['accommodationFee'] + $personAmount + $optionsAmount) * ($value / (100 + $value));
8690
8691 }
8692 $taxValue = floor($taxValue);
8693
8694 }
8695
8696 }
8697
8698 } else if ($tax['scope'] == 'booking') {
8699
8700 if ($tax['method'] == 'addition') {
8701
8702 $taxValue = $applicantCountForTax * $value;
8703
8704 } else if ($tax['method'] == 'multiplication') {
8705
8706 $taxValue = ($value / 100) * $applicantCountForTax;
8707
8708 }
8709
8710 } else if ($tax['scope'] == 'bookingEachGuests') {
8711
8712 if ($tax['method'] == 'addition') {
8713
8714 $taxValue = ($person * $nightsForTax) * $value;
8715
8716 } else if ($tax['method'] == 'multiplication') {
8717
8718 $taxValue = ($value / 100) * ($person * $nightsForTax);
8719
8720 }
8721
8722 }
8723
8724 } else if ($tax['target'] == 'guest') {
8725
8726 if ($tax['scope'] == 'day') {
8727
8728 if ($tax['method'] == 'addition') {
8729
8730 $taxValue = ($nightsForTax * $person) * $value;
8731
8732 } else if ($tax['method'] == 'multiplication') {
8733
8734 #$taxValue = ($value / 100) * ($accommodationDetails['additionalFee'] / $nightsForTax);
8735 $taxValue = ($value / 100) * $accommodationDetails['additionalFee'];
8736 if ($personAmount > 0) {
8737
8738 $taxValue = ($value / 100) * $personAmount;
8739
8740 }
8741 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_inclusive') {
8742
8743 $taxValue = $accommodationDetails['additionalFee'] * ($value / (100 + $value));
8744 if ($personAmount > 0) {
8745
8746 $taxValue = $personAmount * ($value / (100 + $value));
8747
8748 }
8749 $taxValue = floor($taxValue);
8750
8751 }
8752
8753 }
8754
8755 } else if ($tax['scope'] == 'booking') {
8756
8757 if ($tax['method'] == 'addition') {
8758
8759 $taxValue = 1 * $value;
8760
8761 } else if ($tax['method'] == 'multiplication') {
8762
8763 $taxValue = ($value / 100) * 1;
8764
8765 }
8766
8767 } else if ($tax['scope'] == 'bookingEachGuests') {
8768
8769 if ($tax['method'] == 'addition') {
8770
8771 $taxValue = ($person * $nightsForTax) * $value;
8772
8773 } else if ($tax['method'] == 'multiplication') {
8774
8775 $taxValue = ($value / 100) * ($person * $nightsForTax);
8776
8777 }
8778
8779 }
8780
8781 }
8782
8783 } else if (intval($tax['generation']) === 2) {
8784
8785 if ($tax['type'] === 'tax') {
8786
8787 if ($tax['method'] === 'multiplication' && $tax['tax'] === 'tax_inclusive') {
8788
8789 $taxValue = ($accommodationDetails['accommodationFee'] + $personAmount + $optionsAmount + $extraChargeAmount) * ($value / (100 + $value));
8790
8791 } else if ($tax['method'] === 'multiplication' && $tax['tax'] === 'tax_exclusive') {
8792
8793 $taxValue = ($value / 100) * ($accommodationDetails['accommodationFee'] + $personAmount + $optionsAmount + $extraChargeAmount);
8794
8795 } else if ($tax['method'] === 'addition' && $tax['target'] === 'room') {
8796
8797 $taxValue = ($nightsForTax * $applicantCountForTax) * $value;
8798
8799 } else if ($tax['method'] === 'addition' && $tax['target'] === 'guest') {
8800
8801 $taxValue = ($nightsForTax * $person) * $value;
8802
8803 }
8804
8805 } else if ($tax['type'] === 'surcharge') {
8806
8807 continue;
8808
8809 }
8810
8811 }
8812
8813
8814 $taxValue = intval($taxValue);
8815 if ($tax['tax'] == 'tax_exclusive' || ($tax['method'] == "addition" && $tax['type'] == "surcharge")) {
8816
8817 $totalTax += $taxValue;
8818
8819 }
8820
8821 $tax['taxValue'] = $taxValue;
8822 array_push($taxList, $tax);
8823
8824 }
8825
8826 $accommodationDetails['taxes'] = $taxList;
8827 $accommodationDetails['extraChargeAmount'] = $extraChargeAmount;
8828 $accommodationDetails['taxesFee'] = $totalTax;
8829
8830 } else {
8831
8832 $accommodationDetails['taxes'] = array();
8833 $accommodationDetails['taxesFee'] = 0;
8834
8835 }
8836
8837 $accommodationDetails['personAmount'] = $personAmount;
8838 $accommodationDetails['optionsAmount'] = $optionsAmount;
8839 $accommodationDetails['totalCost'] = $totalCost + $additionalFee + $totalTax;
8840 if ($personAmount > 0) {
8841
8842 $accommodationDetails['totalCost'] = $totalCost + $personAmount + $optionsAmount + $totalTax;
8843
8844 }
8845
8846 return $accommodationDetails;
8847
8848 }
8849
8850 public function createTaxesDetails($accountKey, $calendarType, $totalCost, $bookingYMD = 0, $applicantCount = null, $taxes = null) {
8851
8852 global $wpdb;
8853 $setting = new booking_package_setting($this->prefix, $this->pluginName);
8854 $extraChargeAmount = 0;
8855 $taxesDetails = array();
8856 $isExtensionsValid = $this->getExtensionsValid();
8857 if (is_null($taxes) === true) {
8858
8859 $table_name = $wpdb->prefix . "booking_package_taxes";
8860 $sql = $wpdb->prepare("SELECT * FROM " . $table_name . " WHERE `accountKey` = %d AND `active` = %s ORDER BY (type = 'surcharge') DESC, (type = 'tax') DESC, ranking ASC;", array(intval($accountKey), 'true'));
8861 $taxes = $wpdb->get_results($sql, ARRAY_A);
8862 foreach ((array) $taxes as $key => $tax) {
8863
8864 $taxes[$key] = $setting->getTranslateTax($tax, $accountKey);
8865
8866 }
8867
8868 }
8869
8870 /**
8871 foreach ((array) $taxes as $key => $tax) {
8872
8873 if ($isExtensionsValid !== true) {
8874
8875 continue;
8876
8877 }
8878
8879 if ($bookingYMD != 0 && intval($tax['expirationDateStatus']) == 1) {
8880
8881 $isTax = $this->validExpirationDate($bookingYMD, intval($tax['expirationDateStatus']), intval($tax['expirationDateFrom']), intval($tax['expirationDateTo']));
8882 if ($isTax === false) {
8883
8884 unset($rows[$key]);
8885 continue;
8886
8887 }
8888
8889 }
8890
8891
8892 if ($tax['method'] == 'multiplication') {
8893
8894 $taxValue = ($tax['value'] / 100) * $totalCost;
8895 if ($tax['tax'] == 'tax_inclusive') {
8896
8897 $taxValue = $totalCost * (intval($tax['value']) / (100 + intval($tax['value'])));
8898 $taxValue = floor($taxValue);
8899
8900 }
8901 $tax['taxValue'] = $taxValue;
8902
8903 } else {
8904
8905 $tax['taxValue'] = intval($tax['value']);
8906
8907 }
8908
8909 if ($calendarType === 'day' && intval($tax['generation']) === 2) {
8910
8911 if ($tax['type'] === 'tax') {
8912
8913 $taxValue = ($tax['value'] / 100) * ($totalCost + $extraChargeAmount);
8914
8915 if ($tax['tax'] == 'tax_inclusive') {
8916
8917 $taxValue = ($totalCost + $extraChargeAmount) * ( intval($tax['value']) / ( 100 + intval($tax['value']) ) );
8918 $taxValue = floor($taxValue);
8919
8920 }
8921 $tax['taxValue'] = $taxValue;
8922
8923 } else if ($tax['type'] === 'surcharge') {
8924
8925 $tax['taxValue'] = intval($tax['value']);
8926 $extraChargeAmount += intval($tax['value']) * $applicantCount;
8927
8928 }
8929
8930 }
8931
8932
8933 array_push($taxesDetails, $tax);
8934
8935 }
8936 **/
8937
8938 $taxesDetails = $this->getValueForTaxex($taxes, $totalCost, $applicantCount, $calendarType, $bookingYMD);
8939
8940 return $taxesDetails;
8941
8942 }
8943
8944 public function getTaxesDetailsForVisitor($bookingID, $applicantCount, $taxes, $totalCost) {
8945
8946 global $wpdb;
8947 if ($bookingID !== null) {
8948
8949 $taxes = array();
8950 $table_name = $wpdb->prefix . "booking_package_booked_customers";
8951 $sql = $wpdb->prepare("SELECT `taxes` FROM " . $table_name . " WHERE `key` = %d;", array(intval($bookingID)));
8952 $row = $wpdb->get_row($sql, ARRAY_A);
8953 $taxes = json_decode($row['taxes'], true);
8954
8955 }
8956
8957
8958 usort($taxes, function ($a, $b) {
8959
8960 $typeOrder = array('surcharge', 'tax');
8961 return array_search($a['type'], $typeOrder) - array_search($b['type'], $typeOrder);
8962
8963 });
8964
8965 /**
8966 $extraChargeAmount = 0;
8967 foreach ((array) $taxes as $key => $tax) {
8968
8969 if (intval($tax['generation']) === 1) {
8970
8971 if ($tax['method'] == 'multiplication') {
8972
8973 $taxValue = ($tax['value'] / 100) * $totalCost;
8974 if ($tax['tax'] == 'tax_inclusive') {
8975
8976 $taxValue = $totalCost * (intval($tax['value']) / (100 + intval($tax['value'])));
8977 $taxValue = floor($taxValue);
8978
8979 }
8980 $taxes[$key]['taxValue'] = $taxValue;
8981
8982 } else {
8983
8984 $taxes[$key]['taxValue'] = intval($tax['value']);
8985
8986 }
8987
8988 } else if (intval($tax['generation']) === 2) {
8989
8990 if ($tax['type'] === 'tax') {
8991
8992 $taxValue = ($tax['value'] / 100) * ($totalCost + $extraChargeAmount);
8993 if ($tax['tax'] == 'tax_inclusive') {
8994
8995 $taxValue = ($totalCost + $extraChargeAmount) * ( intval($tax['value']) / ( 100 + intval($tax['value']) ) );
8996 $taxValue = floor($taxValue);
8997
8998 }
8999 $taxes[$key]['taxValue'] = $taxValue;
9000
9001 } else if ($tax['type'] === 'surcharge') {
9002
9003 $taxes[$key]['taxValue'] = intval($tax['value']);
9004 $extraChargeAmount += intval($tax['value']) * $applicantCount;
9005
9006 }
9007
9008 }
9009
9010
9011 }
9012 **/
9013
9014 $taxes = $this->getValueForTaxex($taxes, $totalCost, $applicantCount, 'day', 0);
9015
9016 return $taxes;
9017
9018 }
9019
9020 public function getValueForTaxex($taxes, $totalCost, $applicantCount, $calendarType, $bookingYMD = 0) {
9021
9022 $taxesDetails = array();
9023 $extraChargeAmount = 0;
9024 foreach ((array) $taxes as $key => $tax) {
9025
9026 if ($bookingYMD != 0 && intval($tax['expirationDateStatus']) == 1) {
9027
9028 $isTax = $this->validExpirationDate($bookingYMD, intval($tax['expirationDateStatus']), intval($tax['expirationDateFrom']), intval($tax['expirationDateTo']));
9029 if ($isTax === false) {
9030
9031 #unset($rows[$key]);
9032 continue;
9033
9034 }
9035
9036 }
9037
9038 if ( ($calendarType === 'day' && intval($tax['generation']) === 1) || $calendarType === 'hotel') {
9039
9040 if ($tax['method'] == 'multiplication') {
9041
9042 $taxValue = ( $tax['value'] / 100 ) * $totalCost;
9043 if ($tax['tax'] == 'tax_inclusive') {
9044
9045 $taxValue = $totalCost * ( intval($tax['value']) / ( 100 + intval($tax['value']) ) );
9046 $taxValue = floor($taxValue);
9047
9048 }
9049 $tax['taxValue'] = $taxValue;
9050
9051 } else {
9052
9053 $tax['taxValue'] = intval($tax['value']);
9054
9055 }
9056
9057 } else if ($calendarType === 'day' && intval($tax['generation']) === 2) {
9058
9059 if ($tax['type'] === 'tax') {
9060
9061 $taxValue = ($tax['value'] / 100) * ($totalCost + $extraChargeAmount);
9062 if ($tax['tax'] == 'tax_inclusive') {
9063
9064 $taxValue = ($totalCost + $extraChargeAmount) * ( intval($tax['value']) / ( 100 + intval($tax['value']) ) );
9065 $taxValue = floor($taxValue);
9066
9067 }
9068 $tax['taxValue'] = $taxValue;
9069
9070 } else if ($tax['type'] === 'surcharge') {
9071
9072 $tax['taxValue'] = intval($tax['value']);
9073 $extraChargeAmount += intval($tax['value']) * $applicantCount;
9074
9075 }
9076
9077 }
9078
9079 array_push($taxesDetails, $tax);
9080
9081 }
9082
9083
9084
9085 return $taxesDetails;
9086
9087 }
9088
9089 public function intentForStripe() {
9090
9091 global $wpdb;
9092 $verifyAmount = $this->getVerifyAmountForStripePayments($_POST['amount']);
9093 if ($verifyAmount !== false && $verifyAmount !== 0) {
9094
9095 $currency = get_option($this->prefix . "currency", 'usd');
9096 $secret_key = get_option($this->prefix . "stripe_secret_key", null);
9097 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
9098 $response = $creditCard->intentForStripe($secret_key, $verifyAmount, $currency);
9099 return $response;
9100
9101 }
9102
9103 return array('status' => false);
9104
9105 }
9106
9107 public function intentForStripeExpressCheckout() {
9108
9109 global $wpdb;
9110 $verifyAmount = $this->getVerifyAmountForStripePayments($_POST['amount']);
9111 if ($verifyAmount !== false && $verifyAmount !== 0) {
9112
9113 $currency = get_option($this->prefix . "currency", 'usd');
9114 $secret_key = get_option($this->prefix . "stripe_secret_key", null);
9115 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
9116 $response = $creditCard->intentForStripeExpressCheckout($secret_key, $verifyAmount, $currency);
9117 return $response;
9118
9119 }
9120
9121 return array('status' => false);
9122
9123 }
9124
9125 public function intentForStripePayPay() {
9126
9127 global $wpdb;
9128 $verifyAmount = $this->getVerifyAmountForStripePayments($_POST['amount']);
9129 if ($verifyAmount !== false && $verifyAmount !== 0) {
9130
9131 $currency = get_option($this->prefix . "currency", 'jpy');
9132 $secret_key = get_option($this->prefix . "stripe_secret_key", null);
9133 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
9134 $response = $creditCard->intentForStripePayPay($secret_key, $verifyAmount, $currency);
9135 return $response;
9136
9137 }
9138
9139 return array('status' => false);
9140
9141 }
9142
9143 public function intentForStripeKonbini() {
9144
9145 global $wpdb;
9146 $verifyAmount = $this->getVerifyAmountForStripePayments($_POST['amount']);
9147 if ($verifyAmount !== false && $verifyAmount !== 0) {
9148
9149 $currency = get_option($this->prefix . "currency", 'jpy');
9150 $secret_key = get_option($this->prefix . "stripe_secret_key", null);
9151 $expiresDate = date('U') + (intval(get_option($this->prefix . "stripe_konbini_expiration_date", 1440)) * 60);
9152 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
9153 $response = $creditCard->intentForStripeKonbini($secret_key, $verifyAmount, $currency, $expiresDate);
9154 return $response;
9155
9156 }
9157
9158 return array('status' => false);
9159
9160 }
9161
9162 public function getVerifyAmountForStripePayments($amount) {
9163
9164 global $wpdb;
9165 $verifyAmount = 0;
9166 $coupon = null;
9167 $services = array();
9168 $responseGuests = array();
9169 $guests = array();
9170 $applicantCount = intval($_POST['applicantCount']);
9171 $reflectServiceCount = 1;
9172 $reflectAdditionalCount = 1;
9173 $accountKey = 1;
9174 $accountCalendarKey = 1;
9175 if (isset($_POST['accountKey'])) {
9176
9177 $accountKey = intval($_POST['accountKey']);
9178 $accountCalendarKey = intval($_POST['accountKey']);
9179
9180 }
9181
9182 $calendarAccount = $this->getCalendarAccount($accountKey);
9183
9184 $table_name = $wpdb->prefix . "booking_package_schedules";
9185 $sql = $wpdb->prepare(
9186 "SELECT *, `unixTime` - (`deadlineTime` * 60) as `unixTimeDeadline` FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
9187 array(intval($_POST['timeKey']))
9188 );
9189 $row = $wpdb->get_row($sql, ARRAY_A);
9190 if (is_null($row)) {
9191
9192 return false;
9193
9194 } else {
9195
9196 $sql_start_unixTime = $row['unixTime'];
9197 $bookingYMD = intval($row['year'] . sprintf('%02d%02d', $row['month'], $row['day']));
9198 if ($calendarAccount['type'] == "hotel" && isset($_POST['json'])) {
9199
9200 $accommodationDetails = $this->createAccommodationDetails($accountKey, $accountCalendarKey, $_POST['json'], $sql_start_unixTime, $applicantCount, 'book', null);
9201 if (isset($accommodationDetails['status']) && $accommodationDetails['status'] == "error") {
9202
9203 return false;
9204
9205 }
9206 $verifyAmount = $this->getAmount(null, $calendarAccount, $accommodationDetails, null, null, null, null);
9207
9208 } else {
9209
9210 if (isset($_POST['couponID'])) {
9211
9212 $couponResponse = $this->serachCoupons($row['unixTime'], $_POST['couponID'], $accountKey);
9213 if (intval($couponResponse['status']) == 1) {
9214
9215 $coupon = $couponResponse['coupon'];
9216
9217 }
9218
9219 }
9220
9221 if (isset($_POST['guests']) && intval($calendarAccount['guestsBool']) == 1) {
9222
9223 $responseGuests = $this->getSelectedGuests($calendarAccount, $_POST['guests'] );
9224 $guests = $responseGuests['guests'];
9225
9226 }
9227
9228 if (isset($_POST['courseKey']) || isset($_POST['selectedCourseList'])) {
9229
9230 #$servicesDetails = $this->getSelectedServices($calendarAccount, $_POST['selectedCourseList'], $responseGuests['guests'], "selectedOptionsList", $coupon, $applicantCount, true);
9231 $servicesDetails = $this->getSelectedServices($calendarAccount, $_POST['selectedCourseList'], $guests, "selectedOptionsList", $coupon, $reflectServiceCount, true);
9232 if ($servicesDetails['status'] === false) {
9233
9234 return false;
9235
9236 }
9237 $services = $servicesDetails['object'];
9238
9239 }
9240
9241 $taxes = $this->createTaxesDetails($accountKey, 'day', $verifyAmount, $bookingYMD, $applicantCount, null);
9242 $verifyAmount = $this->getAmount(null, $calendarAccount, array(), $services, $responseGuests, $taxes, $coupon);
9243
9244 }
9245
9246 }
9247
9248
9249 #var_dump(intval($verifyAmount));
9250 if (intval($verifyAmount) === intval($amount) && intval($verifyAmount) !== 0 && intval($amount) !== 0) {
9251
9252 return intval($verifyAmount);
9253
9254 }
9255
9256 return false;
9257
9258 }
9259
9260 public function blocksEmail($user_id, $emails) {
9261
9262 global $wpdb;
9263 $response = array('status' => 'success', 'message' => null);
9264 $table_name = $wpdb->prefix . "booking_package_block_list";
9265 $isExtensionsValid = $this->getExtensionsValid();
9266 if (intval(get_option($this->prefix . 'blocksEmail', 0)) == 0) {
9267
9268 return $response;
9269
9270 }
9271
9272 if (!is_null($user_id)) {
9273
9274
9275
9276 }
9277
9278 if (is_array($emails)) {
9279
9280 for ($i = 0; $i < count($emails); $i++) {
9281
9282 $email = $emails[$i];
9283 $sql = $wpdb->prepare(
9284 "SELECT `key` FROM `" . $table_name . "` WHERE `value` = %s;",
9285 array(sanitize_email($email))
9286 );
9287 $row = $wpdb->get_row($sql, ARRAY_A);
9288 if (!is_null($row)) {
9289
9290 $response['status'] = 'error';
9291 $response['message'] = __('Sorry, we have blocked your booking.', 'booking-package');
9292 break;
9293
9294 }
9295
9296 }
9297
9298 }
9299
9300 return $response;
9301
9302 }
9303
9304 public function blockSameTimeBookingByUser($user_id, $calendarAccount, $startUnix, $endUnix, $emails) {
9305
9306 global $wpdb;
9307 $accountKey = $calendarAccount['key'];
9308 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
9309 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
9310 $response = array('status' => 'success', 'message' => null);
9311 $table_name = $wpdb->prefix . "booking_package_booked_customers";
9312
9313 if (!is_null($user_id)) {
9314
9315 if (!is_null($endUnix)) {
9316
9317 $sql = $wpdb->prepare(
9318 "SELECT * FROM `".$table_name."` WHERE (`status` = 'pending' OR `status` = 'approved') AND `user_id` = %d AND `accountKey` = %d AND `scheduleUnixTime` < %d ORDER BY `scheduleUnixTime` DESC;",
9319 array(
9320 intval($user_id),
9321 intval($accountKey),
9322 intval($startUnix),
9323 )
9324 );
9325 $row = $wpdb->get_row($sql, ARRAY_A);
9326 if (!is_null($row)) {
9327
9328 $coupon = null;
9329 if (isset($row['coupon']) && !empty($row['coupon'])) {
9330
9331 $coupon = json_decode($row['coupon'], true);
9332
9333 }
9334 #$responseGuests = json_decode($row['guests'], true);
9335 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
9336 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $row['applicantCount'], false);
9337 $bookedUnixTime = $row['scheduleUnixTime'] + ($servicesDetails['time'] * 60);
9338 if ($startUnix < $bookedUnixTime) {
9339
9340 $startUnix = $row['scheduleUnixTime'];
9341
9342 }
9343
9344 }
9345
9346 $sql = $wpdb->prepare(
9347 "SELECT * FROM `".$table_name."` WHERE (`status` = 'pending' OR `status` = 'approved') AND `user_id` = %d AND `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` < %d;",
9348 array(
9349 intval($user_id),
9350 intval($accountKey),
9351 intval($startUnix),
9352 intval($endUnix),
9353 )
9354 );
9355 $response['message'] = sprintf(__('You already have a booking between %s and %s.', 'booking-package'), $this->dateFormat($dateFormat, $positionOfWeek, $startUnix, '', true, true, 'text'), $this->dateFormat($dateFormat, $positionOfWeek, $endUnix, '', true, true, 'text'));
9356
9357 } else {
9358
9359 $sql = $wpdb->prepare(
9360 "SELECT * FROM `".$table_name."` WHERE `user_id` = %d AND `accountKey` = %d AND `scheduleUnixTime` = %d;",
9361 array(
9362 intval($user_id),
9363 intval($accountKey),
9364 intval($startUnix),
9365 )
9366 );
9367 $response['message'] = sprintf(__('You have already booked at %s.', 'booking-package'), $this->dateFormat($dateFormat, $positionOfWeek, $startUnix, '', true, true, 'text'));
9368
9369 }
9370
9371 $row = $wpdb->get_row($sql, ARRAY_A);
9372 if (!is_null($row)) {
9373
9374 $response['status'] = 'error';
9375 return $response;
9376
9377 }
9378
9379 }
9380
9381 if (is_array($emails)) {
9382
9383 for ($i = 0; $i < count($emails); $i++) {
9384
9385 $email = $emails[$i];
9386 if (!is_null($endUnix)) {
9387
9388 $sql = $wpdb->prepare(
9389 "SELECT * FROM `".$table_name."` WHERE (`status` = 'pending' OR `status` = 'approved') AND `emails` LIKE %s AND `accountKey` = %d AND `scheduleUnixTime` < %d ORDER BY `scheduleUnixTime` DESC;",
9390 array(
9391 '%"' . $email . '"%',
9392 intval($accountKey),
9393 intval($startUnix),
9394 )
9395 );
9396
9397 $row = $wpdb->get_row($sql, ARRAY_A);
9398 if (!is_null($row)) {
9399
9400 $coupon = null;
9401 if (isset($row['coupon']) && !empty($row['coupon'])) {
9402
9403 $coupon = json_decode($row['coupon'], true);
9404
9405 }
9406 #$responseGuests = json_decode($row['guests'], true);
9407 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
9408 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $row['applicantCount'], false);
9409 $bookedUnixTime = $row['scheduleUnixTime'] + ($servicesDetails['time'] * 60);
9410 if ($startUnix < $bookedUnixTime) {
9411
9412 $startUnix = $row['scheduleUnixTime'];
9413
9414 }
9415
9416 }
9417
9418 $sql = $wpdb->prepare(
9419 "SELECT * FROM `".$table_name."` WHERE (`status` = 'pending' OR `status` = 'approved') AND `emails` LIKE %s AND `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` < %d;",
9420 array(
9421 '%"' . $email . '"%',
9422 intval($accountKey),
9423 intval($startUnix),
9424 intval($endUnix),
9425 )
9426 );
9427 $response['message'] = sprintf(__('You already have a booking between %s and %s.', 'booking-package'), $this->dateFormat($dateFormat, $positionOfWeek, $startUnix, '', true, true, 'text'), $this->dateFormat($dateFormat, $positionOfWeek, $endUnix, '', true, true, 'text'));
9428
9429 } else {
9430
9431 $sql = $wpdb->prepare(
9432 "SELECT * FROM `".$table_name."` WHERE (`status` = 'pending' OR `status` = 'approved') AND `emails` LIKE %s AND `accountKey` = %d AND `scheduleUnixTime` = %d;",
9433 array(
9434 '%"' . $email . '"%',
9435 intval($accountKey),
9436 intval($startUnix),
9437 )
9438 );
9439 $response['message'] = sprintf(__('You have already booked at %s by %s.', 'booking-package'), $this->dateFormat($dateFormat, $positionOfWeek, $startUnix, '', true, true, 'text'), $email);
9440
9441 }
9442
9443
9444 $row = $wpdb->get_row($sql, ARRAY_A);
9445 if (!is_null($row)) {
9446
9447 $response['status'] = 'error';
9448
9449 }
9450
9451 }
9452
9453 }
9454
9455 return $response;
9456
9457 }
9458
9459 public function verifyHCaptcha($token) {
9460
9461 $response = array('status' => true, 'message' => null, 'v' => null);
9462 $hCaptcha_active = get_option($this->prefix . "hCaptcha_active", "0");
9463 if (intval($hCaptcha_active) == 0) {
9464
9465 return $response;
9466
9467 }
9468
9469 if (empty($token)) {
9470
9471 $response['status'] = false;
9472 $response['message'] = 'hCaptcha: ' . __('Unknown error.', 'booking-package');
9473 return $response;
9474
9475 }
9476
9477 $secretKey = get_option($this->prefix . "hCaptcha_Secret_key", "0");
9478 $args = array(
9479 'method' => 'POST',
9480 'timeout' => $this->request_timeout,
9481 'body' => array(
9482 'secret' => $secretKey,
9483 'response' => $token
9484 )
9485 );
9486 $json = wp_remote_request("https://hcaptcha.com/siteverify", $args);
9487 $statusCode = wp_remote_retrieve_response_code($json);
9488 $result = json_decode(wp_remote_retrieve_body($json), true);
9489 $response['status'] = $result['success'];
9490
9491 /**
9492 $ch = curl_init();
9493 curl_setopt($ch, CURLOPT_URL,"https://hcaptcha.com/siteverify");
9494 curl_setopt($ch, CURLOPT_POST, true );
9495 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(
9496 array(
9497 'secret' => $secretKey,
9498 'response' => $token,
9499 )
9500 ));
9501 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
9502 $json = curl_exec($ch);
9503 curl_close($ch);
9504 $result = json_decode($json, true);
9505 $response['status'] = $result['success'];
9506 **/
9507
9508 if (isset($result['error-codes'])) {
9509
9510 $response['message'] = $result['error-codes'];
9511
9512 }
9513
9514 return $response;
9515
9516 }
9517
9518 public function verifyGoogleReCaptchaWithGoogleCloud($googleReCaptchaToken) {
9519
9520 $response = array('status' => true, 'message' => null, 'v' => null);
9521 $googleReCAPTCHA_active = get_option($this->prefix . "googleReCAPTCHA_active", "0");
9522 $siteKey = get_option($this->prefix . "googleReCAPTCHA_site_key", null);
9523 $projectId = get_option($this->prefix . "googleCloudProjectId", null);
9524 $apiKey = get_option($this->prefix . "googleCloudApiKey", null);
9525 if (intval($googleReCAPTCHA_active) == 0) {
9526
9527 return $response;
9528
9529 }
9530
9531 if (empty($projectId)) {
9532
9533 $response['status'] = false;
9534 $response['message'] = 'reCaptcha: The Google Cloud Project ID is not entered.';
9535 return $response;
9536
9537 }
9538
9539 if (empty($siteKey)) {
9540
9541 $response['status'] = false;
9542 $response['message'] = 'reCaptcha: The Google Cloud Site Key is not entered.';
9543 return $response;
9544
9545 }
9546
9547 if (empty($apiKey)) {
9548
9549 $response['status'] = false;
9550 $response['message'] = 'reCaptcha: The Google Cloud API Key is not entered.';
9551 return $response;
9552
9553 }
9554
9555 if (empty($googleReCaptchaToken)) {
9556
9557 $response['status'] = false;
9558 $response['message'] = 'reCaptcha: ' . __('Unknown error.', 'booking-package');
9559 return $response;
9560
9561 }
9562
9563 $event = array(
9564 'event' => array(
9565 'token' => $googleReCaptchaToken,
9566 'expectedAction' => 'booking_package',
9567 'siteKey' => $siteKey,
9568 )
9569 );
9570
9571 $args = array(
9572 'method' => 'POST',
9573 'timeout' => $this->request_timeout,
9574 'body' => $event,
9575 );
9576 $json = wp_remote_request('https://recaptchaenterprise.googleapis.com/v1/projects/' . $projectId . '/assessments?key=' . $apiKey, $args);
9577 $statusCode = wp_remote_retrieve_response_code($json);
9578 $result = json_decode(wp_remote_retrieve_body($json), true);
9579 $response['reCaptcha'] = $result;
9580
9581 if (isset($result['error'])) {
9582
9583 $response['status'] = false;
9584 $response['message'] = 'reCaptcha: ' . $result['error']['message'];
9585 return $response;
9586
9587 }
9588
9589 $score = $result['riskAnalysis']['score'];
9590 if (floatval($score) < 0.5) {
9591
9592 $response['status'] = false;
9593 $response['message'] = 'reCaptcha: Your score (' . $score . ') is too low..';
9594
9595 }
9596
9597 return $response;
9598
9599 }
9600
9601 public function verifyGoogleReCaptchaToken($googleReCaptchaToken) {
9602
9603 $response = array('status' => true, 'message' => null, 'v' => null);
9604 $googleReCAPTCHA_active = get_option($this->prefix . "googleReCAPTCHA_active", "0");
9605 if (intval($googleReCAPTCHA_active) == 0) {
9606
9607 return $response;
9608
9609 }
9610
9611 if (empty($googleReCaptchaToken)) {
9612
9613 $response['status'] = false;
9614 $response['message'] = 'reCaptcha: ' . __('Unknown error.', 'booking-package');
9615 return $response;
9616
9617 }
9618
9619 $secretKey = get_option($this->prefix . "googleReCAPTCHA_Secret_key", "0");
9620 $googleReCAPTCHA_v = get_option($this->prefix . "googleReCAPTCHA_version", "v2");
9621 $response['v'] = 'v3';
9622 if ($googleReCAPTCHA_v == 'v2') {
9623
9624 $response['v'] = 'v2';
9625
9626 }
9627
9628 $args = array(
9629 'method' => 'POST',
9630 'timeout' => $this->request_timeout,
9631 'body' => array(
9632 'secret' => $secretKey,
9633 'response' => $googleReCaptchaToken
9634 )
9635 );
9636 $json = wp_remote_request("https://www.google.com/recaptcha/api/siteverify", $args);
9637 $statusCode = wp_remote_retrieve_response_code($json);
9638 $result = json_decode(wp_remote_retrieve_body($json), true);
9639 $response['reCaptcha'] = $result;
9640
9641 /**
9642 $ch = curl_init();
9643 curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
9644 curl_setopt($ch, CURLOPT_POST, true );
9645 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(
9646 array(
9647 'secret' => $secretKey,
9648 'response' => $googleReCaptchaToken,
9649 )
9650 ));
9651 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
9652 $json = curl_exec($ch);
9653 curl_close($ch);
9654 $result = json_decode($json, true);
9655 $response['reCaptcha'] = $result;
9656 **/
9657
9658 if ($result['success']) {
9659
9660 $response['status'] = true;
9661 if ($googleReCAPTCHA_v == 'v3') {
9662
9663 if (floatval($result['score']) < 0.5) {
9664
9665 $response['status'] = false;
9666 $response['message'] = 'reCaptcha: Your score (' . $result['score'] . ') is too low..';
9667
9668 }
9669
9670 }
9671
9672 } else {
9673
9674 $response['status'] = false;
9675 $response['message'] = 'reCaptcha: ' . $result['error-codes'][0];
9676
9677 }
9678
9679 return $response;
9680
9681 }
9682
9683 public function sendVerificationCode($administrator = false) {
9684
9685 $bookingVerificationCode = 'false';
9686 $from = null;
9687 $user = null;
9688 $twilio = null;
9689 $userValues = array();
9690 $accountKey = 1;
9691 if (isset($_POST['accountKey'])) {
9692
9693 $accountKey = $_POST['accountKey'];
9694
9695 }
9696 $calendarAccount = $this->getCalendarAccount($accountKey);
9697 #$from = $calendarAccount['email_from'];
9698 if (isset($_POST['booking_package_user_action']) === false) {
9699
9700 $bookingVerificationCode = $calendarAccount['bookingVerificationCode'];
9701 $user = $this->get_user();
9702 if (intval($user['status']) == 1) {
9703
9704 $bookingVerificationCode = $calendarAccount['bookingVerificationCodeToUser'];
9705
9706 }
9707
9708 if (isset($_POST['userId']) === false) {
9709
9710 $_POST['userId'] = null;
9711
9712 }
9713
9714 $response_user = $this->get_user_id($administrator, $_POST['userId']);
9715 $userValues = $this->getUserValues($accountKey, 'add', $administrator, null, $response_user['user_id']);
9716
9717 } else {
9718
9719 $bookingVerificationCode = 'email';
9720 $userValues = array(
9721 'emails' => array($_POST['user_email']),
9722 'sms' => array(),
9723 );
9724
9725 }
9726
9727
9728
9729 $notifications = array();
9730 $response = array('status' => false, 'message' => null, 'user' => $user, 'userValues' => $userValues, 'bookingVerificationCode' => $bookingVerificationCode);
9731
9732 if ($bookingVerificationCode != 'false') {
9733
9734 #$verificationCode = $_SESSION['verificationCode'];
9735 $verificationCode = rand(100000, 999999);
9736 #setcookie($this->prefix . 'verificationCode', wp_hash($verificationCode));
9737 $from = $calendarAccount['email_from'];
9738 if (empty($from)) {
9739
9740 $from = get_option($this->prefix . 'email_from', null);
9741
9742 }
9743
9744 $subject = __('Verification code', 'booking-package') . ' [' . get_option($this->prefix . 'site_name', 'Booking Package') . ']';
9745 $body = sprintf(__('Your verification code is: %s', 'booking-package'), $verificationCode) . "\n\n" . get_option($this->prefix . 'site_name', 'Booking Package') . "\n" . $from;
9746 $email = $userValues['emails'];
9747 $sms = $userValues['sms'];
9748 if ($bookingVerificationCode == 'emailAndSms' || $bookingVerificationCode == 'email') {
9749
9750 for ($i = 0; $i < count($email); $i++) {
9751
9752 $this->sendMail($email[$i], $subject, $body, 'text');
9753 array_push($notifications, $email[$i]);
9754
9755 }
9756
9757 }
9758
9759 if ($bookingVerificationCode == 'emailAndSms' || $bookingVerificationCode == 'sms') {
9760
9761 $twilio = $this->twilioSMS($sms, $body);
9762 for ($i = 0; $i < count($sms); $i++) {
9763
9764 array_push($notifications, $sms[$i]);
9765
9766 }
9767
9768 }
9769
9770 if (count($notifications) == 0) {
9771
9772 $response['message'] = __("We couldn't send you a verification code.", 'booking-package');
9773
9774 } else {
9775
9776 $response['status'] = true;
9777 $response['verificationHashCode'] = wp_hash($verificationCode);
9778 $response['twilio'] = $twilio;
9779 $response['notifications'] = implode(', ', $notifications);
9780
9781 }
9782
9783 } else {
9784
9785 $response['message'] = __("We couldn't send you a verification code.", 'booking-package');
9786
9787 }
9788
9789 return $response;
9790
9791 }
9792
9793 public function checkVerificationCode($administrator = false) {
9794
9795 $response = array('status' => true, 'verificationCode' => esc_html($_POST['verificationCode']), 'verificationHashCode' => wp_hash($_POST['verificationCode']), 'error_message' => __('The verification code is incorrect.', 'booking-package'));
9796 /**
9797 if ($_POST['verificationCode'] == $_SESSION['verificationCode']) {
9798
9799 unset($_SESSION['verificationCode']);
9800 $response['status'] = true;
9801
9802 } else {
9803
9804 $response['message'] = __('The verification code is incorrect.', 'booking-package');
9805
9806 }
9807 **/
9808 return $response;
9809
9810 }
9811
9812 public function sendBooking($administrator = false) {
9813
9814 $accountKey = 1;
9815 $accountCalendarKey = 1;
9816 if (isset($_POST['accountKey'])) {
9817
9818 $accountKey = intval($_POST['accountKey']);
9819 $accountCalendarKey = intval($_POST['accountKey']);
9820
9821 }
9822
9823 if (isset($_POST['userId']) === false) {
9824
9825 $_POST['userId'] = null;
9826
9827 }
9828
9829 $permalink = "";
9830 if (isset($_POST['permalink'])) {
9831
9832 $permalink = $_POST['permalink'];
9833
9834 }
9835
9836 if ($administrator === false) {
9837
9838 if (!isset($_POST['googleReCaptchaToken'])) {
9839
9840 $_POST['googleReCaptchaToken'] = '';
9841
9842 }
9843 $result = $this->verifyGoogleReCaptchaToken($_POST['googleReCaptchaToken']);
9844 if ($result['status'] === false) {
9845
9846 $this->cancelPayment();
9847 $result['status'] = 'error';
9848 return $result;
9849
9850 }
9851
9852 if (!isset($_POST['hCaptcha'])) {
9853
9854 $_POST['hCaptcha'] = '';
9855
9856 }
9857 $result = $this->verifyHCaptcha($_POST['hCaptcha']);
9858 if ($result['status'] === false) {
9859
9860 $this->cancelPayment();
9861 $result['status'] = 'error';
9862 return $result;
9863
9864 }
9865
9866 }
9867
9868 $service = null;
9869 $coupon = null;
9870 $maintenanceTime = 0;
9871 $remainderTime = 0;
9872 $timestamp = intval(date('U'));
9873 $sendDate = date('U');
9874 $totalCost = 0;
9875 $courseKey = null;
9876 $jsonList = null;
9877 $ressponse = array();
9878 $selectedOptions = array();
9879 $userInformationValues = array();
9880 $responseGuests = array();
9881 $services = array();
9882 $guests = array();
9883 $taxes = array();
9884 $sql_start_unixTime = null;
9885 $sql_max_unixTime = null;
9886 $currency = get_option($this->prefix."currency", 'usd');
9887 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
9888 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
9889 $courseTime = 0;
9890 $courseCost = 0;
9891 $payName = null;
9892 $payId = null;
9893 $stripe_konbini = 0;
9894 $stripe_paypay = 0;
9895 $payResponse = array();
9896
9897 global $wpdb;
9898
9899 $calendarAccount = $this->getCalendarAccount($accountKey);
9900 if (intval($calendarAccount['schedulesSharing']) == 1) {
9901
9902 $accountCalendarKey = intval($calendarAccount['targetSchedules']);
9903
9904 }
9905 $paymentMethod = explode(",", $calendarAccount['paymentMethod']);
9906 $preparation = array("time" => intval($calendarAccount["preparationTime"]), "position" => $calendarAccount["positionPreparationTime"], "v" => 1);
9907 $response_user = $this->get_user_id($administrator, $_POST['userId']);
9908
9909 if ($calendarAccount['type'] == 'hotel') {
9910
9911 $timestamp = mktime(0, 0, 0, date('m', $timestamp), date('d', $timestamp), date('Y', $timestamp));
9912
9913 }
9914
9915 $userValues = $this->getUserValues($accountKey, 'add', $administrator, null, $response_user['user_id']);
9916 if (isset($userValues['status']) && $userValues['status'] == 'error') {
9917
9918 $this->cancelPayment();
9919 return $userValues;
9920
9921 }
9922 $form = $userValues['form'];
9923 $emails = $userValues['emails'];
9924
9925
9926 $blocksEmailEesult = $this->blocksEmail($response_user['user_id'], $emails);
9927 if ($blocksEmailEesult['status'] == 'error') {
9928
9929 $this->cancelPayment();
9930 return $blocksEmailEesult;
9931
9932 }
9933
9934
9935 $visitorBookingDate = 'null';
9936 $visitorEmail = array();
9937 $visitorName = array();
9938 foreach ((array) $form as $key => $value) {
9939
9940 if ($value['isName'] == 'true') {
9941
9942 array_push($visitorName, $value['value']);
9943
9944 }
9945
9946 if ($value['isEmail'] == 'true') {
9947
9948 array_push($visitorEmail, $value['value']);
9949
9950 }
9951
9952 }
9953 $visitorEmail = implode(" ", $visitorEmail);
9954 $visitorName = implode(" ", $visitorName);
9955
9956 $table_name = $wpdb->prefix . "booking_package_schedules";
9957 $sql = $wpdb->prepare(
9958 "SELECT *, `unixTime` - (`deadlineTime` * 60) as `unixTimeDeadline` FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
9959 array(intval($_POST['timeKey']))
9960 );
9961 $row = $wpdb->get_row($sql, ARRAY_A);
9962 if (is_null($row)) {
9963
9964 $public = false;
9965 if(intval($_POST['public']) == 1){
9966
9967 $public = true;
9968
9969 }
9970
9971 $this->cancelPayment();
9972 $response = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), false, $public);
9973 $response['status'] = 'error';
9974 $response['message'] = __("Schedule was not found", 'booking-package');
9975 return $response;
9976
9977 } else {
9978
9979 if (isset($_POST['couponID'])) {
9980
9981 $couponResponse = $this->serachCoupons($row['unixTime'], $_POST['couponID'], $accountKey);
9982 if (intval($couponResponse['status']) == 1) {
9983
9984 $coupon = $couponResponse['coupon'];
9985
9986 } else {
9987
9988 $this->cancelPayment();
9989 return $couponResponse;
9990
9991 }
9992
9993 }
9994 $row = $this->fixUnixTimeShift($row, $calendarAccount['timezone']);
9995 $visitorBookingDate = date('r', $row['unixTime']);
9996 if (isset($row['fixedUnixTime']) && $row['fixedUnixTime'] === true) {
9997
9998 $table_name = $wpdb->prefix . "booking_package_schedules";
9999 $sql = $wpdb->prepare(
10000 "SELECT `key`, `unixTime`, `hour`, `min`, `month`, `day`, `year` FROM `".$table_name."` WHERE `accountKey` = %d AND `year` = %d AND `month` = %d AND `status` = 'open' ORDER BY `unixTime` ASC;",
10001 array(intval($calendarAccount['key']), intval($row['year']), intval($row['month']))
10002 );
10003 $schedules = $wpdb->get_results($sql, ARRAY_A);
10004 foreach ((array) $schedules as $key => $value) {
10005
10006 $value = $this->fixUnixTimeShift($value, $calendarAccount['timezone']);
10007
10008 }
10009
10010 }
10011
10012 if ($this->confirmRegularHolidays($accountKey, $row['month'], $row['day'], $row['year']) === true) {
10013
10014 $this->cancelPayment();
10015 $response = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), false, $public);
10016 $response['status'] = 'error';
10017 $response['reload'] = 0;
10018 $response['message'] = __("The requested schedule has been closed.", 'booking-package');
10019 return $response;
10020
10021 }
10022
10023 if (intval($row['unixTimeDeadline']) < $timestamp && $administrator === false) {
10024
10025 $public = false;
10026 if(intval($_POST['public']) == 1){
10027
10028 $public = true;
10029
10030 }
10031
10032 $this->cancelPayment();
10033 $response = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), false, $public);
10034 $response['status'] = 'error';
10035 $response['reload'] = 0;
10036 $response['timestamp'] = $timestamp;
10037 $response['unixTimeDeadline'] = $row['unixTimeDeadline'];
10038 $response['message'] = __("The requested schedule has been closed.", 'booking-package');
10039 return $response;
10040
10041 }
10042
10043
10044
10045 $applicantCount = intval($_POST['applicantCount']);
10046 $startTime = $row['unixTime'];
10047 $sql_start_unixTime = $row['unixTime'];
10048 $schedule = $row;
10049 $scheduleUnixTime = intval($row['unixTime']);
10050 $scheduleTitle = $row['title'];
10051 $scheduleCost = intval($row['cost']);
10052 $totalCost += intval($row['cost']) * $applicantCount;
10053 $bookingYMD = intval($row['year'] . sprintf('%02d%02d', $row['month'], $row['day']));
10054 if ($row['unixTime'] == $scheduleUnixTime) {
10055
10056 if ($calendarAccount['type'] == "hotel" && isset($_POST['json'])) {
10057
10058 $accommodationDetails = $this->createAccommodationDetails($accountKey, $accountCalendarKey, $_POST['json'], $sql_start_unixTime, $applicantCount, 'book', null);
10059
10060 if (isset($accommodationDetails['status']) && $accommodationDetails['status'] == "error") {
10061
10062 $this->cancelPayment();
10063 return $accommodationDetails;
10064
10065 } else {
10066
10067 $account_sql = $accommodationDetails['sql'];
10068 $valueArray = $accommodationDetails['valueArray'];
10069 $sql_max_unixTime = $accommodationDetails['sql_max_unixTime'];
10070 unset($accommodationDetails['sql']);
10071 unset($accommodationDetails['valueArray']);
10072 unset($accommodationDetails['sql_max_unixTime']);
10073 $this->setAccommodationDetails($accommodationDetails);
10074
10075 }
10076
10077 $applicantCount = $accommodationDetails['applicantCount'];
10078 $taxes = $accommodationDetails['taxes'];
10079 $totalCost = $accommodationDetails['totalCost'];
10080 $taxes = $this->createTaxesDetails($accountKey, 'hotel', $totalCost, 0, null, null);
10081 $taxes = $accommodationDetails['taxes'];
10082
10083 } else {
10084
10085 if (isset($_POST['guests']) && intval($calendarAccount['guestsBool']) == 1) {
10086
10087 $responseGuests = $this->getSelectedGuests($calendarAccount, $_POST['guests'] );
10088 if ($responseGuests['isGuests'] === true) {
10089
10090 $guests = $responseGuests['guests'];
10091 $applicantCount = $responseGuests['applicantCount'];
10092 if ($applicantCount == 0) {
10093
10094 $applicantCount = 1;
10095
10096 }
10097
10098 } else {
10099
10100 $this->cancelPayment();
10101 $responseGuests['status'] = 'error';
10102 return $responseGuests;
10103
10104 }
10105
10106 $totalCost += $this->getSelectedGuestTotalAmount($calendarAccount, $responseGuests['guests'], true);
10107
10108 }
10109
10110 $verificationMaxBookingSlotsPerDay = $this->verificationMaxBookingSlotsPerDay($calendarAccount, $row, $applicantCount);
10111 if ($verificationMaxBookingSlotsPerDay['status'] === false) {
10112
10113 $this->cancelPayment();
10114 $verificationMaxBookingSlotsPerDay['status'] = 'error';
10115 return $verificationMaxBookingSlotsPerDay;
10116
10117 }
10118
10119 if (isset($_POST['courseKey']) || isset($_POST['selectedCourseList'])) {
10120
10121 $verifyServices = true;
10122 if ($administrator === true) {
10123
10124 #$verifyServices = false;
10125
10126 }
10127
10128 $servicesDetails = $this->getSelectedServices($calendarAccount, $_POST['selectedCourseList'], $guests, "selectedOptionsList", $coupon, $applicantCount, $verifyServices);
10129 if ($servicesDetails['status'] === false) {
10130
10131 return array('status' => 'error', 'message' => $servicesDetails['message']);
10132
10133 }
10134
10135 $services = $servicesDetails['object'];
10136 foreach ((array) $services as $key => $service) {
10137
10138 $row = $this->serachCourse($accountKey, $_POST['timeKey'], $service['key'], $servicesDetails, $bookingYMD);
10139 if (isset($row['status']) && $row['status'] == 'error') {
10140
10141 $this->cancelPayment();
10142 $row['message'] = sprintf($row['message'], $service['name']);
10143 return $row;
10144
10145 }
10146
10147
10148 }
10149
10150 $courseTime += intval($servicesDetails['time']);
10151 $courseCost += intval($servicesDetails['cost']);
10152 #$totalCost += intval($servicesDetails['cost']) * $applicantCount;
10153 $totalCost += intval($servicesDetails['cost']);
10154 $sql_max_unixTime = $sql_start_unixTime + ($courseTime * 60) + ($maintenanceTime * 60);
10155
10156 if (intval($calendarAccount['blockSameTimeBookingByUser']) == 1) {
10157
10158 $blockSameTimeBookingByUser = $this->blockSameTimeBookingByUser($response_user['user_id'], $calendarAccount, $sql_start_unixTime, $sql_max_unixTime, $emails);
10159 if ($blockSameTimeBookingByUser['status'] == 'error') {
10160
10161 $this->cancelPayment();
10162 return $blockSameTimeBookingByUser;
10163
10164 }
10165
10166 }
10167
10168 $table_name = $wpdb->prefix . "booking_package_schedules";
10169 $account_sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
10170 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
10171
10172 $sql_start_unixTime -= $preparation['time'] * 60;
10173
10174 }
10175
10176 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
10177
10178 $sql_max_unixTime += $preparation['time'] * 60;
10179
10180 }
10181
10182 $valueArray = array(intval($accountCalendarKey), intval($sql_start_unixTime), intval($sql_max_unixTime));
10183
10184 } else {
10185
10186 $sql_max_unixTime = $sql_start_unixTime;
10187 if (intval($calendarAccount['blockSameTimeBookingByUser']) == 1) {
10188
10189 $blockSameTimeBookingByUser = $this->blockSameTimeBookingByUser($response_user['user_id'], $calendarAccount, $sql_start_unixTime, null, $emails);
10190 if ($blockSameTimeBookingByUser['status'] == 'error') {
10191
10192 $this->cancelPayment();
10193 return $blockSameTimeBookingByUser;
10194
10195 }
10196
10197 }
10198
10199 $table_name = $wpdb->prefix . "booking_package_schedules";
10200 $account_sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` <= %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
10201 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
10202
10203 $sql_start_unixTime = $startTime - $preparation['time'] * 60;
10204
10205 }
10206
10207 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
10208
10209 #$sql_max_unixTime = ($startTime + $preparation['time'] * 60) - 1;
10210 $sql_max_unixTime = $startTime + $preparation['time'] * 60;
10211
10212 }
10213 $valueArray = array(intval($accountCalendarKey), intval($sql_start_unixTime), intval($sql_max_unixTime));
10214
10215 }
10216
10217 $taxes = $this->createTaxesDetails($accountKey, 'day', $totalCost, $bookingYMD, $applicantCount, null);
10218 $accommodationDetails['taxes'] = $taxes;
10219 for ($i = 0; $i < count($taxes); $i++) {
10220
10221 $tax = $taxes[$i];
10222 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_exclusive') {
10223
10224 $totalCost += $tax['taxValue'];
10225
10226 } else if ($tax['type'] == 'surcharge') {
10227
10228 $totalCost += $tax['taxValue'] * $applicantCount;
10229
10230 }
10231
10232 }
10233
10234 }
10235
10236 $response = apply_filters('booking_package_send_booking', $response_user, $schedule);
10237 if (empty($response) === false && isset($response['status']) && $response['status'] == 'error') {
10238
10239 $this->cancelPayment();
10240 return array('status' => $response['status'], 'message' => $response['message']);
10241
10242 }
10243
10244 $souce = array(
10245 array("mode" => "increase", "sql" => $account_sql, "values" => $valueArray),
10246 );
10247 $increaseSouce = $souce;
10248 $updateSchedule = $this->updateRemainderSeart($souce, $applicantCount);
10249 if (isset($updateSchedule['status']) && $updateSchedule['status'] == 'error') {
10250
10251 $public = false;
10252 if (intval($_POST['public']) == 1) {
10253
10254 $public = true;
10255
10256 }
10257
10258 $this->cancelPayment();
10259 $response = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), false, $public);
10260 $response['status'] = 'error';
10261 $response['reload'] = 0;
10262 $response['message'] = $updateSchedule['message'];
10263 return $response;
10264
10265 }
10266 $this->updateBookingCount('add', intval($_POST['timeKey']), intval($applicantCount));
10267 $status = $this->getStatus();
10268 $privateResponse = $this->insertPrivateData($sendDate, $_POST['permission'], $status, $_POST['timeKey'], $scheduleUnixTime, $scheduleTitle, $scheduleCost, $services, $form, $emails, $currency, null, null, $accountKey, $permalink, $preparation, $taxes, $responseGuests, $coupon, $administrator, $applicantCount);
10269
10270 #$privateResponse = $this->insertPrivateData($sendDate, $_POST['permission'], $status, $_POST['timeKey'], $scheduleUnixTime, $scheduleTitle, $scheduleCost, $courseKey, $courseName, $courseTime, $courseCost, $selectedOptions, $form, $currency, $_POST['payType'], $cardToken, $accountKey, $permalink, $preparation, $taxes, $applicantCount);
10271 $lastID = $privateResponse['lastID'];
10272
10273 /** Stripe and PayPal **/
10274 $payment_active = 0;
10275 $payment_mode = 0;
10276 $payment_live = 0;
10277 $public_key = null;
10278 $secret_key = null;
10279 $cardToken = null;
10280 if (isset($_POST['payToken'])) {
10281
10282 if ($_POST['payType'] == 'stripe') {
10283
10284 $payment_active = 0;
10285 if (!is_bool(array_search(strtolower($_POST['payType']), $paymentMethod))) {
10286
10287 $payment_active = 1;
10288
10289 }
10290 $secret_key = get_option($this->prefix."stripe_secret_key", null);
10291
10292 } else if ($_POST['payType'] == 'paypal') {
10293
10294 $payment_active = 0;
10295 if (!is_bool(array_search(strtolower($_POST['payType']), $paymentMethod))) {
10296
10297 $payment_active = 1;
10298
10299 }
10300 $payment_live = get_option($this->prefix."paypal_live", "0");
10301 $public_key = get_option($this->prefix."paypal_client_id", null);
10302 $secret_key = get_option($this->prefix."paypal_secret_key", null);
10303
10304 }
10305
10306 if (isset($_POST['stripe_konbini']) && intval($_POST['stripe_konbini']) === 1) {
10307
10308 $stripe_konbini = intval($_POST['stripe_konbini']);
10309
10310 }
10311
10312 if (isset($_POST['stripe_paypay']) && intval($_POST['stripe_paypay']) === 1) {
10313
10314 $stripe_paypay = intval($_POST['stripe_paypay']);
10315
10316 }
10317
10318 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
10319 $currency = get_option($this->prefix."currency", "usd");
10320 $amount = $this->getAmount($lastID, $calendarAccount, $accommodationDetails, $services, $responseGuests, null, $coupon);
10321 if (intval($payment_active) == 1 && !empty($secret_key)) {
10322
10323 $payResponse = $creditCard->pay($_POST['payType'], $stripe_konbini, $stripe_paypay, $public_key, $secret_key, $_POST['payToken'], $payment_live, $amount, $currency, $lastID, $visitorName, $visitorEmail, $visitorBookingDate);
10324 if (isset($payResponse['error'])) {
10325
10326 $wpdb->delete(
10327 $wpdb->prefix . "booking_package_booked_customers",
10328 array(
10329 'key' => intval($lastID)
10330 ),
10331 array('%d')
10332 );
10333
10334 $souce = array(
10335 array("mode" => "reduce", "sql" => $account_sql, "values" => $valueArray),
10336 );
10337
10338 $updateSchedule = $this->updateRemainderSeart($souce, $applicantCount);
10339 $this->cancelPayment();
10340 if (isset($updateSchedule['status']) && $updateSchedule['status'] == 'error') {
10341
10342 return $updateSchedule;
10343
10344 }
10345 return array('status' => 'error', 'message' => $payResponse['error'], "totalCost" => $totalCost, "currency" => $currency, "totalCost" => $totalCost);
10346
10347 } else {
10348
10349 $cardToken = $payResponse['cardToken'];
10350 $payMode = "CreditCard";
10351 if ($_POST['payType'] == 'stripe') {
10352
10353 $payId = "stripe";
10354 $payName = "Stripe";
10355
10356 if ($stripe_konbini == 1) {
10357
10358 $payId = "stripe_konbini";
10359 $payMode = "stripeKonbini";
10360
10361 }
10362
10363 if($stripe_paypay == 1) {
10364
10365 $payId = "stripe_paypay";
10366 $payMode = "stripePayPay";
10367
10368 }
10369
10370 } else if ($_POST['payType'] == 'paypal') {
10371
10372 $payId = "paypal";
10373 $payName = "PayPal";
10374
10375 }
10376
10377 $wpdb->update(
10378 $wpdb->prefix . "booking_package_booked_customers",
10379 array(
10380 'payMode' => $payMode,
10381 'payId' => $payId,
10382 'payName' => $payName,
10383 'payToken' => sanitize_text_field($cardToken),
10384 ),
10385 array('key' => intval($lastID)),
10386 array('%s', '%s', '%s', '%s'),
10387 array('%d')
10388 );
10389
10390 }
10391
10392 }
10393
10394 }
10395 /** Stripe and PayPal **/
10396
10397 $userInformation = $this->setUserInformation($form);
10398 if(isset($userInformation['values'])){
10399
10400 $userInformationValues = $userInformation['values'];
10401
10402 }
10403
10404 $cancellationToken = $privateResponse['cancellationToken'];
10405 $cancellationUri = null;
10406 if ($administrator === false) {
10407
10408 $cancellationUri = $this->getCancellationUri($permalink, $lastID, $cancellationToken);
10409
10410 }
10411
10412 /**
10413 if(isset($cardToken) && !is_null($cardToken) && $_POST['payType'] == 'paypal'){
10414
10415 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
10416 $payResponse = $creditCard->update($_POST['payType'], $public_key, $secret_key, $_POST['payToken'], $lastID, $payment_live);
10417
10418 }
10419 **/
10420
10421 }
10422
10423 }
10424
10425 if (intval($_POST['sendEmail']) == 1) {
10426
10427 $email = $this->createEmailMessage($accountKey, 'new_booking_notification', intval($lastID));
10428
10429 }
10430
10431 if ($calendarAccount['type'] == 'hotel') {
10432
10433 $sql_max_unixTime += 1440 * 60;
10434
10435 }
10436
10437 #$setting = new booking_package_setting($this->prefix, $this->pluginName);
10438 #$googleCalendar = $setting->pushGC('insert', $accountKey, $calendarAccount['type'], $lastID, $calendarAccount['googleCalendarID'], $sql_start_unixTime, $sql_max_unixTime, $form);
10439 #$this->updateQueueForGC($lastID, $googleCalendar);
10440
10441 $iCal = false;
10442 $public = false;
10443 if(isset($_POST['public']) && intval($_POST['public']) == 1){
10444
10445 $public = true;
10446
10447 }
10448
10449 $ressponse = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), $iCal, $public);
10450 #$ressponse['account'] = $this->getCalendarAccount($accountKey);
10451 $ressponse['automaticApprove'] = $this->automaticApprove;
10452 $ressponse['userInformationValues'] = $userInformationValues;
10453 #$ressponse['payResponse'] = $payResponse;
10454 $ressponse['applicantCount'] = $applicantCount;
10455 $ressponse['lastID'] = $lastID;
10456 if (isset($email)) {
10457
10458 #$ressponse['sendEmails'] = $email;
10459 $ressponse['sendVisitor'] = $email['sendVisitor'];
10460 if (isset($email['sendControl'])) {
10461
10462 $ressponse['sendControl'] = $email['sendControl'];
10463
10464 }
10465
10466 }
10467
10468 $ressponse['selectedOptions'] = $selectedOptions;
10469 $ressponse['form'] = $form;
10470 $ressponse['services'] = $services;
10471 $ressponse['status'] = "success";
10472 $ressponse['increaseSouce'] = $increaseSouce;
10473 $ressponse['response_user'] = $response_user;
10474 $ressponse['responseGuests'] = $responseGuests;
10475
10476 do_action('booking_package_booking_completed', $lastID);
10477
10478 return $ressponse;
10479
10480 }
10481
10482 public function updateBookingCount($mode, $key, $applicantCount) {
10483
10484 global $wpdb;
10485 $table_name = $wpdb->prefix . "booking_package_schedules";
10486 $sql = $wpdb->prepare(
10487 "SELECT `bookingCount` FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
10488 array(intval($key))
10489 );
10490 $row = $wpdb->get_row($sql, ARRAY_A);
10491 $bookingCount = intval($row['bookingCount']);
10492
10493
10494 try {
10495
10496 $wpdb->query("START TRANSACTION");
10497 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE");
10498
10499 if ($mode === 'add') {
10500
10501 $bookingCount += $applicantCount;
10502
10503 } else {
10504
10505 $bookingCount -= $applicantCount;
10506 if ($bookingCount < 0) {
10507
10508 $bookingCount = 0;
10509
10510 }
10511
10512 }
10513
10514 $updateSql = $wpdb->prepare(
10515 'UPDATE `' . $table_name . '` SET `bookingCount` = %d WHERE `key` = %d;',
10516 array(intval($bookingCount), intval($key))
10517 );
10518 $bool = $wpdb->query($updateSql);
10519
10520 $wpdb->query('COMMIT');
10521 $wpdb->query('UNLOCK TABLES');
10522
10523 } catch (Exception $e) {
10524
10525 $wpdb->query('ROLLBACK');
10526 $wpdb->query('UNLOCK TABLES');
10527 $error = json_decode($e->getMessage(), true);
10528 return $error;
10529
10530 }
10531 /** finally {
10532
10533 $wpdb->query('UNLOCK TABLES');
10534
10535 }
10536 **/
10537
10538 }
10539 public function cancelPayment() {
10540
10541 if (isset($_POST['payType']) && $_POST['payType'] == 'stripe') {
10542
10543 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
10544 $secret_key = get_option($this->prefix."stripe_secret_key", null);
10545 if (empty($secret_key) === false) {
10546
10547 $creditCard->cancelStripe(0, $secret_key, $_POST['payToken']);
10548
10549 }
10550
10551 }
10552
10553 }
10554
10555 public function getCancellationUri($permalink, $id, $token) {
10556
10557 $parse_url = parse_url($permalink);
10558 if (isset($parse_url['query'])) {
10559
10560 $parse_url['query'] .= "&bookingID=".$id."&bookingToken=".$token;
10561
10562 } else {
10563
10564 $parse_url['query'] = "bookingID=".$id."&bookingToken=".$token;
10565
10566 }
10567
10568 $permalink = $parse_url['scheme'].'://'.$parse_url['host'];
10569 if (isset($parse_url['port'])) {
10570
10571 $permalink .= ':'.$parse_url['port'];
10572
10573 }
10574
10575 if (isset($parse_url['path'])) {
10576
10577 $permalink .= $parse_url['path'];
10578
10579 }
10580
10581 if (isset($parse_url['query'])) {
10582
10583 $permalink .= '?'.$parse_url['query'];
10584
10585 }
10586
10587 if (isset($parse_url['fragment'])) {
10588
10589 $permalink .= '#'.$parse_url['fragment'];
10590
10591 }
10592
10593 return $permalink;
10594
10595 }
10596
10597 public function getSelectedGuests($calendarAccount, $selectedGuestsString, $mode = 'add') {
10598
10599 $setting = new booking_package_setting($this->prefix, $this->pluginName);
10600 $limitNumberOfGuests = $calendarAccount['limitNumberOfGuests'];
10601 if (is_array($limitNumberOfGuests) === false) {
10602
10603 $limitNumberOfGuests = json_decode($calendarAccount['limitNumberOfGuests'], true);
10604
10605 }
10606
10607 if (empty($limitNumberOfGuests)) {
10608
10609 $limitNumberOfGuests = array(
10610 'minimumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
10611 'maximumGuests' => array('enabled' => 0, 'included' => 0, 'number' => 0),
10612 );
10613
10614 }
10615
10616 $response = array(
10617 'isGuests' => false,
10618 'guests' => array(),
10619 'applicantCount' => 0,
10620 'requiredTotalNumberOfGuests' => 0,
10621 'unrequiredTotalNumberOfGuests' => 0,
10622 'reflectService' => 0,
10623 'reflectAdditional' => 0,
10624 'reflectServiceTitle' => null,
10625 'reflectAdditionalTitle' => null,
10626 'limitNumberOfGuests' => $limitNumberOfGuests,
10627 );
10628 $selectedGuests = null;
10629 if (is_array($selectedGuestsString)) {
10630
10631 $selectedGuests = $json;
10632
10633 } else {
10634
10635 #$selectedGuests = json_decode(str_replace("\\", "", $selectedGuestsString), true);
10636 $selectedGuests = json_decode(stripslashes($selectedGuestsString), true);
10637
10638 }
10639
10640 $isExtensionsValid = $this->getExtensionsValid();
10641 global $wpdb;
10642 $table_name = $wpdb->prefix . "booking_package_guests";
10643 for ($guestKey = 0; $guestKey < count($selectedGuests); $guestKey++) {
10644
10645 $selectedGuest = $selectedGuests[$guestKey];
10646 $sql = $wpdb->prepare("SELECT * FROM " . $table_name . " WHERE `key` = %d ORDER BY ranking ASC;", array(intval($selectedGuest['key'])));
10647 $row = $wpdb->get_row($sql, ARRAY_A);
10648 if (is_null($row)) {
10649
10650 return $response;
10651
10652 } else {
10653
10654 $row = $setting->getTranslateGuest($row, intval($calendarAccount['key']) );
10655 $list = json_decode($row['json'], true);
10656 array_unshift($list, array("number" => 0, "price" => 0, "name" => __("Select")));
10657 $selected = 0;
10658 for ($listKey = 0; $listKey < count($list); $listKey++) {
10659
10660 $list[$listKey]['selected'] = 0;
10661
10662 }
10663
10664 $key = intval($selectedGuest['index']);
10665 if (isset($list[$key]) && isset($selectedGuest['selectedName']) && $list[$key]['name'] == $selectedGuest['selectedName']) {
10666
10667 $row['index'] = $key;
10668 $row['number'] = intval($list[$key]['number']);
10669 $selected = 1;
10670 $list[$key]['selected'] = 1;
10671 if ($row['guestsInCapacity'] == 'included' && intval($list[$key]['number']) > 0) {
10672
10673 $response['applicantCount'] += intval($list[$key]['number']);
10674
10675 }
10676
10677 if ($isExtensionsValid !== true) {
10678
10679 $row['costInServices'] = 'cost_1';
10680 $row['reflectService'] = '0';
10681 $row['reflectAdditional'] = '0';
10682
10683 }
10684
10685 if (intval($row['required']) == 1) {
10686
10687 $response['requiredTotalNumberOfGuests'] += intval($list[$key]['number']);
10688
10689 } else {
10690
10691 $response['unrequiredTotalNumberOfGuests'] += intval($list[$key]['number']);
10692
10693 }
10694
10695 if (intval($row['reflectService']) == 1 && intval($list[$key]['number']) > 0) {
10696
10697 $response['reflectService'] += intval($list[$key]['number']);
10698
10699 }
10700
10701 if (intval($row['reflectAdditional']) == 1 && intval($list[$key]['number']) > 0) {
10702
10703 $response['reflectAdditional'] += intval($list[$key]['number']);
10704
10705 }
10706
10707 }
10708
10709 if ($selected == 0) {
10710
10711 $row['index'] = 0;
10712 $row['number'] = 0;
10713 $list[0]['selected'] = 1;
10714
10715 }
10716
10717 $row['json'] = $list;
10718
10719 }
10720
10721 if ($response['reflectService'] == 1) {
10722
10723 $response['reflectServiceTitle'] = sprintf(__('%s guest', 'booking-package'), $response['reflectService']);
10724
10725 } else if ($response['reflectService'] > 1) {
10726
10727 $response['reflectServiceTitle'] = sprintf(__('%s guests', 'booking-package'), $response['reflectService']);
10728
10729 }
10730
10731 if ($response['reflectAdditional'] == 1) {
10732
10733 $response['reflectAdditionalTitle'] = sprintf(__('%s guest', 'booking-package'), $response['reflectAdditional']);
10734
10735 } else if ($response['reflectAdditional'] > 1) {
10736
10737 $response['reflectAdditionalTitle'] = sprintf(__('%s guests', 'booking-package'), $response['reflectAdditional']);
10738
10739 }
10740
10741 array_push($response['guests'], $row);
10742
10743 }
10744
10745 if ($response['reflectService'] == 0) {
10746
10747 $response['reflectService'] = 1;
10748 $response['reflectServiceTitle'] = 1 . __('guest', 'booking-package');
10749
10750 }
10751
10752 if ($response['reflectAdditional'] == 0) {
10753
10754 $response['reflectAdditional'] = 1;
10755 $response['reflectAdditionalTitle'] = 1 . __('guest', 'booking-package');
10756
10757 }
10758
10759 $response['isGuests'] = true;
10760
10761 $minimumGuests = $limitNumberOfGuests['minimumGuests'];
10762 if ($minimumGuests['enabled'] == 1 && $minimumGuests['number'] > 0) {
10763
10764 if ($minimumGuests['included'] == 1 && $minimumGuests['number'] > ($response['requiredTotalNumberOfGuests'] + $response['unrequiredTotalNumberOfGuests'])) {
10765
10766 $response['isGuests'] = false;
10767 $response['message'] = sprintf(__('The total number of people must be %s or more.', 'booking-package'), $minimumGuests['number']);
10768
10769 } else if ($minimumGuests['number'] > $response['requiredTotalNumberOfGuests']) {
10770
10771 $response['isGuests'] = false;
10772 $response['message'] = sprintf(__('The required total number of people must be %s or more.', 'booking-package'), $minimumGuests['number']);
10773
10774 }
10775
10776 if ($response['isGuests'] === false) {
10777
10778 return $response;
10779
10780 }
10781
10782 }
10783
10784 $maximumGuests = $limitNumberOfGuests['maximumGuests'];
10785 if ($maximumGuests['enabled'] == 1 && $maximumGuests['number'] > 0) {
10786
10787 if ($maximumGuests['included'] == 1 && $maximumGuests['number'] < ($response['requiredTotalNumberOfGuests'] + $response['unrequiredTotalNumberOfGuests'])) {
10788
10789 $response['isGuests'] = false;
10790 $response['message'] = sprintf(__('The total number of people must be %s or less.', 'booking-package'), $maximumGuests['number']);
10791
10792 } else if ($maximumGuests['number'] < $response['requiredTotalNumberOfGuests']) {
10793
10794 $response['isGuests'] = false;
10795 $response['message'] = sprintf(__('The required total number of people must be %s or less.', 'booking-package'), $maximumGuests['number']);
10796
10797 }
10798
10799 }
10800
10801 return $response;
10802
10803 }
10804
10805 public function getSelectedServices($calendarAccount, $selectedServices, $guests, $targetOptions, $coupon = array(), $applicantCount = 1, $verifyServices = false) {
10806
10807 global $wpdb;
10808 $time = 0;
10809 $cost = 0;
10810 $hasKeys = array(
10811 "key" => "int",
10812 "accountKey" => "int",
10813 "name" => "string",
10814 "time" => "int",
10815 "cost" => "int",
10816 "cost_1" => "int",
10817 "cost_2" => "int",
10818 "cost_3" => "int",
10819 "cost_4" => "int",
10820 "cost_5" => "int",
10821 "cost_6" => "int",
10822 "active" => "string",
10823 "options" => "object",
10824 "selectedOptionsList" => "object",
10825 "service" => "int",
10826 "selected" => "int",
10827 "stopServiceUnderFollowingConditions" => "string",
10828 "doNotStopServiceAsException" => "string",
10829 "stopServiceForDayOfTimes" => "string",
10830 "stopServiceForSpecifiedNumberOfTimes" => "int",
10831 );
10832 if (isset($selectedServices)) {
10833
10834 $jsonList = $selectedServices;
10835 $services = array();
10836 if (is_string($selectedServices) === true) {
10837
10838 #$jsonList = json_decode(str_replace("\\", "", $selectedServices), true);
10839 $jsonList = json_decode(stripslashes($selectedServices), true);
10840
10841 }
10842
10843 if (is_array($jsonList)) {
10844
10845 $table_name = $wpdb->prefix . "booking_package_services";
10846 for ($i = 0; $i < count($jsonList); $i++) {
10847
10848 if ($verifyServices === true) {
10849
10850 $sql = $wpdb->prepare(
10851 "SELECT * FROM " . $table_name . " WHERE `key` = %d;",
10852 array(intval($jsonList[$i]['key']))
10853 );
10854 $verify_service = $wpdb->get_row($sql, ARRAY_A);
10855 if (empty($verify_service) === true) {
10856
10857 return array('status' => false, 'message' => 'Invalid service.');
10858
10859 }
10860
10861 if ($verify_service['active'] !== 'true') {
10862
10863 return array('status' => false, 'message' => 'Service currently suspended.');
10864
10865 }
10866
10867 $setting = new booking_package_setting($this->prefix, $this->pluginName);
10868 $verify_service = $setting->getTranslateService($verify_service, $calendarAccount['key']);
10869
10870 $jsonList[$i]['time'] = intval($verify_service['time']);
10871 $jsonList[$i]['cost'] = intval($verify_service['cost']);
10872 $jsonList[$i]['cost_1'] = intval($verify_service['cost_1']);
10873 $jsonList[$i]['cost_2'] = intval($verify_service['cost_2']);
10874 $jsonList[$i]['cost_3'] = intval($verify_service['cost_3']);
10875 $jsonList[$i]['cost_4'] = intval($verify_service['cost_4']);
10876 $jsonList[$i]['cost_5'] = intval($verify_service['cost_5']);
10877 $jsonList[$i]['cost_6'] = intval($verify_service['cost_6']);
10878
10879 $verify_options = json_decode($verify_service['options'], true);
10880 if (!is_array($verify_options)) {
10881
10882 $verify_options = array();
10883
10884 }
10885
10886 if (!isset($jsonList[$i]['options']) || !is_array($jsonList[$i]['options'])) {
10887
10888 $jsonList[$i]['options'] = array();
10889
10890 }
10891
10892 if (is_array($verify_options) && is_array($jsonList[$i]['options']) && count($verify_options) === count($jsonList[$i]['options'])) {
10893
10894 $jsonList[$i]['options'] = (function($verify_options, $options) {
10895
10896 for ($j = 0; $j < count($verify_options); $j++) {
10897
10898 if ($verify_options[$j]['name'] !== $options[$j]['name']) {
10899
10900 return false;
10901
10902 }
10903
10904
10905 $verify_option = $verify_options[$j];
10906 $options[$j]['time'] = intval($verify_option['time']);
10907 #$options[$j]['cost'] = intval($verify_option['cost']);
10908 $options[$j]['cost_1'] = intval($verify_option['cost_1']);
10909 $options[$j]['cost_2'] = intval($verify_option['cost_2']);
10910 $options[$j]['cost_3'] = intval($verify_option['cost_3']);
10911 $options[$j]['cost_4'] = intval($verify_option['cost_4']);
10912 $options[$j]['cost_5'] = intval($verify_option['cost_5']);
10913 $options[$j]['cost_6'] = intval($verify_option['cost_6']);
10914
10915 }
10916
10917 return $options;
10918
10919 })($verify_options, $jsonList[$i]['options']);
10920
10921 if ($jsonList[$i]['options'] === false) {
10922
10923 return array('status' => false, 'message' => 'Invalid option name.');
10924
10925 }
10926
10927 } else {
10928
10929 return array('status' => false, 'message' => 'Invalid options.');
10930
10931 }
10932
10933 if (!isset($jsonList[$i]['selectedOptionsList']) || !is_array($jsonList[$i]['selectedOptionsList'])) {
10934
10935 $jsonList[$i]['selectedOptionsList'] = array();
10936
10937 }
10938
10939 if (is_array($verify_options) && is_array($jsonList[$i]['selectedOptionsList']) && count($verify_options) === count($jsonList[$i]['selectedOptionsList'])) {
10940
10941 $jsonList[$i]['selectedOptionsList'] = (function($verify_options, $selectedOptionsList) {
10942
10943 for ($j = 0; $j < count($verify_options); $j++) {
10944
10945 if ($verify_options[$j]['name'] !== $selectedOptionsList[$j]['name']) {
10946
10947 return false;
10948
10949 }
10950
10951 $verify_option = $verify_options[$j];
10952 $selectedOptionsList[$j]['time'] = intval($verify_option['time']);
10953 #$selectedOptionsList[$j]['cost'] = intval($verify_option['cost']);
10954 $selectedOptionsList[$j]['cost_1'] = intval($verify_option['cost_1']);
10955 $selectedOptionsList[$j]['cost_2'] = intval($verify_option['cost_2']);
10956 $selectedOptionsList[$j]['cost_3'] = intval($verify_option['cost_3']);
10957 $selectedOptionsList[$j]['cost_4'] = intval($verify_option['cost_4']);
10958 $selectedOptionsList[$j]['cost_5'] = intval($verify_option['cost_5']);
10959 $selectedOptionsList[$j]['cost_6'] = intval($verify_option['cost_6']);
10960
10961 }
10962
10963 return $selectedOptionsList;
10964
10965 })($verify_options, $jsonList[$i]['selectedOptionsList']);
10966
10967 if ($jsonList[$i]['selectedOptionsList'] === false) {
10968
10969 return array('status' => false, 'message' => 'Invalid option name.');
10970
10971 }
10972
10973 } else {
10974
10975 return array('status' => false, 'message' => 'Invalid options.');
10976
10977 }
10978
10979 }
10980
10981
10982 $time += intval($jsonList[$i]['time']);
10983 //$cost += intval($jsonList[$i]['cost']);
10984 $responseCostInService = $this->getCostsInService($calendarAccount, $jsonList[$i], $guests);
10985 $cost += $responseCostInService['totalCost'];
10986 $service = array('options' => array());
10987 foreach ((array) $hasKeys as $key => $value) {
10988
10989 if (isset($jsonList[$i][$key])) {
10990
10991 if ($value == 'object') {
10992
10993 if ($key == $targetOptions) {
10994
10995 $optionsDetails = $this->getSelectedOptions($calendarAccount, $jsonList[$i][$key], $guests, $applicantCount);
10996 //var_dump($optionsDetails);
10997 $service['options'] = $optionsDetails['object'];
10998 $time += $optionsDetails['time'];
10999 $cost += $optionsDetails['cost'];
11000
11001 }
11002
11003 } else {
11004
11005 $service[sanitize_text_field($key)] = sanitize_text_field($jsonList[$i][$key]);
11006 if ($key === 'int') {
11007
11008 if (is_null($jsonList[$i][$key]) === true) {
11009
11010 $jsonList[$i][$key] = 0;
11011
11012 }
11013 $service[sanitize_text_field($key)] = intval($jsonList[$i][$key]);
11014
11015 }
11016
11017 }
11018
11019 }
11020
11021 }
11022
11023 array_push($services, $service);
11024
11025 }
11026
11027 }
11028
11029 }
11030
11031 $cost = $this->getDiscountCostByCoupon($coupon, $cost);
11032 return array("status" => true, "time" => $time, "cost" => $cost, "object" => $services);
11033
11034 }
11035
11036 public function getDiscountCostByCoupon($coupon, $cost) {
11037
11038 if (!empty($coupon) && is_array($coupon) && isset($coupon['key'])) {
11039
11040 if ($coupon['method'] == 'subtraction') {
11041
11042 if ($cost > intval($coupon['value'])) {
11043
11044 $cost -= intval($coupon['value']);
11045
11046 } else {
11047
11048 $cost = 0;
11049
11050 }
11051
11052 } else {
11053
11054 #totalCost -= totalCost - (totalCost * (100 - parseInt(coupon.value)) / 100);
11055 $cost -= $cost - ($cost * (100 - intval($coupon['value'])) / 100);
11056
11057 }
11058
11059 return intval($cost);
11060
11061 } else {
11062
11063 return $cost;
11064
11065 }
11066
11067 }
11068
11069 public function getSelectedGuestTotalAmount($calendarAccount, $guests, $onlyTotalAmount = true) {
11070
11071 $totalAmount = 0;
11072 if (is_array($guests) === false) {
11073
11074 $guests = json_decode(stripslashes($guests), true);
11075
11076 }
11077 #var_dump($guests);
11078
11079 if (intval($calendarAccount['guestsBool']) == 1 && is_array($guests)) {
11080
11081 foreach ($guests as $key => $guest) {
11082
11083 $index = intval($guest['index']);
11084 if ($index > 0) {
11085
11086 $totalAmount += intval($guest['json'][$index]['price']);
11087 #var_dump($totalAmount);
11088
11089 }
11090
11091 }
11092
11093 }
11094
11095 if ($onlyTotalAmount === true) {
11096
11097 return $totalAmount;
11098
11099 }
11100
11101 }
11102
11103 public function getCostsInService($calendarAccount, $service, $guests) {
11104
11105 $currency = get_option($this->prefix."currency", 'usd');
11106 $hasReflectService = false;
11107 $totalCost = 0;
11108 $totalCost1 = 0;
11109 $totalCost2 = 0;
11110 $hasMultipleCosts = false;
11111 $isExtensionsValid = $this->getExtensionsValid();
11112 if (isset($service['cost_1']) === false) {
11113
11114 if (isset($service['cost']) === true) {
11115
11116 $service['cost_1'] = $service['cost'];
11117 $service['cost_2'] = $service['cost'];
11118 $service['cost_3'] = $service['cost'];
11119 $service['cost_4'] = $service['cost'];
11120 $service['cost_5'] = $service['cost'];
11121 $service['cost_6'] = $service['cost'];
11122
11123 } else {
11124
11125 $service['cost_1'] = 0;
11126 $service['cost_2'] = 0;
11127 $service['cost_3'] = 0;
11128 $service['cost_4'] = 0;
11129 $service['cost_5'] = 0;
11130 $service['cost_6'] = 0;
11131
11132 }
11133
11134 }
11135
11136 if (intval($calendarAccount['guestsBool']) === 1 && is_array($guests)) {
11137
11138 $countActives = 0;
11139 foreach ($guests as $key => $guest) {
11140
11141 if (intval($guest['reflectService']) === 1) {
11142
11143 $hasReflectService = true;
11144
11145 }
11146
11147 if ($guest['active'] === 'true') {
11148
11149 $countActives++;
11150
11151 }
11152
11153 }
11154
11155 if ($countActives === 0) {
11156
11157 $calendarAccount['guestsBool'] = 0;
11158
11159 }
11160
11161 }
11162
11163 #$costs = array(intval($service['cost_1']), intval($service['cost_2']), intval($service['cost_3']), intval($service['cost_4']), intval($service['cost_5']), intval($service['cost_6']));
11164 $costsWithKey = array('cost_1' => intval($service['cost_1']), 'cost_2' => intval($service['cost_2']), 'cost_3' => intval($service['cost_3']), 'cost_4' => intval($service['cost_4']), 'cost_5' => intval($service['cost_5']), 'cost_6' => intval($service['cost_6']));
11165 $response = array('hasReflectService' => $hasReflectService, 'hasMultipleCosts' => $hasMultipleCosts, 'max' => 0, 'min' => 0, 'costs' => array(), 'costsWithKey' => $costsWithKey, 'totalCost' => 0, 'guests' => null);
11166 $costs = array();
11167 if (intval($calendarAccount['guestsBool']) == 1 && is_array($guests)) {
11168
11169 foreach ($guests as $key => $guest) {
11170
11171 if (isset($guest['costInServices']) === false) {
11172
11173 $guest['costInServices'] = 'cost_1';
11174
11175 }
11176
11177 if ($isExtensionsValid !== true) {
11178
11179 $guest['costInServices'] = 'cost_1';
11180 $guest['reflectService'] = '0';
11181 $guest['reflectAdditional'] = '0';
11182
11183 }
11184
11185 $costInServices = $guest['costInServices'];
11186 if ($costsWithKey[$costInServices] != null) {
11187
11188 array_push($costs, $costsWithKey[$costInServices]);
11189
11190 }
11191
11192 $index = intval($guest['index']);
11193 $option = $guest['json'][$index];
11194 $number = intval($option['number']);
11195 $costKey = $guest['costInServices'];
11196
11197 if ($number > 0 && intval($costsWithKey[$costKey]) != 0 && intval($guest['reflectService']) == 1) {
11198
11199 #$hasReflectService = true;
11200 $guests[$key]['content'] = $guest['name'] . ': ' . $option['name'] . ' * ' . $this->formatCost($costsWithKey[$costKey], $currency);
11201 $totalCost1 += $costsWithKey[$costKey] * $number;
11202
11203 } else if ($number > 0 && intval($costsWithKey[$costKey]) != 0 && intval($guest['reflectService']) == 0) {
11204
11205 $guests[$key]['content'] = $guest['name'] . ': ' . /**$this->formatCost($costsWithKey[$costKey], $currency) . ' * ' .**/ $option['name'];
11206 if ($totalCost2 == 0) {
11207
11208 $totalCost2 = $costsWithKey['cost_1'];
11209
11210 }
11211
11212 }
11213
11214 }
11215
11216 if ($hasReflectService === true) {
11217
11218 $totalCost2 = 0;
11219
11220 }
11221
11222 if (count($costs) === 0) {
11223
11224 array_push($costs, $costsWithKey['cost_1']);
11225
11226 }
11227
11228 $response['costs'] = $costs;
11229 $response['totalCost'] = $totalCost1 + $totalCost2;
11230 $response['guests'] = $guests;
11231
11232 } else {
11233
11234 $costs = array($costsWithKey['cost_1']);
11235 $response['costs'] = $costs;
11236 $totalCost += $costsWithKey['cost_1'];
11237 $response['totalCost'] = $totalCost;
11238 $response['guests'] = $guests;
11239
11240 }
11241
11242 return $response;
11243
11244 }
11245
11246 public function getSelectedOptions($calendarAccount, $selectedOptions, $guests, $applicantCount = 1){
11247
11248 $time = 0;
11249 $cost = 0;
11250 $options = array();
11251 if (isset($selectedOptions)) {
11252
11253 $jsonList = $selectedOptions;
11254 if (is_string($selectedOptions) === true) {
11255
11256 #$jsonList = json_decode(str_replace("\\", "", $selectedOptions), true);
11257 $jsonList = json_decode(stripslashes($selectedOptions), true);
11258
11259 }
11260
11261 if (is_array($jsonList)) {
11262
11263 for ($i = 0; $i < count($jsonList); $i++) {
11264
11265 $object = array();
11266 foreach ((array) $jsonList[$i] as $key => $value) {
11267
11268 $object[sanitize_text_field($key)] = sanitize_text_field($value);
11269
11270 }
11271
11272 if (intval($object['selected']) == 1) {
11273
11274 $time += intval($object['time']);
11275 #$cost += intval($object['cost']) * $applicantCount;
11276 $responseCostInService = $this->getCostsInService($calendarAccount, $object, $guests);
11277 $cost += $responseCostInService['totalCost'];
11278
11279 }
11280
11281 array_push($options, $object);
11282
11283 }
11284
11285 }
11286
11287 }
11288
11289 return array("time" => $time, "cost" => $cost, "object" => $options);
11290
11291 }
11292
11293 public function get_user_id($administrator = false, $request_user_id = null) {
11294
11295 $user_id = null;
11296 $user_login = null;
11297 if ($administrator === false) {
11298
11299 $user = $this->get_user();
11300 if (intval($user['status']) == 1) {
11301
11302 $user = $user['user'];
11303 $user_id = intval($user['current_member_id']);
11304 $user_login = $user['user_login'];
11305
11306 }
11307
11308 } else if ($administrator === true && isset($request_user_id)) {
11309
11310 $user = $this->get_user(intval($request_user_id), false);
11311 $user = $user['user'];
11312 $user_id = intval($user['current_member_id']);
11313 $user_login = $user['user_login'];
11314
11315 }
11316
11317 return array('user_id' => $user_id, 'user_login' => $user_login);
11318
11319 }
11320
11321 public function insertPrivateData($sendDate, $permission, $status, $timeKey, $scheduleUnixTime, $scheduleTitle, $scheduleCost, $services, $form, $emails, $currency, $payType, $cardToken, $accountKey, $permalink, $preparation, $taxes, $guests, $coupon, $administrator, $applicantCount = 1){
11322
11323 global $wpdb;
11324
11325 $remainderTime = 0;
11326 $maintenanceTime = 0;
11327 $remainderBool = 'false';
11328 $cancellationToken = hash('ripemd160', $timeKey.$scheduleUnixTime.microtime(true));
11329 if(($sendDate + ($remainderTime * 60)) > $scheduleUnixTime){
11330
11331 $remainderBool = 'true';
11332
11333 }
11334
11335 $courseTitle = get_option($this->prefix . "courseName", "Services");
11336 $numberOfWeek = ceil(date('d', $scheduleUnixTime) / 7);
11337
11338 $payMode = "";
11339 $payId = "";
11340 $payName = "";
11341 if ($cardToken != null) {
11342
11343 $payMode = "CreditCard";
11344 if ($payType == 'stripe') {
11345
11346 $payId = "stripe";
11347 $payName = "Stripe";
11348
11349 } else if ($payType == 'paypal') {
11350
11351 $payId = "paypal";
11352 $payName = "PayPal";
11353
11354 }
11355
11356 }
11357
11358 $type = "day";
11359 $checkIn = 0;
11360 $checkOut = 0;
11361 $accommodationDetails = $this->getAccommodationDetails();
11362 if (!is_null($accommodationDetails)) {
11363
11364 $type = "hotel";
11365 $checkIn = $accommodationDetails['checkIn'];
11366 $checkOut = $accommodationDetails['checkOut'];
11367
11368 }
11369
11370 $response_user = $this->get_user_id($administrator, $_POST['userId']);
11371 $user_id = $response_user['user_id'];
11372 $user_login = $response_user['user_login'];
11373
11374 $couponKey = '';
11375 if (!empty($coupon) && is_array($coupon) && isset($coupon['key'])) {
11376
11377 $couponKey = $coupon['key'];
11378 $coupon = json_encode($coupon);
11379
11380 } else {
11381
11382 $coupon = '';
11383
11384 }
11385
11386 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11387 $valueArray = array(
11388 'reserveTime' => intval($sendDate),
11389 'remainderTime' => 0,
11390 'remainderBool' => $remainderBool,
11391 'maintenanceTime' => intval($maintenanceTime),
11392 'permission' => sanitize_text_field($permission),
11393 'type' => $type,
11394 'status' => sanitize_text_field($status),
11395 'accountKey' => intval($accountKey),
11396 'accountName' => '',
11397 'scheduleUnixTime' => intval($scheduleUnixTime),
11398 'scheduleWeek' => intval($numberOfWeek),
11399 'scheduleTitle' => sanitize_text_field($scheduleTitle),
11400 'scheduleKey' => intval($timeKey),
11401 'scheduleCost' => intval($scheduleCost),
11402 'applicantCount' => intval($applicantCount),
11403 'courseTitle' => sanitize_text_field($courseTitle),
11404 'currency' => sanitize_text_field($currency),
11405 'payMode' => $payMode,
11406 'payId' => $payId,
11407 'payName' => $payName,
11408 'payToken' => sanitize_text_field($cardToken),
11409 'praivateData' => sanitize_text_field( json_encode($form) ),
11410 'checkIn' => intval($checkIn),
11411 'checkOut' => intval($checkOut),
11412 'accommodationDetails' => sanitize_text_field( json_encode($accommodationDetails) ),
11413 'options' => sanitize_text_field( json_encode($services) ),
11414 'cancellationToken' => $cancellationToken,
11415 'permalink' => esc_url($permalink),
11416 'preparation' => sanitize_text_field( json_encode($preparation) ),
11417 'taxes' => sanitize_text_field( json_encode($taxes) ),
11418 'guests' => sanitize_text_field( json_encode($guests) ),
11419 'user_id' => $user_id,
11420 'user_login' => sanitize_text_field($user_login),
11421 'couponKey' => sanitize_text_field($couponKey),
11422 'coupon' => sanitize_text_field($coupon),
11423 'emails' => sanitize_text_field( json_encode($emails )),
11424 'locale' => sanitize_text_field( get_locale() ),
11425 );
11426
11427 $bool = $wpdb->insert(
11428 $table_name,
11429 $valueArray,
11430 array(
11431 '%d', '%d', '%s', '%d', '%s', '%s', '%s', '%d', '%s', '%d',
11432 '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s',
11433 '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s',
11434 '%s', '%d', '%s', '%s', '%s', '%s', '%s',
11435 )
11436 );
11437 #$ressponse['insert'] = $bool;
11438 $lastID = $wpdb->insert_id;
11439
11440 $user = $this->get_user();
11441 if (intval($user['status']) == 1) {
11442
11443 $user = $user['user'];
11444 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11445 $bool = $wpdb->update(
11446 $table_name,
11447 array(
11448 'user_id' => intval($user["current_member_id"]),
11449 'user_login' => sanitize_text_field($user["user_login"]),
11450 ),
11451 array('key' => intval($lastID)),
11452 array('%d', '%s'),
11453 array('%d')
11454 );
11455
11456 }
11457
11458 return array("lastID" => $lastID, "cancellationToken" => $cancellationToken, "cancellationUri" => "id=".$lastID."&token=".$cancellationToken);
11459 #return $lastID;
11460
11461 }
11462
11463 public function getBookingDetailsOnVisitor($key, $token) {
11464
11465 global $wpdb;
11466 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11467 $sql = "SELECT * FROM `" . $table_name . "` WHERE `key` = %d;";
11468 $sql = $wpdb->prepare(
11469 "SELECT * FROM `" . $table_name . "` WHERE `key` = %d AND `cancellationToken` = %s;",
11470 array(
11471 intval($key),
11472 sanitize_text_field( esc_html($token) )
11473 )
11474 );
11475 $row = $wpdb->get_row($sql, ARRAY_A);
11476 if (is_null($row) === false) {
11477
11478 $row['scheduleMonth'] = date('n', $row['scheduleUnixTime']);
11479 $row['scheduleDay'] = date('j', $row['scheduleUnixTime']);
11480 $row['scheduleYear'] = date('Y', $row['scheduleUnixTime']);
11481 $row['scheduleWeek'] = date('w', $row['scheduleUnixTime']);
11482 $row['scheduleHour'] = date('H', $row['scheduleUnixTime']);
11483 $row['scheduleMin'] = date('i', $row['scheduleUnixTime']);
11484 $accommodationDetails = json_decode($row['accommodationDetails'], true);
11485 if (isset($accommodationDetails['rooms']) === false) {
11486
11487 $accommodationDetails['rooms'] = null;
11488
11489 }
11490 if ($row['type'] == 'hotel' && is_null($accommodationDetails) === false && is_null($accommodationDetails['rooms'])) {
11491
11492 $accommodationDetails['applicantCount'] = 1;
11493 $accommodationDetails['rooms'] = $this->createRooms($accommodationDetails);
11494 $row['accommodationDetails'] = json_encode($accommodationDetails);
11495
11496 }
11497
11498 $row['accommodationDetailsList'] = $this->bookingDetailsForHotel($row['accountKey'], json_decode($row['accommodationDetails'], true), $row['currency'], 'object');
11499 $guests = $row['guests'];
11500 if (empty($guests) || is_null($guests)) {
11501
11502 $guests = array();
11503
11504 } else {
11505
11506 $guests = json_decode($guests, true);
11507
11508 }
11509 $row['guests'] = $guests;
11510
11511 return array("status" => "success", "details" => $row);
11512
11513 } else {
11514
11515 return array("status" => "error", "details" => null);
11516
11517 }
11518
11519 }
11520
11521 public function verifyCancellation($bookingDetails, $isExtensionsValid = false, $user = 0) {
11522
11523 $response = array("cancel" => false);
11524 $calendarAccount = $this->getCalendarAccount(intval($bookingDetails['accountKey']));
11525 if (intval($calendarAccount['cancellationOfBooking']) == 1) {
11526
11527 $unixTime = date('U');
11528 if ($isExtensionsValid === true) {
11529
11530 $current_cancellation_limit_time = intval($calendarAccount['allowCancellationVisitor']);
11531 $cancellation_limit_time = apply_filters( 'booking_package_override_cancellation_limit_time', $current_cancellation_limit_time, intval($calendarAccount['key']) );
11532 if ( !is_numeric($cancellation_limit_time) || $cancellation_limit_time <= 0 ) {
11533
11534 $cancellation_limit_time = $current_cancellation_limit_time;
11535
11536 } else {
11537
11538 $cancellation_limit_time = intval($cancellation_limit_time);
11539
11540 }
11541
11542 $unixTime = $unixTime + ($cancellation_limit_time * 60);
11543 #$unixTime = $unixTime + (intval($calendarAccount['allowCancellationVisitor']) * 60);
11544
11545 } else {
11546
11547 $calendarAccount['refuseCancellationOfBooking'] = 'not_refuse';
11548
11549 }
11550
11551 if ($unixTime < intval($bookingDetails['scheduleUnixTime'])) {
11552
11553 if ($calendarAccount['refuseCancellationOfBooking'] == 'not_refuse') {
11554
11555 $response['cancel'] = true;
11556
11557 } else if ($bookingDetails['status'] == $calendarAccount['refuseCancellationOfBooking']) {
11558
11559 $response['cancel'] = true;
11560
11561 }
11562
11563 }
11564
11565 }
11566
11567 return $response;
11568
11569 }
11570
11571 public function cancelBookingData($deleteKey, $token, $status) {
11572
11573 global $wpdb;
11574 $applicantCount = 1;
11575 $response = array("status" => "error", "key" => intval($deleteKey), "token" => esc_html($token), "cancel" => 0, "myBookingDetails" => array());
11576 $bookingDetailsOnVisitor = $this->getBookingDetailsOnVisitor($deleteKey, $token);
11577 $response = apply_filters('booking_package_update_status', $status, $bookingDetailsOnVisitor['details']);
11578 if (empty($response) === false && isset($response['status']) && $response['status'] == 'error') {
11579
11580 return array('status' => $response['status']);
11581
11582 }
11583 $response = array("status" => "error", "key" => intval($deleteKey), "token" => esc_html($token), "cancel" => 0, "myBookingDetails" => array());
11584 $myBookingDetails = $bookingDetailsOnVisitor['details'];
11585 $_POST['accountKey'] = $myBookingDetails['accountKey'];
11586 $verifyCancellation = $this->verifyCancellation($myBookingDetails, true, 0);
11587 if ($verifyCancellation['cancel'] === true) {
11588
11589 $this->updateStatus($deleteKey, $token, $status);
11590 $response['status'] = 'success';
11591 $_POST['sendEmail'] = 0;
11592
11593 }
11594
11595 $response['myBookingDetails'] = $myBookingDetails;
11596 #$response['accommodationDetails'] = $accommodationDetails;
11597 $response['cancel'] = $verifyCancellation['cancel'];
11598
11599 return $response;
11600
11601 }
11602
11603 public function deleteBookingData($deleteKey = false, $accountKey = 1, $sendGC = true, $deleteVisitorDetails = true, $sendEmail = 1){
11604
11605 global $wpdb;
11606 $accountCalendarKey = $accountKey;
11607 $refound = null;
11608 $options = array();
11609 $responseGuests = array();
11610 $calendarAccount = $this->getCalendarAccount($accountKey);
11611 if (intval($calendarAccount['schedulesSharing']) == 1) {
11612
11613 $accountCalendarKey = intval($calendarAccount['targetSchedules']);
11614
11615 }
11616
11617 $paymentMethod = explode(",", $calendarAccount['paymentMethod']);
11618 if ($deleteKey !== false) {
11619
11620 $unixTimeStart = 0;
11621 $accommodationDetails = array();
11622 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11623 $sql = "SELECT * FROM `" . $table_name . "` WHERE `key` = %d;";
11624 $sql = $wpdb->prepare("SELECT * FROM `".$table_name."` WHERE `key` = %d;", array(intval($deleteKey)));
11625 $row = $wpdb->get_row($sql, ARRAY_A);
11626 if (is_null($row) === false) {
11627
11628 $coupon = null;
11629 if (isset($row['coupon']) && !empty($row['coupon'])) {
11630
11631 $coupon = json_decode($row['coupon'], true);
11632
11633 }
11634
11635 $status = $row['status'];
11636 $unixTimeStart = $row['scheduleUnixTime'];
11637 $accountKey = $row['accountKey'];
11638 $table_name = $wpdb->prefix . "booking_package_schedules";
11639 $sql = null;
11640 $month = date('m', $row['scheduleUnixTime']);
11641 $year = date('Y', $row['scheduleUnixTime']);
11642 $scheduleKey = $row['scheduleKey'];
11643 $applicantCount = $row['applicantCount'];
11644 $payId = $row['payId'];
11645 $payToken = $row['payToken'];
11646 $options = json_decode($row['options'], true);
11647 $preparation = json_decode($row['preparation'], true);
11648 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
11649 $selectedOptionsObject = $this->getSelectedOptions($calendarAccount, $row['options'], $responseGuests['guests']);
11650 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $applicantCount, false);
11651 $services = $servicesDetails['object'];
11652
11653 if (empty($responseGuests) === true) {
11654
11655 $responseGuests = array();
11656
11657 }
11658
11659 if ($status != 'canceled') {
11660
11661 if ($calendarAccount['type'] == 'hotel') {
11662
11663 $accommodationDetails = json_decode($row['accommodationDetails'], true);
11664 $endKey = end($accommodationDetails['scheduleList']);
11665 $unixTimeStart = $row['scheduleUnixTime'];
11666 $unixTimeEnd = $accommodationDetails['lastUnixTime'];
11667 $timestampForUnixTime = $row['reserveTime'];
11668 $sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
11669 $valueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
11670 #$sql = $wpdb->prepare($account_sql, $valueArray);
11671
11672 } else {
11673
11674 $accommodationDetails['taxes'] = json_decode($row['taxes'], true);
11675 $startTime = $row['scheduleUnixTime'];
11676 $unixTimeStart = $row['scheduleUnixTime'];
11677 $timestampForUnixTime = $row['reserveTime'];
11678
11679 $hasMultipleServices = 0;
11680 #$responseGuests = json_decode($row['guests'], true);
11681 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
11682 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $applicantCount, false);
11683 $services = $servicesDetails['object'];
11684 if (is_array($services)) {
11685
11686 foreach ((array) $services as $service) {
11687
11688 if (isset($service['service']) && intval($service['service']) == 1) {
11689
11690 $hasMultipleServices = 1;
11691 break;
11692
11693 }
11694
11695 }
11696
11697 }
11698
11699 if ($hasMultipleServices == 1) {
11700
11701 $unixTimeEnd = $row['scheduleUnixTime'] + ($servicesDetails['time'] * 60) + ($row['maintenanceTime'] * 60);
11702 #return array("status" => "error", "servicesDetails" => $servicesDetails, "unixTimeEnd" => $unixTimeEnd);
11703
11704 } else {
11705
11706 $unixTimeEnd = $row['scheduleUnixTime'] + ($row['courseTime'] * 60) + ($row['maintenanceTime'] * 60) + ($selectedOptionsObject['time'] * 60);
11707
11708 }
11709
11710 $valueArray = array();
11711 if ($hasMultipleServices == 1) {
11712
11713 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
11714
11715 $unixTimeStart -= $preparation['time'] * 60;
11716
11717 }
11718
11719 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
11720
11721 $unixTimeEnd += $preparation['time'] * 60;
11722
11723 }
11724 $sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC;";
11725 $valueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
11726
11727 } else {
11728
11729 if (isset($preparation['time']) && intval(isset($preparation['time'])) > 0) {
11730
11731 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
11732
11733 $unixTimeStart = $startTime - ($preparation['time'] * 60);
11734
11735 }
11736
11737 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
11738
11739 $unixTimeEnd = $startTime + ($preparation['time'] * 60);
11740 /**
11741 if (array_key_exists('v', $preparation) === true && $preparation['v'] === 1) {
11742
11743 $unixTimeEnd = ( $startTime + ($preparation['time'] * 60) ) - 1;
11744
11745 }
11746 **/
11747
11748 }
11749 $sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` <= %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
11750 $valueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
11751
11752 } else {
11753
11754 $sql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `key` = %d AND `status` = 'open';";
11755 $valueArray = array(intval($accountCalendarKey), intval($row['scheduleKey']));
11756
11757 }
11758
11759 }
11760
11761 }
11762
11763 $souce = array(
11764 array("mode" => "reduce", "sql" => $sql, "values" => $valueArray),
11765 );
11766 $updateSchedule = $this->updateRemainderSeart($souce, $applicantCount);
11767 if (isset($updateSchedule['status']) && $updateSchedule['status'] == 'error') {
11768
11769 $updateSchedule['sql'] = $souce;
11770 return $updateSchedule;
11771
11772 }
11773
11774 $this->updateBookingCount('remove', $scheduleKey, intval($applicantCount));
11775
11776 }
11777
11778 if (isset($_POST['refound']) && intval($_POST['refound']) == 1) {
11779
11780 $payment_active = 0;
11781 $payment_mode = 0;
11782 $payment_live = 0;
11783 $stripe_public_key = null;
11784 $stripe_secret_key = null;
11785 if ($payId == 'stripe' || $payId == 'stripe_konbini' || $payId == 'stripe_paypay') {
11786
11787 #$payment_active = get_option($this->prefix."stripe_active", "0");
11788 $payment_active = 0;
11789 if (!is_bool(array_search(strtolower($payId), $paymentMethod))) {
11790
11791 $payment_active = 1;
11792
11793 }
11794
11795 $stripe_secret_key = get_option($this->prefix."stripe_secret_key", null);
11796
11797 } else if($payId == 'paypal') {
11798
11799 #$payment_active = get_option($this->prefix."paypal_active", "0");
11800 $payment_active = 0;
11801 if (!is_bool(array_search(strtolower($payId), $paymentMethod))) {
11802
11803 $payment_active = 1;
11804
11805 }
11806
11807 $payment_live = get_option($this->prefix."paypal_live", "0");
11808 $stripe_public_key = get_option($this->prefix."paypal_client_id", null);
11809 $stripe_secret_key = get_option($this->prefix."paypal_secret_key", null);
11810
11811 }
11812
11813
11814 if (intval($payment_active) == 1 && !is_null($stripe_secret_key)) {
11815
11816 $creditCard = new booking_package_CreditCard($this->pluginName, $this->prefix);
11817 $refound = $creditCard->cancel($payId, $stripe_public_key, $stripe_secret_key, $payment_live, $payToken);
11818 if (isset($refound['status']) && $refound['status'] == 'error') {
11819
11820 return $refound;
11821 die();
11822
11823 }
11824
11825 }
11826
11827 }
11828
11829 if (intval($sendEmail) == 1) {
11830
11831 $email = $this->createEmailMessage($accountKey, 'booking_deleted_notification', intval($deleteKey));
11832
11833 }
11834
11835 if ($deleteVisitorDetails === true) {
11836
11837 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11838 $wpdb->delete($table_name, array('key' => intval($deleteKey)), array('%d'));
11839
11840 }
11841
11842 $ressponse = $this->getReservationData($month, 1, $year);
11843 $ressponse['status'] = "success";
11844 $ressponse['refound'] = $refound;
11845 $ressponse['selectedOptions'] = $selectedOptionsObject;
11846 $ressponse['sql'] = $sql;
11847
11848 do_action('booking_package_deleted_customer', array('id' => intval($deleteKey)));
11849
11850 return $ressponse;
11851
11852 } else {
11853
11854 return array('error' => 'ERROR3', 'status' => 'error');
11855
11856 }
11857
11858 }
11859
11860 }
11861
11862 public function retryToSendToServer(){
11863
11864 global $wpdb;
11865 #$calendarAccountList = $this->getCalendarAccountListData();
11866 $setting = new booking_package_setting($this->prefix, $this->pluginName);
11867 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11868 $sql = $wpdb->prepare("SELECT * FROM `".$table_name."` WHERE `resultOfGoogleCalendar` = %d;", array(0));
11869 $rows = $wpdb->get_results($sql, ARRAY_A);
11870 if(is_null($rows) === false && count($rows) != 0){
11871
11872 for($row = 0; $row < count($rows); $row++){
11873
11874
11875 $form = json_decode($rows[$row]['praivateData'], true);
11876 $data = $rows[$row];
11877 $accountKey = $data['accountKey'];
11878 $key = $data['key'];
11879 $sql_start_unixTime = $data['scheduleUnixTime'];
11880 $sql_max_unixTime = $sql_start_unixTime + ($data['courseTime'] * 60) + ($data['maintenanceTime'] * 60);
11881 #var_dump($data);
11882 $iCalID = false;
11883 if(!is_null($data['iCalIDforGoogleCalendar']) && is_string($data['iCalIDforGoogleCalendar'])){
11884
11885 $iCalID = $data['iCalIDforGoogleCalendar'];
11886
11887 }
11888
11889 $calendarAccount = $this->getCalendarAccount($accountKey);
11890
11891 $googleCalendar = $setting->pushGC(
11892 $data['resultModeOfGoogleCalendar'],
11893 $accountKey,
11894 $calendarAccount['type'],
11895 $key,
11896 $calendarAccount['googleCalendarID'],
11897 $sql_start_unixTime,
11898 $sql_max_unixTime,
11899 $form,
11900 $iCalID
11901 );
11902
11903 $this->updateQueueForGC($key, $googleCalendar);
11904
11905 }
11906
11907 }
11908
11909 }
11910
11911 public function updateQueueForGC($key, $googleCalendar){
11912
11913 global $wpdb;
11914 if(isset($googleCalendar->responseStatus) && isset($googleCalendar->responseMode)){
11915
11916 $valueList = array(
11917 'resultOfGoogleCalendar' => intval($googleCalendar->responseStatus),
11918 'resultModeOfGoogleCalendar' => sanitize_text_field($googleCalendar->responseMode)
11919 );
11920 $formatList = array('%s', '%s');
11921 if(isset($googleCalendar->id)){
11922
11923 $valueList['iCalIDforGoogleCalendar'] = sanitize_text_field($googleCalendar->id);
11924 array_push($formatList, '%s');
11925
11926 }
11927
11928 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11929 $bool = $wpdb->update(
11930 $table_name,
11931 /**array('iCalIDforGoogleCalendar' => sanitize_text_field($googleCalendar->id)),**/
11932 $valueList,
11933 array('key' => intval($key)),
11934 $formatList,
11935 array('%d')
11936 );
11937
11938 }
11939
11940 }
11941
11942 public function updateBooking($administrator) {
11943
11944 $accountKey = 1;
11945 $accountCalendarKey = 1;
11946 if (isset($_POST['accountKey'])) {
11947
11948 $accountKey = $_POST['accountKey'];
11949 $accountCalendarKey = $_POST['accountKey'];
11950
11951 }
11952
11953 global $wpdb;
11954 $calendarAccount = $this->getCalendarAccount($accountKey);
11955 if (intval($calendarAccount['schedulesSharing']) == 1) {
11956
11957 $accountCalendarKey = intval($calendarAccount['targetSchedules']);
11958
11959 }
11960
11961 $oldScheduleKey = null;
11962 $newScheduleKey = null;
11963 $bookingID = intval($_POST['updateKey']);
11964 $response_user = array();
11965 $selectedOptions = array();
11966 $resultArray = array();
11967 $unixTimeStart = 0;
11968 $unixTimeEnd = 0;
11969 $maintenanceTime = 0;
11970 $bookingYMD = null;
11971 $taxes = array();
11972 $souce = null;
11973 $servicesDetails1 = null;
11974 $servicesDetails2 = null;
11975 $deleteValueArray = array();
11976 $updateValueArray = array();
11977 $updateSchedule = array();
11978 $table_name = $wpdb->prefix . "booking_package_booked_customers";
11979 $sql = $wpdb->prepare("SELECT * FROM `" . $table_name . "` WHERE `key` = %d;", array(intval($_POST['updateKey'])));
11980 $row = $wpdb->get_row($sql, ARRAY_A);
11981 if (is_null($row) === false) {
11982
11983 $user_id = null;
11984 if (is_null($row['user_id']) === false) {
11985
11986 $response_user = $this->get_user_id($administrator, $row['user_id']);
11987 $user_id = $response_user['user_id'];
11988
11989 }
11990
11991 $coupon = null;
11992 if (isset($row['coupon']) && !empty($row['coupon'])) {
11993
11994 $coupon = json_decode($row['coupon'], true);
11995
11996 }
11997
11998 $bookingYMD = date('Y', $row['scheduleUnixTime']) . date('m', $row['scheduleUnixTime']) . date('d', $row['scheduleUnixTime']);
11999 $userValues = $this->getUserValues($accountKey, 'update', $administrator, $row['praivateData'], $user_id);
12000 if (isset($userValues['status']) && $userValues['status'] == 'error') {
12001
12002 return $userValues;
12003
12004 }
12005 $form = $userValues['form'];
12006 $emails = $userValues['emails'];
12007
12008 if ($calendarAccount['type'] != 'hotel') {
12009
12010 $row = $this->updateVistorService($row);
12011
12012 }
12013
12014 $status = $row['status'];
12015 $applicantCount = $row['applicantCount'];
12016 $preparation = json_decode($row['preparation'], true);
12017 $taxes = json_decode($row['taxes'], true);
12018 $iCalIDforGoogleCalendar = $row['iCalIDforGoogleCalendar'];
12019 $startTime = $row['scheduleUnixTime'];
12020 $unixTimeStart = $row['scheduleUnixTime'];
12021
12022 #$responseGuests = json_decode($row['guests'], true);
12023 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
12024 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $applicantCount, false);
12025 $services = $servicesDetails['object'];
12026 $unixTimeEnd = $row['scheduleUnixTime'] + ($servicesDetails['time'] * 60) + ($row['maintenanceTime'] * 60);
12027
12028 if ($calendarAccount['type'] == 'hotel') {
12029
12030 $accountCalendarKey = $calendarAccount['key'];
12031 if (intval($calendarAccount['schedulesSharing']) == 1) {
12032
12033 $accountCalendarKey = intval($calendarAccount['targetSchedules']);
12034
12035 }
12036
12037 $accommodationDetails = json_decode($row['accommodationDetails'], true);
12038 $accommodationDetails = $this->createAccommodationDetails($calendarAccount['key'], $accountCalendarKey, $_POST['json'], $unixTimeStart, $applicantCount, 'update', $accommodationDetails);
12039 if (isset($accommodationDetails['status']) === true && $accommodationDetails['status'] == "error") {
12040
12041 return $accommodationDetails;
12042
12043 } else {
12044
12045 /**
12046 $account_sql = $accommodationDetails['sql'];
12047 $valueArray = $accommodationDetails['valueArray'];
12048 $unixTimeEnd = $accommodationDetails['sql_max_unixTime'];
12049 unset($accommodationDetails['sql']);
12050 unset($accommodationDetails['valueArray']);
12051 unset($accommodationDetails['sql_max_unixTime']);
12052 **/
12053
12054 $unsetKeys = array('sql', 'valueArray', 'sql_max_unixTime');
12055 for ($i = 0; $i < count($unsetKeys); $i++) {
12056
12057 if (array_key_exists($unsetKeys[$i], $accommodationDetails) === true) {
12058
12059 unset($accommodationDetails[$unsetKeys[$i]]);
12060
12061 }
12062
12063 }
12064
12065 $this->setAccommodationDetails($accommodationDetails);
12066
12067 }
12068
12069 }
12070
12071 if (isset($_POST['update_booking_date']) || isset($_POST['update_booking_course'])) {
12072
12073 define("COURSE_KEY", $row['courseKey']);
12074
12075 $table_name = $wpdb->prefix . "booking_package_schedules";
12076
12077 $scheduleKey = $row['scheduleKey'];
12078 $oldScheduleKey = $row['scheduleKey'];
12079 $scheduleUnixTime = $row['scheduleUnixTime'];
12080 $scheduleTitle = $row['scheduleTitle'];
12081 $scheduleCost = $row['scheduleCost'];
12082 $scheduleWeek = $row['scheduleWeek'];
12083 $bookingReminder = intval($row['bookingReminder']);
12084
12085 $courseKey = $row['courseKey'];
12086 $courseName = $row['courseName'];
12087 $courseTime = $row['courseTime'];
12088 $courseCost = $row['courseCost'];
12089 #$responseGuests = json_decode($row['guests'], true);
12090 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
12091 $servicesDetails1 = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $applicantCount, false);
12092 $services = $servicesDetails1['object'];
12093 $courseTime = $servicesDetails1['time'];
12094 $deleteSql = null;
12095 $deleteValueArray = array();
12096 $updateSql = null;
12097 $updateValueArray = array();
12098
12099 if ($calendarAccount['type'] == 'hotel') {
12100
12101
12102
12103 } else {
12104
12105 $unixTimeStart = $scheduleUnixTime;
12106 $unixTimeEnd = intval($scheduleUnixTime + ($courseTime * 60) + ($row['maintenanceTime'] * 60));
12107 $servicesDetails1['unixTimeEnd'] = $unixTimeEnd;
12108 $deleteValueArray = array();
12109 if (count($services) > 0) {
12110
12111 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
12112
12113 $unixTimeStart -= $preparation['time'] * 60;
12114
12115 }
12116
12117 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
12118
12119 $unixTimeEnd += $preparation['time'] * 60;
12120
12121 }
12122
12123 $deleteSql = "SELECT * FROM `" . $table_name . "` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC;";
12124 $deleteValueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
12125
12126 } else {
12127
12128 if (isset($preparation['time']) && intval(isset($preparation['time'])) > 0) {
12129
12130 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
12131
12132 $unixTimeStart = $startTime - ($preparation['time'] * 60);
12133
12134 }
12135
12136 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
12137
12138 $unixTimeEnd = $startTime + ($preparation['time'] * 60);
12139 /**
12140 if (array_key_exists('v', $preparation) === true && $preparation['v'] === 1) {
12141
12142 $unixTimeEnd = ( $startTime + ($preparation['time'] * 60) ) - 1;
12143
12144 }
12145 **/
12146
12147 }
12148
12149 $deleteSql = "SELECT * FROM `" . $table_name . "` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` <= %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
12150 $deleteValueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
12151
12152 } else {
12153
12154 $deleteSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `key` = %d AND `status` = 'open';";
12155 $deleteValueArray = array(intval($accountCalendarKey), intval($scheduleKey));
12156
12157 }
12158
12159 }
12160
12161 if (isset($_POST['update_booking_date'])) {
12162
12163 $bookingReminder = 0;
12164 $table_name = $wpdb->prefix . "booking_package_schedules";
12165 $sql = $wpdb->prepare(
12166 "SELECT * FROM `".$table_name."` WHERE `key` = %d AND `status` = 'open';",
12167 array(intval($_POST['update_booking_date']))
12168 );
12169 $rowSchedule = $wpdb->get_row($sql, ARRAY_A);
12170 if (is_null($rowSchedule)) {
12171
12172 return array('status' => 'error', 'error' => '9016');
12173
12174 } else {
12175
12176 $scheduleKey = $rowSchedule['key'];
12177 $newScheduleKey = $rowSchedule['key'];
12178 $scheduleUnixTime = $rowSchedule['unixTime'];
12179 $scheduleTitle = $rowSchedule['title'];
12180 $scheduleCost = $rowSchedule['cost'];
12181 $scheduleWeek = $rowSchedule['weekKey'];
12182
12183 }
12184
12185 }
12186
12187 $servicesDetails2 = $this->getSelectedServices($calendarAccount, $_POST['options'], $responseGuests['guests'], "options", $coupon, $applicantCount, false);
12188 $selectedServices = $servicesDetails2['object'];
12189 $courseTime = $servicesDetails2['time'];
12190 $totalCost = intval($servicesDetails2['cost']);
12191 if (intval($calendarAccount['courseBool']) === 1 && count($servicesDetails2['object']) === 0) {
12192
12193 $selectedServices = $servicesDetails1['object'];
12194 $courseTime = $servicesDetails1['time'];
12195 $totalCost = intval($servicesDetails1['cost']);
12196 }
12197
12198 $totalCost += $this->getSelectedGuestTotalAmount($calendarAccount, $responseGuests['guests'], true);
12199 $taxes = $this->createTaxesDetails($accountKey, 'day', $totalCost, $bookingYMD, $applicantCount, null);
12200 for ($i = 0; $i < count($taxes); $i++) {
12201
12202 $tax = $taxes[$i];
12203 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_exclusive') {
12204
12205 $totalCost += $tax['taxValue'];
12206
12207 } else if ($tax['type'] == 'surcharge') {
12208
12209 $totalCost += $tax['taxValue'] * $applicantCount;
12210
12211 }
12212
12213 }
12214
12215
12216 foreach ((array) $selectedServices as $service) {
12217
12218 $rowCourse = $this->serachCourse($accountKey, $scheduleKey, $service['key'], $servicesDetails2, $bookingYMD, false, $bookingID);
12219 if (isset($rowCourse['status']) && $rowCourse['status'] == 'error') {
12220
12221 return array('status' => 'error', 'error' => '9020', 'servicesDetails2' => $servicesDetails2, 'rowCourse' => $rowCourse, 'accountKey' => $accountKey, 'message' => $rowCourse['message']);
12222
12223 }
12224
12225 }
12226
12227 $preparation = array("time" => intval($calendarAccount["preparationTime"]), "position" => $calendarAccount["positionPreparationTime"], 'v' => 1);
12228 $startTime = $scheduleUnixTime;
12229 $unixTimeStart = $scheduleUnixTime;
12230 $unixTimeEnd = intval($scheduleUnixTime + ($courseTime * 60) + ($row['maintenanceTime'] * 60));
12231 $servicesDetails2['unixTimeEnd'] = $unixTimeEnd;
12232
12233 #return array("status" => "error", "servicesDetails" => $servicesDetails2, "unixTimeEnd" => $unixTimeEnd);
12234
12235 $updateValueArray = array();
12236 if (count($selectedServices) > 0) {
12237
12238 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
12239
12240 $unixTimeStart -= $preparation['time'] * 60;
12241
12242 }
12243
12244 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
12245
12246 $unixTimeEnd += $preparation['time'] * 60;
12247
12248 }
12249
12250 $updateSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC;";
12251 $updateValueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
12252
12253 } else {
12254
12255 if (isset($preparation['time']) && intval(isset($preparation['time'])) > 0) {
12256
12257 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'before') {
12258
12259 $unixTimeStart = $startTime - ($preparation['time'] * 60);
12260
12261 }
12262
12263 if (isset($preparation['position']) && $preparation['position'] == 'before_after' || $preparation['position'] == 'after') {
12264
12265 $unixTimeEnd = $startTime + ($preparation['time'] * 60);
12266 /**
12267 if (array_key_exists('v', $preparation) === true && $preparation['v'] === 1) {
12268
12269 $unixTimeEnd = ( $startTime + ($preparation['time'] * 60) ) - 1;
12270
12271 }
12272 **/
12273
12274 }
12275
12276 $updateSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` <= %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
12277 $updateValueArray = array(intval($accountCalendarKey), intval($unixTimeStart), intval($unixTimeEnd));
12278
12279 } else {
12280
12281 $updateSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `key` = %d AND `status` = 'open';";
12282 $updateValueArray = array(intval($accountCalendarKey), intval($scheduleKey));
12283
12284 }
12285
12286 }
12287
12288 }
12289
12290 $souce = array(
12291 array("mode" => "reduce", "sql" => $deleteSql, "values" => $deleteValueArray),
12292 array("mode" => "increase", "sql" => $updateSql, "values" => $updateValueArray),
12293 );
12294
12295 $updateSchedule = $this->updateRemainderSeart($souce, $applicantCount);
12296 if ($status != 'canceled' && isset($updateSchedule['status']) && $updateSchedule['status'] == 'error') {
12297
12298 return $updateSchedule;
12299
12300 }
12301
12302 if (is_null($oldScheduleKey) === false && is_null($newScheduleKey) === false) {
12303
12304 $this->updateBookingCount('remove', intval($oldScheduleKey), intval($applicantCount));
12305 $this->updateBookingCount('add', intval($newScheduleKey), intval($applicantCount));
12306
12307 }
12308
12309 try {
12310
12311 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12312 $wpdb->query("START TRANSACTION");
12313 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_booked_customers" . "` WRITE");
12314
12315 $bool = $wpdb->update(
12316 $table_name,
12317 array(
12318 'scheduleKey' => intval($scheduleKey),
12319 'scheduleUnixTime' => intval($scheduleUnixTime),
12320 'scheduleTitle' => sanitize_text_field($scheduleTitle),
12321 'scheduleCost' => intval($scheduleCost),
12322 'scheduleWeek' => intval($scheduleWeek),
12323 'courseKey' => sanitize_text_field(""),
12324 'courseName' => sanitize_text_field(""),
12325 'courseTime' => intval(""),
12326 'courseCost' => intval(""),
12327 'options' => sanitize_text_field( json_encode($selectedServices) ),
12328 'preparation' => sanitize_text_field( json_encode($preparation) ),
12329 'emails' => sanitize_text_field( json_encode($emails) ),
12330 'taxes' => sanitize_text_field( json_encode($taxes) ),
12331 'bookingReminder' => intval($bookingReminder),
12332 ),
12333 array('key' => intval($_POST['updateKey'])),
12334 array(
12335 '%d', '%d', '%s', '%d', '%d', '%s', '%s', '%d', '%d', '%s',
12336 '%s', '%s', '%s', '%d',
12337 ),
12338 array('%d')
12339 );
12340
12341 $wpdb->query('COMMIT');
12342 $wpdb->query('UNLOCK TABLES');
12343
12344 } catch (Exception $e) {
12345
12346 $wpdb->query('ROLLBACK');
12347 $wpdb->query('UNLOCK TABLES');
12348 $error = json_decode($e->getMessage(), true);
12349 return $error;
12350
12351 }
12352 /** finally {
12353
12354 $wpdb->query('UNLOCK TABLES');
12355
12356 }
12357 **/
12358
12359 }
12360
12361
12362 $checkIn = 0;
12363 $checkOut = 0;
12364 $accommodationDetails = $this->getAccommodationDetails();
12365 if(!is_null($accommodationDetails)){
12366
12367 $checkIn = $accommodationDetails['checkIn'];
12368 $checkOut = $accommodationDetails['checkOut'];
12369
12370 }
12371
12372 try {
12373
12374 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12375 $wpdb->query("START TRANSACTION");
12376 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_booked_customers" . "` WRITE");
12377
12378 $bool = $wpdb->update(
12379 $table_name,
12380 array(
12381 'praivateData' => sanitize_text_field( json_encode($form) ),
12382 'accommodationDetails' => sanitize_text_field( json_encode($accommodationDetails) ),
12383 'checkIn' => intval($checkIn),
12384 'checkOut' => intval($checkOut)
12385 ),
12386 array('key' => intval($_POST['updateKey'])),
12387 array('%s', '%s', '%d', '%d'),
12388 array('%d')
12389 );
12390
12391 $wpdb->query('COMMIT');
12392 $wpdb->query('UNLOCK TABLES');
12393
12394 } catch (Exception $e) {
12395
12396 $wpdb->query('ROLLBACK');
12397 $wpdb->query('UNLOCK TABLES');
12398 $error = json_decode($e->getMessage(), true);
12399 return $error;
12400
12401 }
12402 /** finally {
12403
12404 $wpdb->query('UNLOCK TABLES');
12405
12406 }
12407 **/
12408
12409 }
12410
12411 $sendEmail = 0;
12412 if (isset($_POST['sendEmail']) === true) {
12413
12414 $sendEmail = intval($_POST['sendEmail']);
12415
12416 }
12417
12418 if ($sendEmail === 1) {
12419
12420 $email = $this->createEmailMessage($accountKey, 'booking_updated_notification', intval($_POST['updateKey']));
12421
12422 }
12423
12424 $ressponse = $this->getReservationData(intval($_POST['month']), 1, intval($_POST['year']));
12425 $ressponse['status'] = "success";
12426 $ressponse['souce'] = $souce;
12427 $ressponse['accommodationDetails'] = $accommodationDetails;
12428 $ressponse['servicesDetails1'] = $servicesDetails1;
12429 $ressponse['servicesDetails2'] = $servicesDetails2;
12430 $ressponse['deleteValueArray'] = $deleteValueArray;
12431 $ressponse['updateValueArray'] = $updateValueArray;
12432 $ressponse['resultArray'] = $resultArray;
12433 $ressponse['updateSchedule'] = $updateSchedule;
12434 $ressponse['response_user'] = $response_user;
12435 return $ressponse;
12436
12437 }
12438
12439 public function serachGoogleCalendarIdOfVisitor($googleCalendarId = false){
12440
12441 global $wpdb;
12442 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12443 if ($googleCalendarId != false) {
12444
12445 $sql = $wpdb->prepare(
12446 "SELECT `key`,`iCalIDforGoogleCalendar`,`resultOfGoogleCalendar`,`resultModeOfGoogleCalendar` FROM ".$table_name." WHERE `iCalIDforGoogleCalendar` = %s;",
12447 array(sanitize_text_field($googleCalendarId))
12448 );
12449 $row = $wpdb->get_row($sql, ARRAY_A);
12450
12451 return $row;
12452
12453 }
12454
12455 return false;
12456
12457 }
12458
12459 public function updateICalIDforGoogleCalendar($id, $iCalIDforGoogleCalendar){
12460
12461 global $wpdb;
12462 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12463 $bool = $wpdb->update(
12464 $table_name,
12465 array(
12466 'iCalIDforGoogleCalendar' => sanitize_text_field($iCalIDforGoogleCalendar),
12467 'resultOfGoogleCalendar' => 1
12468 ),
12469 array('key' => intval($id)),
12470 array('%s', '%d'),
12471 array('%d')
12472 );
12473
12474 }
12475
12476 public function updateStatus($bookedKey, $bookedToken, $status = 'pending'){
12477
12478 global $wpdb;
12479
12480 $sendEmail = $_POST['sendEmail'];
12481 $status = strtolower($status);
12482 $bookingDetailsOnVisitor = $this->getBookingDetailsOnVisitor($bookedKey, $bookedToken);
12483
12484 $response = apply_filters('booking_package_update_status', $status, $bookingDetailsOnVisitor['details']);
12485 if (empty($response) === false && isset($response['status']) && $response['status'] == 'error') {
12486
12487 return array('status' => $response['status']);
12488
12489 }
12490
12491 if ($bookingDetailsOnVisitor['status'] == 'error') {
12492
12493 return $bookingDetailsOnVisitor;
12494
12495 }
12496 $myBookingDetails = $bookingDetailsOnVisitor['details'];
12497 if ($status == 'canceled') {
12498
12499 $_POST['sendEmail'] = 0;
12500 $this->deleteBookingData($bookedKey, $myBookingDetails['accountKey'], false, false, 0);
12501
12502 }
12503
12504 $options = array();
12505 $responseGuests = array();
12506 $row = $this->getCustomer($bookedKey, null);
12507 if (is_null($row) === false) {
12508
12509 $applicantCount = $row['applicantCount'];
12510 $accountKey = $row['accountKey'];
12511 $calendarAccount = $this->getCalendarAccount($accountKey);
12512
12513 $coupon = null;
12514 if (isset($row['coupon']) && !empty($row['coupon'])) {
12515
12516 $coupon = json_decode($row['coupon'], true);
12517
12518 }
12519
12520 $options = json_decode($row['options'], true);
12521 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
12522 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $applicantCount, false);
12523 $services = $servicesDetails['object'];
12524
12525 if (empty($responseGuests) === true) {
12526
12527 $responseGuests = array();
12528
12529 }
12530
12531 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12532 $bool = $wpdb->update(
12533 $table_name,
12534 array('status' => sanitize_text_field($status)),
12535 array('key' => intval($bookedKey)),
12536 array('%s'),
12537 array('%d')
12538 );
12539
12540 }
12541
12542 $email_id = null;
12543 if ($status == "pending") {
12544
12545 $email_id = 'booking_pending_notification';
12546
12547 } else if ($status == "approved") {
12548
12549 $email_id = 'booking_approved_notification';
12550
12551 } else if ($status == "canceled") {
12552
12553 $email_id = 'booking_cancellation_notification';
12554
12555 }
12556
12557 if (intval($sendEmail) == 1) {
12558
12559 $email = $this->createEmailMessage($accountKey, $email_id, intval($bookedKey));
12560
12561 }
12562
12563 $ressponse = array();
12564 if (isset($_POST['reload']) && intval($_POST['reload']) == 1) {
12565
12566 $ressponse = $this->getReservationData(intval($_POST['month']), 1, intval($_POST['year']));
12567
12568 }
12569
12570 $ressponse['status'] = "success";
12571 $ressponse['services'] = $services;
12572 $ressponse['status'] = $status;
12573 $ressponse['sendEmail'] = $sendEmail;
12574
12575 do_action('booking_package_changed_status', array('id' => intval($bookedKey), 'status' => $status));
12576
12577 return $ressponse;
12578
12579 }
12580
12581 public function changeBookingTime($mode, $updateKey, $updateScheduleKey, $status, $applicantCount, $newTimeStart, $newTimeEnd, $oldTimeStart, $oldTimeEnd, $accommodationDetails, $accountKey = 1){
12582
12583 #var_dump($mode);
12584 global $wpdb;
12585 $accountCalendarKey = $accountKey;
12586 $calendarAccount = $this->getCalendarAccount($accountKey);
12587 if (intval($calendarAccount['schedulesSharing']) == 1) {
12588
12589 $accountCalendarKey = intval($calendarAccount['targetSchedules']);
12590
12591 }
12592 $checkIn = 0;
12593 $checkOut = 0;
12594 $changeBool = true;
12595 $scheduleDetail = null;
12596 $table_name = $wpdb->prefix . "booking_package_schedules";
12597 $updateSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
12598 $updateValue = array(intval($accountCalendarKey), intval($newTimeStart), intval($newTimeEnd));
12599 if($newTimeStart == $newTimeEnd){
12600
12601 $updateSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `unixTime` = %d AND `status` = 'open';";
12602 $updateValue = array(intval($accountCalendarKey), intval($newTimeStart));
12603
12604 }
12605
12606 if(isset($accommodationDetails['sql']) && isset($accommodationDetails['valueArray'])){
12607
12608 $updateSql = $accommodationDetails['sql'];
12609 $updateValue = $accommodationDetails['valueArray'];
12610
12611 }
12612
12613 $sql = $wpdb->prepare($updateSql, $updateValue);
12614 #var_dump($sql);
12615 $rows = $wpdb->get_results($sql, ARRAY_A);
12616
12617 if (count($rows) == 0 || $rows[0]['unixTime'] != $newTimeStart) {
12618
12619 return array('status' => 'error', 'event' => 'return', 'message' => 'There is no booking schedule.');
12620
12621 }
12622
12623
12624 foreach ((array) $rows as $row) {
12625
12626 if (!is_null($oldTimeStart) && !is_null($oldTimeEnd)) {
12627
12628 if ($oldTimeStart != $oldTimeEnd) {
12629
12630 if($oldTimeStart <= $row['unixTime'] && $oldTimeEnd > $row['unixTime']){
12631
12632 $row['remainder'] += $applicantCount;
12633
12634 }
12635
12636 } else {
12637
12638 if ($oldTimeStart == $row['unixTime']) {
12639
12640 $row['remainder'] += $applicantCount;
12641
12642 }
12643
12644 }
12645
12646 }
12647
12648 $row['remainder'] -= $applicantCount;
12649 #print "key = ".$row['key']." unixTime = ".$row['unixTime']." time = ".$row['hour'].":".$row['min']." capacity = ".$row['capacity']." remainder = ".$row['remainder']."<br>";
12650 if($row['remainder'] < 0 || $row['stop'] == 'true'){
12651
12652 $changeBool = false;
12653 return array('status' => 'error', 'event' => 'return', 'message' => 'The remaining slots in the schedules have an issue.', 'rows' => $rows);
12654 break;
12655
12656 }else{
12657
12658 if(is_null($scheduleDetail)){
12659
12660 $scheduleDetail = $row;
12661
12662 }
12663
12664 }
12665
12666 }
12667
12668
12669
12670 if($changeBool === true){
12671
12672 $newCourseTime = ($newTimeEnd - $newTimeStart) / 60;
12673 $oldCourseTime = ($oldTimeEnd - $oldTimeStart) / 60;
12674 #print "courseTime = ".$newCourseTime."<br>";
12675 #var_dump($scheduleDetail);
12676
12677 if ($mode == 'update') {
12678
12679 $checkIn = 0;
12680 $checkOut = 0;
12681 $deleteSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` < %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
12682 $deleteValue = array(intval($accountCalendarKey), intval($oldTimeStart), intval($oldTimeEnd));
12683 if ($oldTimeStart == $oldTimeEnd) {
12684
12685 $deleteSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND `key` = %d AND `status` = 'open';";
12686 $deleteValue = array(intval($accountCalendarKey), intval($updateScheduleKey));
12687
12688 }
12689
12690 if (isset($accommodationDetails['sql']) && isset($accommodationDetails['valueArray'])) {
12691
12692 $checkIn = $accommodationDetails['checkIn'];
12693 $checkOut = $accommodationDetails['checkOut'];
12694 $deleteSql = "SELECT * FROM `".$table_name."` WHERE `accountKey` = %d AND (`unixTime` >= %d AND `unixTime` <= %d) AND `status` = 'open' ORDER BY `unixTime` ASC ;";
12695 $deleteValue = array(intval($accountCalendarKey), intval($oldTimeStart), intval($oldTimeEnd));
12696 unset($accommodationDetails['sql']);
12697 unset($accommodationDetails['valueArray']);
12698
12699 }
12700
12701 $souce = array(
12702 array("mode" => "delete", "sql" => $deleteSql, "values" => $deleteValue),
12703 array("mode" => "increase", "sql" => $updateSql, "values" => $updateValue),
12704 );
12705 $this->updateRemainderSeart($souce, $applicantCount);
12706
12707 $updateValue = array(
12708 'scheduleUnixTime' => intval($scheduleDetail['unixTime']),
12709 'scheduleWeek' => intval($scheduleDetail['weekKey']),
12710 'scheduleTitle' => $scheduleDetail['title'],
12711 'scheduleCost' => intval($scheduleDetail['cost']),
12712 'scheduleKey' => intval($scheduleDetail['key']),
12713 'checkIn' => intval($checkIn),
12714 'checkOut' => intval($checkOut),
12715 'accommodationDetails' => sanitize_text_field( json_encode($accommodationDetails) )
12716 );
12717
12718 if ($newCourseTime != $oldCourseTime) {
12719
12720 $updateValue['courseKey'] = "exception";
12721 $updateValue['courseName'] = $newCourseTime." min";
12722 $updateValue['courseTime'] = intval($newCourseTime);
12723
12724 }
12725
12726 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12727 $bool = $wpdb->update(
12728 $table_name,
12729 $updateValue,
12730 array('key' => intval($updateKey)),
12731 array('%d', '%d', '%s', '%d', '%d', '%d', '%d', '%s', '%s', '%s', '%d'),
12732 array('%d')
12733 );
12734
12735 } else {
12736
12737 return $changeBool;
12738
12739 }
12740
12741 }
12742
12743 }
12744
12745 public function updatePraivateData($id, $form){
12746
12747 global $wpdb;
12748 $form = sanitize_text_field( json_encode($form) );
12749 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12750 $bool = $wpdb->update(
12751 $table_name,
12752 array(
12753 'praivateData' => $form
12754 ),
12755 array('key' => intval($id)),
12756 array('%s'),
12757 array('%d')
12758 );
12759
12760 }
12761
12762 public function updateRemainderSeart($souce, $applicantCount = 1){
12763 #var_dump($souce);
12764 global $wpdb;
12765 $updateSchedule = array();
12766 $rollbackQueries = array();
12767 $updateList = array();
12768 $error = array();
12769 try {
12770
12771 $wpdb->query("START TRANSACTION");
12772 $wpdb->query("LOCK TABLES `" . $wpdb->prefix . "booking_package_schedules" . "` WRITE");
12773 for ($i = 0; $i < count($souce); $i++) {
12774
12775 $mode = $souce[$i]['mode'];
12776 $sql = $souce[$i]['sql'];
12777 $valueArray = $souce[$i]['values'];
12778
12779 if ($mode == "increase") {
12780
12781 $sql = $wpdb->prepare($sql, $valueArray);
12782 $rows = $wpdb->get_results($sql, ARRAY_A);
12783 $updateArray = array();
12784 foreach ((array) $rows as $row) {
12785
12786 $waitingRemainder = 0;
12787 $remainder = intval($row['remainder']) - $applicantCount;
12788 if ($row['stop'] == 'false' && $remainder >= 0) {
12789
12790 if (0 < $row['waitingRemainder']) {
12791
12792 $waitingRemainder = $row['waitingRemainder'] - $applicantCount;
12793
12794 }
12795
12796 array_push($updateArray, array('remainder' => intval($remainder), 'waitingRemainder' => intval($waitingRemainder), 'key' => intval($row['key'])));
12797
12798 } else {
12799
12800 for ($backKey = 0; $backKey < count($rollbackQueries); $backKey++) {
12801
12802 $wpdb->query($rollbackQueries[$backKey]);
12803
12804 }
12805
12806 $error = array('status' => 'error', 'error' => '9503', 'mode' => $mode, 'sql' => $sql, 'message' => __('The remaining slots in the schedules have an issue.', 'booking-package'));
12807 throw new Exception(json_encode($error));
12808 #break;
12809
12810 }
12811
12812 }
12813
12814 $table_name = $wpdb->prefix . "booking_package_schedules";
12815 for ($a = 0; $a < count($updateArray); $a++) {
12816
12817 $data = $updateArray[$a];
12818 $updateSql = $wpdb->prepare(
12819 'UPDATE `' . $table_name . '` SET `remainder` = %d, `waitingRemainder` = %d WHERE `key` = %d AND `status` = %s;',
12820 array(intval($data['remainder']), intval($data['waitingRemainder']), intval($data['key']), 'open')
12821 );
12822 $bool = $wpdb->query($updateSql);
12823 array_push($updateSchedule, $bool);
12824
12825 }
12826
12827 } else {
12828
12829 $table_name = $wpdb->prefix . "booking_package_schedules";
12830 $sql = $wpdb->prepare($sql, $valueArray);
12831 $rows = $wpdb->get_results($sql, ARRAY_A);
12832 foreach ((array) $rows as $row) {
12833
12834 $remainder = intval($row['remainder']) + $applicantCount;
12835 if (intval($row['capacity']) < $remainder) {
12836
12837 $error = array('status' => 'error', 'error' => '9503', 'mode' => $mode, 'sql' => $sql, 'message' => __('The remaining slots in the schedules have an issue.', 'booking-package'), "data" => $row);
12838 throw new Exception(json_encode($error));
12839 #break;
12840
12841 }
12842
12843 $updateSql = $wpdb->prepare(
12844 'UPDATE `' . $table_name . '` SET `remainder` = %d WHERE `key` = %d AND `status` = %s;',
12845 array(intval($remainder), intval($row['key']), 'open')
12846 );
12847 $wpdb->query($updateSql);
12848
12849 array_push(
12850 $rollbackQueries,
12851 $wpdb->prepare(
12852 'UPDATE `' . $table_name . '` SET `remainder` = %d WHERE `key` = %d AND `status` = %s;',
12853 array(intval($row['remainder']), intval($row['key']), 'open')
12854 )
12855 );
12856
12857 array_push($updateSchedule, $row['hour'].":".$row['min']." ".$remainder);
12858
12859 }
12860
12861 }
12862
12863 }
12864
12865 $wpdb->query('COMMIT');
12866 $wpdb->query('UNLOCK TABLES');
12867
12868 } catch (Exception $e) {
12869
12870 $wpdb->query('ROLLBACK');
12871 $wpdb->query('UNLOCK TABLES');
12872 $error = json_decode($e->getMessage(), true);
12873 return $error;
12874
12875 }
12876 /** finally {
12877
12878 $wpdb->query('UNLOCK TABLES');
12879
12880 }
12881 **/
12882
12883
12884
12885 return $updateSchedule;
12886
12887 }
12888
12889 public function getUserList($unixTime, $accountKey = 1){
12890
12891 global $wpdb;
12892 $table_name = $wpdb->prefix . "booking_package_booked_customers";
12893 $sql = $wpdb->prepare(
12894 "SELECT `key`,`scheduleUnixTime`,`scheduleKey`,`courseTime`,`status`,`applicantCount`,`praivateData`,`iCalIDforGoogleCalendar`,`resultOfGoogleCalendar`,`praivateData`,`checkIn`,`checkOut`,`accommodationDetails` FROM ".$table_name." WHERE `iCalIDforGoogleCalendar` IS NOT NULL AND `accountKey` = %d AND `scheduleUnixTime` > %d ORDER BY `key` ASC;",
12895 array(intval($accountKey), intval($unixTime))
12896 );
12897 $rows = $wpdb->get_results($sql, ARRAY_A);
12898 return $rows;
12899
12900 }
12901
12902 private function getUserValues($accountKey, $type, $administrator, $personalInformation = null, $user_id = null) {
12903
12904 global $wpdb;
12905 $setting = new booking_package_setting($this->prefix, $this->pluginName);
12906 $strlen = 0;
12907 $visitorName = array();
12908 $emails = array();
12909 $sms = array();
12910 $table_name = $wpdb->prefix."booking_package_form";
12911 $sql = $wpdb->prepare("SELECT * FROM ".$table_name." WHERE `accountKey` = %d;", array(intval($accountKey)));
12912 $row = $wpdb->get_row($sql, ARRAY_A);
12913 $form = array();
12914 $data = json_decode($row['data'], true);
12915
12916 if ($type == 'update' && empty($personalInformation) === false) {
12917
12918 $data = json_decode($personalInformation, true);
12919
12920 }
12921
12922 if (empty($user_id) === false) {
12923
12924
12925
12926 }
12927
12928 foreach ((array) $data as $key => $value) {
12929
12930 if (is_int($user_id) === true && isset($value['targetCustomers']) && $value['targetCustomers'] == 'visitors') {
12931
12932 $value['active'] = '';
12933
12934 }
12935
12936 if (is_null($user_id) === true && isset($value['targetCustomers']) && $value['targetCustomers'] == 'users') {
12937
12938 $value['active'] = '';
12939
12940 }
12941
12942 $value = $setting->getTranslateFormField($value, $accountKey, get_locale(), 'form_field');
12943
12944 array_push($form, $value);
12945
12946 }
12947
12948 for ($i = 0; $i < count($form); $i++) {
12949
12950 if (!isset($form[$i]['active'])) {
12951
12952 $form[$i]['active'] = '';
12953
12954 }
12955
12956 if (!isset($_POST['form' . $i]) && $form[$i]['active'] == 'true') {
12957
12958 $_POST['form' . $i] = '';
12959
12960 }
12961
12962 if (!isset($_POST['form' . $i])) {
12963
12964 continue;
12965
12966 }
12967
12968 $value = $_POST['form' . $i];
12969 if ($form[$i]['type'] == 'TEXTAREA') {
12970
12971 $value = sanitize_textarea_field($value);
12972
12973 } else if ($form[$i]['type'] == 'CHECK') {
12974
12975 $value = stripslashes($value);
12976 $value = sanitize_text_field($value);
12977 $value = json_decode($value, true);
12978 if (is_null($value) || is_bool($value) === true) {
12979
12980 $value = array();
12981
12982 }
12983
12984 $value = implode(',', $value);
12985
12986 } else {
12987
12988 $value = sanitize_text_field($value);
12989
12990 }
12991
12992 if (isset($_POST['form' . $i])) {
12993
12994 if (($form[$i]['required'] == 'true' || $form[$i]['required'] == 'true_frontEnd') && strlen(preg_replace("/( | )/", "", $value)) == 0) {
12995
12996 if ($administrator === true && $form[$i]['required'] == 'true') {
12997
12998 return array('status' => 'error', "message" => stripslashes('Invalid value in the "' . $form[$i]['name'] . '".'), 'form' => $form[$i]);
12999
13000 } else if ($administrator === false) {
13001
13002 return array('status' => 'error', "message" => stripslashes('Invalid value in the "' . $form[$i]['name'] . '".'), 'form' => $form[$i]);
13003
13004 }
13005
13006 } else {
13007
13008 if ($form[$i]['isEmail'] == 'true' && strlen($value) != 0 && is_email($value) === false) {
13009
13010 return array('status' => 'error', "message" => __('The format of the email address is incorrect.', 'booking-package') . "\n" . $form[$i]['name'], 'form' => $form[$i]);
13011
13012 } else {
13013
13014 if ($form[$i]['type'] === 'CHECK') {
13015
13016 $value = stripslashes($_POST['form' . $i]);
13017 $value = sanitize_text_field($value);
13018 $value = json_decode($value, true);
13019 if (is_null($value) || is_bool($value) === true) {
13020
13021 $value = array();
13022
13023 }
13024
13025 }
13026
13027 if ($form[$i]['isEmail'] === 'true') {
13028
13029 if (is_array($value) === true) {
13030
13031 return array('status' => 'error', "message" => __('The format of the email address is incorrect.', 'booking-package') . "\n" . $form[$i]['name'], 'form' => $form[$i]);
13032
13033 }
13034
13035 $value = sanitize_email($value);
13036 if (!empty($value)) {
13037
13038 array_push($emails, $value);
13039
13040 }
13041
13042 }
13043
13044 if (isset($form[$i]['isSMS']) && $form[$i]['isSMS'] == 'true') {
13045
13046 $value = sanitize_text_field($value);
13047 if (!empty($value)) {
13048
13049 array_push($sms, $value);
13050
13051 }
13052
13053 }
13054
13055 if ($form[$i]['isName'] == 'true') {
13056
13057 array_push($visitorName, sanitize_text_field($value));
13058
13059 }
13060
13061 $form[$i]['value'] = $value;
13062
13063 }
13064
13065 }
13066
13067 }
13068
13069 }
13070
13071 return array('form' => $form, 'emails' => $emails, 'sms' => $sms);
13072
13073 }
13074
13075 private function getExtensionsValid() {
13076
13077 if (is_null($this->isExtensionsValid)) {
13078
13079 $setting = new booking_package_setting($this->prefix, $this->pluginName);
13080 $this->isExtensionsValid = $setting->getSiteStatus();
13081
13082 }
13083
13084 return $this->isExtensionsValid;
13085
13086 }
13087
13088 public function emailFormat($email, $title = null){
13089
13090 if (empty($email)) {
13091
13092 return null;
13093
13094 }
13095
13096 $email = trim($email);
13097 $value = $email;
13098 if (!is_null($title) && strlen($title) != 0) {
13099
13100 $title = stripslashes($title);
13101 $title = wp_specialchars_decode($title, ENT_QUOTES);
13102 $value = sprintf("%s <%s>", $title, $email);
13103
13104 }
13105 return $value;
13106
13107 }
13108
13109 public function dateFormat($dateFormat, $positionOfWeek, $unixTime, $title, $includingTime, $shortString, $responseType){
13110
13111 $dateFormat = intval($dateFormat);
13112 $comma = ',';
13113 $clock = get_option($this->prefix . "clock", '24hours');
13114 $positionTimeDate = get_option($this->prefix . "positionTimeDate", "dateTime");
13115 if (is_numeric($clock)) {
13116
13117 if (intval($clock) == 12) {
13118
13119 $clock = '12a.m.p.m';
13120
13121 } else if (intval($clock) == 24) {
13122
13123 $clock = '24hours';
13124
13125 }
13126
13127 }
13128
13129 $monthList = array(__('January', 'booking-package'), __('February', 'booking-package'), __('March', 'booking-package'), __('April', 'booking-package'), __('May', 'booking-package'), __('June', 'booking-package'), __('July', 'booking-package'), __('August', 'booking-package'), __('September', 'booking-package'), __('October', 'booking-package'), __('November', 'booking-package'), __('December', 'booking-package'));
13130 $weekNameList = array(__('Sunday', 'booking-package'), __('Monday', 'booking-package'), __('Tuesday', 'booking-package'), __('Wednesday', 'booking-package'), __('Thursday', 'booking-package'), __('Friday', 'booking-package'), __('Saturday', 'booking-package'));
13131 $weekName = $weekNameList[date('w', $unixTime)];
13132
13133 if ($shortString == true) {
13134
13135 $monthList = array(__('Jan', 'booking-package'), __('Feb', 'booking-package'), __('Mar', 'booking-package'), __('Apr', 'booking-package'), __('May', 'booking-package'), __('Jun', 'booking-package'), __('Jul', 'booking-package'), __('Aug', 'booking-package'), __('Sep', 'booking-package'), __('Oct', 'booking-package'), __('Nov', 'booking-package'), __('Dec', 'booking-package'));
13136 $weekNameList = array(__('Sun', 'booking-package'), __('Mon', 'booking-package'), __('Tue', 'booking-package'), __('Wed', 'booking-package'), __('Thu', 'booking-package'), __('Fri', 'booking-package'), __('Sat', 'booking-package'));
13137 $weekName = $weekNameList[date('w', $unixTime)];
13138
13139 }
13140
13141 if (empty($title)) {
13142
13143 $title = '';
13144
13145 }
13146
13147 $date = date('d/m/Y ', $unixTime);
13148 $time = date('H:i', $unixTime);
13149 $hour = intval(date('G', $unixTime));
13150 if ($clock != '24hours') {
13151
13152 $print_am_pm = 'a.m.';
13153 if ($clock == '12AMPM') {
13154
13155 $print_am_pm = 'AM';
13156
13157 } else if ($clock == '12ampm') {
13158
13159 $print_am_pm = 'am';
13160
13161 }
13162
13163 if ($hour >= 12) {
13164
13165 $print_am_pm = 'p.m.';
13166 if ($clock == '12AMPM') {
13167
13168 $print_am_pm = 'PM';
13169
13170 } else if ($clock == '12ampm') {
13171
13172 $print_am_pm = 'pm';
13173
13174 }
13175
13176 }
13177
13178 $time = sprintf(__('%s:%s ' . $print_am_pm, 'booking-package'), date('h', $unixTime), date('i', $unixTime));
13179
13180 }
13181
13182 if ($includingTime == false) {
13183
13184 $time = "";
13185 $comma = '';
13186
13187 }
13188
13189 if ($dateFormat == 0) {
13190
13191 $date = date('m/d/Y', $unixTime);
13192
13193 } else if ($dateFormat == 1) {
13194
13195 $date = date('m-d-Y', $unixTime);
13196
13197 } else if ($dateFormat == 2) {
13198
13199 #$date = date('F d, Y', $unixTime);
13200 $date = $monthList[date('n', $unixTime) - 1] . date(' d, Y', $unixTime);
13201
13202 } else if ($dateFormat == 3) {
13203
13204 $date = date('d/m/Y', $unixTime);
13205
13206 } else if ($dateFormat == 4) {
13207
13208 $date = date('d-m-Y', $unixTime);
13209
13210 } else if ($dateFormat == 5) {
13211
13212 #$date = date('d F, Y ', $unixTime);
13213 $date = date('d', $unixTime) . ' ' . $monthList[date('n', $unixTime) - 1].date(', Y', $unixTime);
13214
13215 } else if ($dateFormat == 6) {
13216
13217 $date = date('Y/m/d', $unixTime);
13218
13219 } else if ($dateFormat == 7) {
13220
13221 $date = date('Y-m-d', $unixTime);
13222
13223 } else if ($dateFormat == 8 || $dateFormat == 9) {
13224
13225 $date = date('d.m.Y', $unixTime);
13226
13227 } else if ($dateFormat == 10) {
13228
13229 $date = date('d', $unixTime) . '.' . $monthList[date('n', $unixTime) - 1] . date('.Y', $unixTime);
13230
13231 } else if ($dateFormat == 11) {
13232
13233 $date = $monthList[date('n', $unixTime) - 1] . ' ' . date('d', $unixTime) . date(' Y', $unixTime);
13234
13235 } else if ($dateFormat == 12) {
13236
13237 $date = date('d', $unixTime) . ' ' . $monthList[date('n', $unixTime) - 1] . date(' Y', $unixTime);
13238
13239 } else if ($dateFormat == 13) {
13240
13241 #$date = date('F d, Y', $unixTime);
13242 $date = date('d.m.Y', $unixTime);
13243
13244 } else if ($dateFormat == 14) {
13245
13246 #$date = date('F d, Y', $unixTime);
13247 $date = date('d.', $unixTime) . $monthList[date('n', $unixTime) - 1] . date('.Y', $unixTime);
13248
13249 } else if ($dateFormat == 15) {
13250
13251 $date = date('Y年m月d日', $unixTime);
13252
13253 }
13254
13255
13256 if ($responseType == 'text') {
13257
13258 if ($positionTimeDate == 'dateTime') {
13259
13260 if ($positionOfWeek == 'before') {
13261
13262 $date = $weekName . ' ' . $date . $comma . ' ' . $time . ' ' . $title;
13263
13264 } else {
13265
13266 $date = $date . ' ' . $weekName . $comma . ' ' . $time . ' ' . $title;
13267
13268 }
13269
13270 } else {
13271
13272 if (!empty($title)) {
13273
13274 $title = ' ' . $title;
13275
13276 } else {
13277
13278 $title = '';
13279
13280 }
13281
13282 if ($positionOfWeek == 'before') {
13283
13284 $date = $time . $title . $comma . ' ' . $weekName . ' ' . $date;
13285
13286 } else {
13287
13288 $date = $time . $title . $comma . ' ' . $date . ' ' . $weekName;
13289
13290 }
13291
13292 }
13293
13294
13295
13296 $date = trim($date);
13297 return $date;
13298
13299 } else {
13300
13301 if ($positionOfWeek == 'before') {
13302
13303 $date = $weekName . ' ' . $date . ' ';
13304
13305 } else {
13306
13307 $date = $date . ' ' . $weekName . ' ';
13308
13309 }
13310
13311 return array('date' => trim($date), 'time' => (trim($time)), 'title' => trim($title));
13312
13313 }
13314
13315 }
13316
13317 public function formatCost($cost = 0, $currency = 'usd'){
13318
13319 $cost = intval($cost);
13320 if ($this->numberFormatter === true) {
13321
13322 $currency_info = $this->currencies[$currency];
13323 $digits = $currency_info['ISOdigits'];
13324 if ($digits !== 0) {
13325
13326 $costString = strval($cost);
13327 $cost = substr($costString, 0, -$digits) . '.' . substr($costString, -$digits);
13328
13329 }
13330
13331 $fmt = new NumberFormatter($this->locale, NumberFormatter::CURRENCY);
13332 $cost = $fmt->formatCurrency($cost, $currency);
13333 if ($currency === 'jpy') {
13334
13335 $cost = preg_replace('/(\.\d{2})/', '', $cost);
13336
13337 }
13338
13339 return $cost;
13340
13341 }
13342
13343
13344
13345 if (strtoupper($currency) == 'USD') {
13346
13347 $cost = 'US\$' . number_format(($cost / 100), 2);
13348
13349 } else if (strtoupper($currency) == 'EUR') {
13350
13351 $cost = number_format(($cost / 100), 2, ',', '.') . ' €';
13352
13353 } else if (strtoupper($currency) == 'JPY') {
13354
13355 $cost = '¥' . number_format($cost, 0);
13356
13357 } else if (strtoupper($currency) == 'TRY') {
13358
13359 $cost = number_format($cost, 0) . '₺';
13360
13361 } else if (strtoupper($currency) == 'KRW') {
13362
13363 $cost = '₩' . number_format($cost, 0);
13364
13365 } else if (strtoupper($currency) == 'HUF') {
13366
13367 $cost = 'HUF ' . number_format($cost, 0);
13368
13369 } else if (strtoupper($currency) == 'DKK') {
13370
13371 $cost = number_format(($cost / 100), 2) . 'kr';
13372
13373 } else if (strtoupper($currency) == 'CNY') {
13374
13375 $cost = 'CN¥' . number_format(($cost / 100), 2);
13376
13377 } else if (strtoupper($currency) == 'TWD') {
13378
13379 $cost = 'NT\$' . number_format($cost, 0);
13380
13381 } else if (strtoupper($currency) == 'THB') {
13382
13383 $cost = 'TH฿' . number_format($cost, 0);
13384
13385 } else if (strtoupper($currency) == 'COP') {
13386
13387 $cost = 'COP' . number_format($cost, 0);
13388
13389 } else if (strtoupper($currency) == 'CAD') {
13390
13391 $cost = '\$' . number_format(($cost / 100), 2);
13392
13393 } else if (strtoupper($currency) == 'AUD') {
13394
13395 $cost = '\$' . number_format(($cost / 100), 2);
13396
13397 } else if (strtoupper($currency) == 'GBP') {
13398
13399 $cost = '£' . number_format(($cost / 100), 2);
13400
13401 } else if (strtoupper($currency) == 'PHP') {
13402
13403 $cost = 'PHP ' . number_format(($cost / 100), 2);
13404
13405 } else if (strtoupper($currency) == 'CHF') {
13406
13407 $cost = 'CHF ' . number_format(($cost / 100), 2);
13408
13409 } else if (strtoupper($currency) == 'CZK') {
13410
13411 $cost = 'Kč' . number_format(($cost / 100), 2);
13412
13413 } else if (strtoupper($currency) == 'RUB') {
13414
13415 $cost = number_format(($cost / 100), 2) . '₽';
13416
13417 } else if (strtoupper($currency) == 'NZD') {
13418
13419 $cost = 'NZ\$' . number_format(($cost / 100), 2);
13420
13421 } else if (strtoupper($currency) == 'HRK') {
13422
13423 $cost = number_format(($cost / 100), 2) . ' Kn';
13424
13425 } else if (strtoupper($currency) == 'UAH') {
13426
13427 $cost = number_format(($cost / 100), 2) . 'грн.';
13428
13429 } else if (strtoupper($currency) == 'BRL') {
13430
13431 $cost = 'R\$' . number_format(($cost / 100), 2, ',', '.');
13432
13433 } else if (strtoupper($currency) == 'AED') {
13434
13435 $cost = number_format(($cost / 100), 2, ',', '.') . ' AED';
13436
13437 } else if (strtoupper($currency) == 'GTQ') {
13438
13439 $cost = 'Q' . number_format(($cost / 100), 2);
13440
13441 } else if (strtoupper($currency) == 'MXN') {
13442
13443 $cost = '$' . number_format(($cost / 100), 2) . " MXN";
13444
13445 } else if (strtoupper($currency) == 'ARS') {
13446
13447 $cost = '$' . number_format($cost, 0, '.', '.');
13448
13449 } else if (strtoupper($currency) == 'ZAR') {
13450
13451 $cost = 'R' . number_format(($cost / 100), 2);
13452
13453 } else if (strtoupper($currency) == 'SEK') {
13454
13455 $cost = number_format(($cost / 100), 2, '.', ' ') . ' kr';
13456
13457 } else if (strtoupper($currency) == 'RON') {
13458
13459 $cost = number_format(($cost / 100), 2, ',', '') . ' lei';
13460
13461 } else if (strtoupper($currency) == 'INR') {
13462
13463 $cost = number_format(($cost / 1000), 3, '.', '');
13464 $parts = explode(".", $cost);
13465 if (intval($parts[0]) > 0) {
13466
13467 $formattedIntegerPart = preg_replace("/\B(?=(\d{2})+(?!\d))/", " ", $parts[0]);
13468 $cost = $formattedIntegerPart . (isset($parts[1]) ? "." . $parts[1] : "");
13469
13470 } else {
13471
13472 $cost = $parts[1];
13473
13474 }
13475
13476 $cost = '₹' . str_replace(".", " ", $cost);
13477
13478 } else if (strtoupper($currency) == 'SGD') {
13479
13480 $cost = '\$ ' . number_format(($cost / 100), 2);
13481
13482 } else if (strtoupper($currency) == 'IDR') {
13483
13484 $cost = 'Rp ' . number_format($cost, 0, '.', '.');
13485
13486 }
13487
13488 return $cost;
13489
13490 }
13491
13492 public function bookingDetailsForHotel($accountKey, $accommodationDetails, $currency, $mode = 'array'){
13493
13494 if (is_null($accommodationDetails) || $accommodationDetails === false) {
13495
13496 return array();
13497
13498 }
13499
13500 $setting = new booking_package_setting($this->prefix, $this->pluginName);
13501 $numberKeys = $setting->getObjectOfDaysOfWeek();
13502
13503 $calendarAccount = $this->getCalendarAccount($accountKey);
13504 $applicantCount = intval($accommodationDetails['applicantCount']);
13505 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
13506 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
13507 $formatNigh = __('nights', 'booking-package');
13508 $nights = __('nights', 'booking-package');
13509 if (intval($calendarAccount['formatNightDay']) == 1) {
13510
13511 $nights = __('%s nights %s days', 'booking-package');
13512
13513 }
13514
13515 $lengthOfStay = $accommodationDetails['nights'] . " " . $nights . " (".$this->formatCost($accommodationDetails['accommodationFee'], $currency) . ")";
13516 if (intval($accommodationDetails['nights']) == 1) {
13517
13518 $formatNigh = __('night', 'booking-package');
13519 $nights = __('night', 'booking-package');
13520 if (intval($calendarAccount['formatNightDay']) == 1) {
13521
13522 $nights = __('%s night %s days', 'booking-package');
13523
13524 }
13525
13526 }
13527
13528 $multipleRooms = false;
13529 $roomStr = __('room', 'booking-package');
13530 if ($applicantCount > 1) {
13531
13532 $multipleRooms = true;
13533 $roomStr = __('rooms', 'booking-package');
13534
13535 }
13536
13537 $formatNigh = $accommodationDetails['nights'] . " " . $formatNigh;
13538 $formatNightDay = $accommodationDetails['nights'] . " " . $nights;
13539 if (intval($calendarAccount['formatNightDay']) == 1) {
13540
13541 $formatNightDay = sprintf($nights, $accommodationDetails['nights'], $accommodationDetails['nights'] + 1);
13542
13543 }
13544
13545 $detailsList = array(__('Total number of nights', 'booking-package') . ": " . $formatNightDay . " ".$this->formatCost($accommodationDetails['accommodationFee'], $currency) . ", " . $accommodationDetails['applicantCount'] . ' ' . $roomStr);
13546 #$detailsList = array(__('Total number of nights', 'booking-package') . ": " . sprintf($nights, $accommodationDetails['nights'], $accommodationDetails['nights'] + 1) . " ".$this->formatCost($accommodationDetails['accommodationFee'], $currency) . ", " . $accommodationDetails['applicantCount'] . ' ' . $roomStr);
13547 $objectList = array(
13548 'totalLengthOfStay' => array(
13549 #'main' => $accommodationDetails['nights'] . " " . $nights . " " . $this->formatCost(($accommodationDetails['accommodationFee']), $currency),
13550 'main' => $formatNightDay . " " . $this->formatCost(($accommodationDetails['accommodationFee']), $currency),
13551 'sub' => array(),
13552 ),
13553 'totalLengthOfOptions' => array(
13554 'main' => array(),
13555 'sub' => array(),
13556 ),
13557 'totalLengthOfGuests' => array(
13558 'main' => array(),
13559 'sub' => array(),
13560 ),
13561 'totalLengthOfTaxes' => array(
13562 'main' => array(),
13563 'sub' => array(),
13564 ),
13565 );
13566 $scheduleDetails = $accommodationDetails['scheduleDetails'];
13567 $no = 0;
13568 foreach ((array) $scheduleDetails as $key => $value) {
13569
13570 $no++;
13571 $details = "#" . $no . " " . $this->dateFormat($dateFormat, $positionOfWeek, $value['unixTime'], null, false, false, 'text') . " ";
13572 if (intval($value['cost']) > 0) {
13573
13574 $details .= $this->formatCost($value['cost'] * $applicantCount, $currency);
13575
13576 }
13577
13578 if ($multipleRooms === true) {
13579
13580 $details .= ' (' . $this->formatCost($value['cost'], $currency) . ' * ' . $applicantCount . ' ' . $roomStr . ')';
13581
13582 }
13583
13584 array_push($detailsList, $details);
13585 array_push($objectList['totalLengthOfStay']['sub'], $details);
13586
13587 if (isset($value['priceKeyByDayOfWeek'])) {
13588
13589 $priceKeyByDayOfWeek = $value['priceKeyByDayOfWeek'];
13590 if (isset($numberKeys[$priceKeyByDayOfWeek])) {
13591
13592 $numberKeys[$priceKeyByDayOfWeek]++;
13593
13594 }
13595
13596 }
13597
13598 }
13599
13600 if (isset($accommodationDetails['adult']) === false) {
13601
13602 $accommodationDetails['adult'] = 0;
13603
13604 }
13605
13606 if (isset($accommodationDetails['children']) === false) {
13607
13608 $accommodationDetails['children'] = 0;
13609
13610 }
13611
13612 $people = intval($accommodationDetails['adult']) + intval($accommodationDetails['children']);
13613 $personAmount = 0;
13614 $optionsAmount = 0;
13615 $additionalFee = 0;
13616 $people = 0;
13617 $totalNumberOfOptions = 0;
13618 if (isset($accommodationDetails['rooms']) === false) {
13619
13620 $accommodationDetails['rooms'] = array();
13621
13622 }
13623 $rooms = $accommodationDetails['rooms'];
13624 foreach ((array) $rooms as $room) {
13625
13626 $personAmount += intval($accommodationDetails['personAmount']);
13627 $optionsAmount += intval($room['optionsAmount']);
13628 $additionalFee += intval($room['additionalFee']) * intval($accommodationDetails['nights']);
13629 $people += intval($room['person']);
13630 if (isset($room['totalNumberOfOptions'])) {
13631
13632 $totalNumberOfOptions += intval($room['totalNumberOfOptions']);
13633
13634 }
13635
13636 }
13637
13638 /** Options **/
13639
13640 if ($optionsAmount > 0) {
13641
13642 $totalNumberOfOptions .= ", " . $this->formatCost($optionsAmount, $currency) . "";
13643
13644 }
13645
13646 array_push($detailsList, "\n" . __('Total Number of Options', 'booking-package') . ": " . $totalNumberOfOptions);
13647 $objectList['totalLengthOfOptions']['main'] = $totalNumberOfOptions;
13648
13649 $roomNo = 0;
13650 foreach ((array) $rooms as $room) {
13651
13652 if ($multipleRooms === true) {
13653
13654 $roomNo++;
13655 array_push($detailsList, __('Room', 'booking-package') . ': ' . $roomNo);
13656 array_push($objectList['totalLengthOfOptions']['sub'], __('Room', 'booking-package') . ': ' . $roomNo);
13657
13658 }
13659
13660 $optionsList = array();
13661 if (isset($room['optionsList'])) {
13662
13663 $optionsList = $room['optionsList'];
13664
13665 }
13666 $no = 0;
13667 foreach ((array) $optionsList as $key => $value) {
13668
13669 $no++;
13670 $name = $value['name'];
13671 $options = $value['json'];
13672 for ($i = 0; $i < count($options); $i++) {
13673
13674 if (intval($options[$i]['selected']) == 1) {
13675
13676 $details = "#" . $no . " " . $name . ": " . $options[$i]['name'] . "";
13677 if ($i === 0) {
13678
13679 $details = "#" . $no . " " . $name . ": " . __('Unselected', 'booking-package') . "";
13680
13681 }
13682
13683 $extraCharge = $this->getExtraChargeForHotelOption($value, $options[$i], intval($accommodationDetails['nights']), intval($room['adult']), intval($room['children']));
13684 if (intval($extraCharge) > 0) {
13685
13686 $details .= ", " . $this->formatCost($extraCharge, $currency);
13687
13688 }
13689
13690 array_push($detailsList, $details);
13691 array_push($objectList['totalLengthOfOptions']['sub'], $details);
13692 break;
13693
13694 }
13695
13696 }
13697
13698 }
13699
13700 }
13701
13702
13703 if (isset($objectList['totalLengthOfOptions']) === true) {
13704
13705 unset($objectList['totalLengthOfOptions']);
13706
13707 }
13708
13709 /** Options **/
13710
13711 /** Guests **/
13712 if ($people == 1) {
13713
13714 //$people = $people . " " . __("person", 'booking-package') . "";
13715 $people = sprintf(__("%s guest", 'booking-package'), $people);
13716
13717
13718 } else {
13719
13720 //$people = $people . " " . __("people", 'booking-package') . "";
13721 $people = sprintf(__("%s guests", 'booking-package'), $people);
13722
13723 }
13724
13725 if ($personAmount > 0) {
13726
13727 $people .= ", " . $this->formatCost($personAmount, $currency) . "";
13728
13729 } else {
13730 /**
13731 if ($additionalFee > 0) {
13732
13733 $people .= ", " . $this->formatCost($additionalFee, $currency) . "";
13734
13735 }
13736 **/
13737 }
13738
13739 array_push($detailsList, "\n" . __('Total Number of Guests', 'booking-package') . ": " . $people);
13740 $objectList['totalLengthOfGuests']['main'] = $people;
13741
13742 $roomNo = 0;
13743 foreach ((array) $rooms as $room) {
13744
13745 if ($multipleRooms === true) {
13746
13747 $roomNo++;
13748 array_push($detailsList, __('Room', 'booking-package') . ': ' . $roomNo);
13749 array_push($objectList['totalLengthOfGuests']['sub'], __('Room', 'booking-package') . ': ' . $roomNo);
13750
13751 }
13752
13753 $guestsList = array();
13754 if (isset($room['guestsList'])) {
13755
13756 $guestsList = $room['guestsList'];
13757
13758 }
13759 $no = 0;
13760 foreach ((array) $guestsList as $key => $value) {
13761
13762 $no++;
13763 $name = $value['name'];
13764 $guests = $value['json'];
13765 for ($i = 0; $i < count($guests); $i++) {
13766
13767 if (intval($guests[$i]['selected']) == 1) {
13768
13769 $details = "#" . $no . " " . $name . ": " . $guests[$i]['name'] . "";
13770 if ($i === 0) {
13771
13772 $details = "#" . $no . " " . $name . ": " . __('Unselected', 'booking-package') . "";
13773
13774 }
13775
13776
13777 if (intval($guests[$i]['price']) > 0) {
13778
13779 #$details .= ", ".$this->formatCost($guests[$i]['price'], $currency) . " * " . $accommodationDetails['nights']." ".$nights."";
13780 $details .= ", " . $this->formatCost($guests[$i]['price'], $currency) . " * " . $formatNigh;
13781
13782 }
13783
13784 if (isset($room['personAmount']) && intval($room['personAmount']) > 0) {
13785
13786 $isGuestsPrice = true;
13787 $guestPrice = 0;
13788 $details = "#" . $no . " " . $name . ": " . $guests[$i]['name'] . "";
13789 if ($i === 0) {
13790
13791 $isGuestsPrice = false;
13792 $details = "#" . $no . " " . $name . ": " . __('Unselected', 'booking-package') . "";
13793
13794 }
13795
13796 foreach ((array) $numberKeys as $nmuberKey => $numberValue) {
13797
13798 if (intval($guests[$i][$nmuberKey]) == 0 && ($nmuberKey == 'priceOnDayBeforeNationalHoliday' || $nmuberKey == 'priceOnNationalHoliday')) {
13799
13800 $changePriceForGuest = function($schedules, $numberKeys, $nmuberKey, $guest) {
13801
13802 $personAmount = 0;
13803 foreach ((array) $schedules as $schedule) {
13804
13805 if ($schedule['priceKeyByDayOfWeek'] == $nmuberKey) {
13806
13807 $weekKey = intval($schedule['weekKey']);
13808 if ($weekKey == 0) {
13809
13810 $weekKey = 6;
13811
13812 } else {
13813
13814 $weekKey--;
13815
13816 }
13817
13818 $personAmount += $guest[$numberKeys[$weekKey]];
13819
13820 }
13821
13822 }
13823
13824 return $personAmount;
13825
13826 };
13827 $guestPrice += $changePriceForGuest($scheduleDetails, array_keys($numberKeys), $nmuberKey, $guests[$i]);
13828
13829 } else {
13830
13831 $guestPrice += $guests[$i][$nmuberKey] * $numberValue;
13832
13833 }
13834
13835
13836 }
13837
13838 if ($isGuestsPrice === true) {
13839
13840 $details .= ", " . $this->formatCost($guestPrice, $currency);
13841
13842 }
13843
13844 }
13845
13846 array_push($detailsList, $details);
13847 array_push($objectList['totalLengthOfGuests']['sub'], $details);
13848 break;
13849
13850 }
13851
13852 }
13853
13854 }
13855
13856
13857 }
13858 /** Guests **/
13859
13860 $taxes = array();
13861 $surcharges = array();
13862 $taxesList = $accommodationDetails['taxes'];
13863 foreach ((array) $taxesList as $key => $tax) {
13864
13865 $details = $tax['name'] . " " . $this->formatCost($tax['taxValue'], $currency);
13866 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_inclusive') {
13867
13868 array_push($taxes, $details);
13869
13870 } else if($tax['type'] == 'tax' && $tax['tax'] == 'tax_exclusive') {
13871
13872 array_push($taxes, $details);
13873
13874 } else if($tax['type'] == 'surcharge') {
13875
13876 array_push($surcharges, $details);
13877
13878 }
13879
13880 #$details = $tax['name']." ".$this->formatCost($tax['taxValue'], $currency);
13881 #array_push($detailsList, $details);
13882 array_push($objectList['totalLengthOfTaxes']['sub'], $details);
13883
13884 }
13885
13886 if (count($surcharges) > 0) {
13887
13888 array_push($detailsList, "\n".__('Surcharges', 'booking-package'));
13889 for ($i = 0; $i < count($surcharges); $i++) {
13890
13891 array_push($detailsList, $surcharges[$i]);
13892
13893 }
13894
13895 }
13896
13897 if (count($taxes) > 0) {
13898
13899 array_push($detailsList, "\n".__('Taxes', 'booking-package'));
13900 for ($i = 0; $i < count($taxes); $i++) {
13901
13902 array_push($detailsList, $taxes[$i]);
13903
13904 }
13905
13906 }
13907
13908 if ($mode == 'array') {
13909
13910 return $detailsList;
13911
13912 } else {
13913
13914 return $objectList;
13915
13916 }
13917
13918 }
13919
13920
13921 public function getAmount($bookingID, $calendarAccount, $accommodationDetails, $services = null, $guests = null, $taxes = null, $coupon = null) {
13922
13923 $amount = 0;
13924 $reflectAdditional = 1;
13925 $reflectAdditionalTitle = null;
13926 $reflectService = 1;
13927 $reflectServiceTitle = null;
13928 $guestsList = array();
13929 if (is_null($guests) === false && array_key_exists('guests', $guests) === true && is_null($guests['guests']) === false ) {
13930
13931 $reflectAdditional = intval($guests['reflectAdditional']);
13932 $reflectAdditionalTitle = $guests['reflectAdditionalTitle'];
13933 $reflectService = intval($guests['reflectService']);
13934 $reflectServiceTitle = $guests['reflectServiceTitle'];
13935 $guestsList = $guests['guests'];
13936
13937 }
13938
13939 if ($reflectAdditional == 0) {
13940
13941 $reflectAdditional = 1;
13942
13943 }
13944
13945 if ($calendarAccount['type'] == 'day') {
13946
13947 if (is_array($services)) {
13948
13949 foreach ((array) $services as $key => $service) {
13950
13951 #$amount += intval($service['cost']) * $reflectService;
13952 $responseCostInService = $this->getCostsInService($calendarAccount, $service, $guestsList);
13953 $amount += $responseCostInService['totalCost'];
13954 foreach ((array) $service['options'] as $option) {
13955
13956 if (intval($option['selected']) == 1) {
13957
13958 #$amount += intval($option['cost']) * $reflectService;
13959 $responseCostInOption = $this->getCostsInService($calendarAccount, $option, $guestsList);
13960 $amount += $responseCostInOption['totalCost'];
13961
13962 }
13963
13964 }
13965
13966 }
13967
13968 #$amount = $this->getDiscountCostByCoupon($coupon, $amount);
13969
13970 }
13971
13972 $amount += $this->getSelectedGuestTotalAmount($calendarAccount, $guestsList, true);
13973 $amount = $this->getDiscountCostByCoupon($coupon, $amount);
13974
13975 $taxes = $this->getTaxesDetailsForVisitor($bookingID, $reflectAdditional, $taxes, $amount);
13976 for ($i = 0; $i < count($taxes); $i++) {
13977
13978 $tax = $taxes[$i];
13979 if ($tax['type'] == 'tax' && $tax['tax'] == 'tax_exclusive') {
13980
13981 $amount += $tax['taxValue'];
13982
13983 } else if ($tax['type'] == 'surcharge') {
13984
13985 $amount += $tax['taxValue'] * $reflectAdditional;
13986
13987 }
13988
13989 }
13990
13991 #$amount = $this->formatCost($amount, $currency);
13992
13993 } else {
13994
13995 #$amount = $this->formatCost((intval($accommodationDetails['accommodationFee']) + intval($accommodationDetails['taxesFee']) + intval($accommodationDetails['additionalFee'])), $currency);
13996 $amount = (intval($accommodationDetails['accommodationFee']) + intval($accommodationDetails['taxesFee']) + intval($accommodationDetails['additionalFee']));
13997
13998 if (isset($accommodationDetails['personAmount']) === false) {
13999
14000 $accommodationDetails['personAmount'] = 0;
14001
14002 }
14003
14004 if (isset($accommodationDetails['optionsAmount']) === false) {
14005
14006 $accommodationDetails['optionsAmount'] = 0;
14007
14008 }
14009
14010 if (intval($accommodationDetails['personAmount']) > 0 || intval($accommodationDetails['optionsAmount']) > 0) {
14011
14012 $amount = (intval($accommodationDetails['accommodationFee']) + intval($accommodationDetails['taxesFee']) + intval($accommodationDetails['personAmount']) + intval($accommodationDetails['optionsAmount']));
14013
14014 }
14015
14016
14017 }
14018
14019 return $amount;
14020
14021 }
14022
14023 public static function isIndexedArray($array) {
14024
14025 if (!is_array($array)) {
14026 return false;
14027 }
14028
14029 if ($array === []) {
14030 return true;
14031 }
14032
14033 return array_keys($array) === range(0, count($array) - 1);
14034
14035 }
14036
14037 public function getNotificationContents($calendarAccount, $customer, $email_id, $emailKey, $notificationContents, $emailFormat) {
14038
14039 $accountKey = $calendarAccount['key'];
14040 $bookingID = $customer['key'];
14041 $unixTime = $customer['scheduleUnixTime'];
14042 $scheduleTitle = $customer['scheduleTitle'];
14043 $timestampForUnixTime = $customer['reserveTime'];
14044 $currency = $customer['currency'];
14045 $payName = $customer['payName'];
14046 $payId = $customer['payId'];
14047 $form = json_decode($customer['praivateData'], true);
14048 $options = json_decode($customer['options'], true);
14049 $coupon = null;
14050 $positionTimeDate = get_option($this->prefix . "positionTimeDate", "dateTime");
14051
14052 $paymentMethod = array('locally' => __('Local Payment', 'booking-package'), 'stripe' => __('Pay with Credit Card', 'booking-package'), 'stripe_paypay' => sprintf(__('Pay with %s', 'booking-package'), 'PayPay'), 'stripe_konbini' => __('Pay at Convenience Store', 'booking-package'), 'paypal' => __('Pay with PayPal', 'booking-package'));
14053
14054 if (intval($calendarAccount['customizeLabelsBool']) === 1) {
14055
14056 $customizeLabels = $calendarAccount['customizeLabels'];
14057 $paymentMethod = array('locally' => $customizeLabels['Local Payment'], 'stripe' => $customizeLabels['Pay with Stripe'], 'stripe_paypay' => $customizeLabels['Pay with PayPay'], 'stripe_konbini' => $customizeLabels['Pay at Convenience Store (via Stripe)'], 'paypal' => $customizeLabels['Pay with PayPal']);
14058
14059 }
14060
14061 if (empty($payName)) {
14062
14063 $payName = $paymentMethod['locally'];
14064
14065 }
14066
14067 if (isset($customer['coupon']) && !empty($customer['coupon'])) {
14068
14069 $coupon = json_decode($customer['coupon'], true);
14070
14071 }
14072
14073 $accommodationDetails = array();
14074 if ($calendarAccount['type'] == 'hotel') {
14075
14076 $accommodationDetails = json_decode($customer['accommodationDetails'], true);
14077
14078 } else {
14079
14080 $accommodationDetails['taxes'] = json_decode($customer['taxes'], true);
14081
14082 }
14083
14084 $guests = $this->jsonDecodeForGuests($customer['guests']);
14085 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($customer['options'], true), $guests['guests'], "options", $coupon, $customer['applicantCount'], false);
14086 $services = $servicesDetails['object'];
14087 #$guests = $responseGuests['guests'];
14088 #var_dump($servicesDetails);
14089 $cancellationUri = null;
14090 if (!empty($customer['permalink']) && !empty($customer['cancellationToken'])) {
14091
14092 $cancellationUri = $this->getCancellationUri($customer['permalink'], $customer['key'], $customer['cancellationToken']);
14093
14094 }
14095
14096 $response = array('emailSubject' => array(), 'emailBody' => array(), 'visitorEmail' => array(), 'visitorSMS' => array());
14097
14098 $customerDetailsUrl = admin_url('admin.php?page=booking-package%2Findex.php&key=' . $bookingID . '&calendar=' . $accountKey . '&month=' . date('n', $unixTime) . '&day=' . date('j', $unixTime) . '&year=' . date('Y', $unixTime));
14099
14100 $reflectAdditional = 1;
14101 $reflectAdditionalTitle = null;
14102 $reflectService = 1;
14103 $reflectServiceTitle = null;
14104 $guestsList = array();
14105
14106 if (is_null($guests) === false && array_key_exists('guests', $guests) === true && is_null($guests['guests']) === false ) {
14107
14108 $reflectAdditional = intval($guests['reflectAdditional']);
14109 $reflectAdditionalTitle = $guests['reflectAdditionalTitle'];
14110 $reflectService = intval($guests['reflectService']);
14111 $reflectServiceTitle = $guests['reflectServiceTitle'];
14112 $guestsList = $guests['guests'];
14113
14114 }
14115
14116 if ($reflectAdditional == 0) {
14117
14118 $reflectAdditional = 1;
14119
14120 }
14121
14122 $emailSubject = null;
14123 $emailBody = null;
14124 foreach ((array) $notificationContents as $contentsKey => $contents) {
14125
14126 $site_name = get_option($this->prefix."site_name", "");
14127 $dateFormat = intval(get_option($this->prefix."dateFormat", 0));
14128 $positionOfWeek = get_option($this->prefix."positionOfWeek", "before");
14129 $date = $this->dateFormat($dateFormat, $positionOfWeek, $unixTime, $scheduleTitle, true, false, 'object');
14130 $contents = str_replace('[date]', $date['date'] . ' ' . $date['time'], $contents);
14131 $contents = str_replace('[bookingDate]', $date['date'], $contents);
14132 $contents = str_replace('[bookingTime]', $date['time'], $contents);
14133 $contents = str_replace('[bookingTitle]', $date['title'], $contents);
14134
14135 if ($positionTimeDate == 'dateTime') {
14136
14137 $contents = str_replace('[bookingDateAndTime]', $date['date'] . ', ' . $date['time'] . ' ' . $date['title'], $contents);
14138
14139 } else {
14140
14141 if (!empty($date['title'])) {
14142
14143 $date['title'] = ' ' . $date['title'];
14144
14145 }
14146 $contents = str_replace('[bookingDateAndTime]', $date['time'] . $date['title'] . ', ' . $date['date'], $contents);
14147
14148 }
14149
14150
14151 $timestamp = $this->dateFormat($dateFormat, $positionOfWeek, $timestampForUnixTime, '', true, false, 'text');
14152 $contents = str_replace('[receptionDate]', $timestamp, $contents);
14153 $contents = str_replace('[submissionDate]', $timestamp, $contents);
14154
14155 if ($calendarAccount['type'] == 'hotel') {
14156
14157 $checkInDate = $this->dateFormat($dateFormat, $positionOfWeek, $accommodationDetails['checkIn'], $scheduleTitle, false, false, 'text');
14158 $contents = str_replace('[checkIn]', $checkInDate, $contents);
14159
14160 $checkOutDate = $this->dateFormat($dateFormat, $positionOfWeek, $accommodationDetails['checkOut'], $scheduleTitle, false, false, 'text');
14161 $contents = str_replace('[checkOut]', $checkOutDate, $contents);
14162
14163 $detailsList = $this->bookingDetailsForHotel($accountKey, $accommodationDetails, $currency, 'array');
14164 $contents = str_replace('[bookingDetails]', implode("\n", $detailsList), $contents);
14165
14166 }
14167
14168 $amount = $this->getAmount($bookingID, $calendarAccount, $accommodationDetails, $services, $guests, null, $coupon);
14169 $amount = $this->formatCost($amount, $currency);
14170 $contents = str_replace('[totalPaymentAmount]', $amount, $contents);
14171 $contents = str_replace('[totalAmount]', $amount, $contents);
14172
14173 if (intval($calendarAccount['cancellationOfBooking']) == 1 && !is_null($cancellationUri)) {
14174
14175 $contents = str_replace('[cancellationUri]', $cancellationUri, $contents);
14176 $contents = str_replace('[bookingCancellationUrl]', $cancellationUri, $contents);
14177
14178 } else {
14179
14180 $contents = str_replace('[cancellationUri]', "", $contents);
14181 $contents = str_replace('[bookingCancellationUrl]', "", $contents);
14182
14183 }
14184
14185 if (!empty($coupon) && is_array($coupon) && isset($coupon['key'])) {
14186
14187 $contents = str_replace('[couponCode]', $coupon['id'], $contents);
14188
14189 } else {
14190
14191 $contents = str_replace('[couponCode]', __('None', 'booking-package'), $contents);
14192
14193 }
14194
14195 if (!empty($coupon) && is_array($coupon) && isset($coupon['key'])) {
14196
14197 $contents = str_replace('[couponName]', $coupon['name'], $contents);
14198
14199 } else {
14200
14201 $contents = str_replace('[couponName]', __('None', 'booking-package'), $contents);
14202
14203 }
14204
14205 if (!empty($coupon) && is_array($coupon) && isset($coupon['key'])) {
14206
14207 $discountValue = $this->formatCost($coupon['value'], $currency);
14208 if ($coupon['method'] == 'multiplication') {
14209
14210 $discountValue = $coupon['value'] . '%';
14211
14212 }
14213
14214 $contents = str_replace('[couponDiscount]', $discountValue, $contents);
14215
14216 } else {
14217
14218 $contents = str_replace('[couponDiscount]', __('None', 'booking-package'), $contents);
14219
14220 }
14221
14222 if (isset($_POST['receivedUri'])) {
14223
14224 $contents = str_replace('[receivedUri]', $_POST['receivedUri'], $contents);
14225
14226 }
14227
14228 if (isset($_POST['receivedUrl'])) {
14229
14230 $contents = str_replace('[receivedUrl]', $_POST['receivedUri'], $contents);
14231
14232 }
14233
14234 $guestsDetails = array();
14235 $optionsDetails = array();
14236 if ($calendarAccount['type'] == 'hotel') {
14237
14238 if (isset($accommodationDetails['rooms']) === false) {
14239
14240 $accommodationDetails['rooms'] = array();
14241
14242 }
14243 $rooms = $accommodationDetails['rooms'];
14244 if (is_null($rooms)) {
14245
14246 $rooms = array();
14247
14248 }
14249
14250 if (count($rooms) > 0) {
14251
14252 foreach ((array) $rooms as $roomKey => $room) {
14253
14254 if (count($rooms) > 1) {
14255
14256 array_push($optionsDetails, __('Room', 'booking-package') . ': ' . ($roomKey + 1));
14257 array_push($guestsDetails, __('Room', 'booking-package') . ': ' . ($roomKey + 1));
14258
14259 }
14260 $guestsList = array();
14261 if (isset($room['guestsList'])) {
14262
14263 $guestsList = $room['guestsList'];
14264
14265 }
14266 foreach ((array) $guestsList as $key => $value) {
14267
14268 $name = $value['name'];
14269 $guests = $value['json'];
14270 for ($i = 0; $i < count($guests); $i++) {
14271
14272 if (intval($guests[$i]['selected']) == 1) {
14273
14274 if ($i === 0) {
14275
14276 array_push($guestsDetails, $name . ": " . __('Unselected', 'booking-package'));
14277
14278 } else {
14279
14280 array_push($guestsDetails, $name . ": " . $guests[$i]['name']);
14281
14282 }
14283
14284 break;
14285
14286 }
14287
14288 }
14289
14290 }
14291
14292 $optionsList = array();
14293 if (isset($room['optionsList']) === true) {
14294
14295 $optionsList = $room['optionsList'];
14296
14297 }
14298
14299 foreach ((array) $optionsList as $key => $value) {
14300
14301 $name = $value['name'];
14302 $options = $value['json'];
14303 for ($i = 0; $i < count($options); $i++) {
14304
14305 if (intval($options[$i]['selected']) == 1) {
14306
14307 if ($i === 0) {
14308
14309 array_push($optionsDetails, $name . ": " . __('Unselected', 'booking-package'));
14310
14311 } else {
14312
14313 array_push($optionsDetails, $name . ": " . $options[$i]['name']);
14314
14315 }
14316
14317 break;
14318
14319 }
14320
14321 }
14322
14323 }
14324
14325 }
14326
14327 } else {
14328
14329 $guestsList = $accommodationDetails['guestsList'];
14330 foreach ((array) $guestsList as $key => $value) {
14331
14332 $name = $value['name'];
14333 $guests = $value['json'];
14334 for($i = 0; $i < count($guests); $i++){
14335
14336 if (intval($guests[$i]['selected']) == 1) {
14337
14338 array_push($guestsDetails, $name.": ".$guests[$i]['name']);
14339 break;
14340
14341 }
14342
14343 }
14344
14345 }
14346
14347 }
14348
14349 } else if ($calendarAccount['type'] == 'day') {
14350
14351 for ($i = 0; $i < count($guestsList); $i++) {
14352
14353 $guest = $guestsList[$i];
14354 $index = intval($guest['index']);
14355 if ($index > 0) {
14356
14357 $label = $guest['name'] . ": " . $guest['json'][$index]['name'];
14358 if (intval($guest['json'][$index]['price']) > 0) {
14359
14360 $label .= ' ' . $this->formatCost(intval($guest['json'][$index]['price']), $currency);
14361
14362 }
14363
14364 array_push($guestsDetails, $label);
14365
14366 }
14367
14368 }
14369
14370 }
14371
14372 $optionsDetails = implode("\n", $optionsDetails);
14373 $contents = str_replace('[options]', $optionsDetails, $contents);
14374
14375 $guestsDetails = implode("\n", $guestsDetails);
14376 $contents = str_replace('[guests]', $guestsDetails, $contents);
14377
14378 $surchargesDetails = array();
14379 $surcharges = $accommodationDetails['taxes'];
14380 for ($i = 0; $i < count($surcharges); $i++) {
14381
14382 $tax = $surcharges[$i];
14383 if ($tax['type'] == 'surcharge' && $tax['active'] == 'true') {
14384
14385 $cost = $this->formatCost($tax['taxValue'], $currency);
14386
14387 if ($reflectAdditional > 1) {
14388
14389 #$details .= ' * ' . $reflectAdditionalTitle;
14390 $details = $tax['name'] . ': ' . $reflectAdditionalTitle . ' * ' . $cost;
14391 array_push($surchargesDetails, $details);
14392
14393 }
14394
14395 }
14396
14397 }
14398 $surchargesDetails = implode("\n", $surchargesDetails);
14399 $contents = str_replace('[surcharges]', $surchargesDetails, $contents);
14400
14401 $taxesDetails = array();
14402 $taxes = $accommodationDetails['taxes'];
14403 for ($i = 0; $i < count($taxes); $i++) {
14404
14405 $tax = $taxes[$i];
14406 if ($tax['type'] == 'tax' && $tax['active'] == 'true') {
14407
14408 $cost = $this->formatCost($tax['taxValue'], $currency);
14409 array_push($taxesDetails, $tax['name'] . ' ' . $cost);
14410
14411 }
14412
14413 }
14414 $taxesDetails = implode("\n", $taxesDetails);
14415 $contents = str_replace('[taxes]', $taxesDetails, $contents);
14416 $contents = str_replace('[id]', $bookingID, $contents);
14417 $contents = str_replace('[site_name]', $site_name, $contents);
14418
14419 $payName = $paymentMethod['locally'];
14420 if ($payId == 'stripe') {
14421
14422 $payName = $paymentMethod['stripe'];
14423
14424 } else if ($payId == 'stripe_konbini') {
14425
14426 $payName = $paymentMethod['stripe_konbini'];
14427
14428 } else if ($payId == 'stripe_paypay') {
14429
14430 $payName = $paymentMethod['stripe_paypay'];
14431
14432 } else if ($payId == 'paypal') {
14433
14434 $payName = $paymentMethod['paypal'];
14435
14436 }
14437 $contents = str_replace('[paymentMethod]', $payName, $contents);
14438
14439 if (!is_null($services)) {
14440
14441 if (is_array($services)) {
14442
14443 $detailsList = array();
14444 $detailsListExcludedGuests = array();
14445 $detailsListExcludedGuestsAndCosts = array();
14446 foreach ((array) $services as $key => $service) {
14447
14448 $responseCostInService = $this->getCostsInService($calendarAccount, $service, $guestsList);
14449 #$costs = $responseCostInService['costs'];
14450 $subtotalInService = $responseCostInService['totalCost'];
14451 $details = $service['name'];
14452 $detailsExcludedGuests = $service['name'];
14453 $detailsExcludedGuestsAndCosts = $service['name'];
14454 if ($subtotalInService > 0) {
14455
14456 $details .= ' ' . $this->formatCost($subtotalInService, $currency);
14457 $detailsExcludedGuests .= ' ' . $this->formatCost($subtotalInService, $currency);
14458
14459 }
14460
14461 if ($reflectService > 0) {
14462
14463 foreach ($responseCostInService['guests'] as $guestsInServiceKey => $guestsInService) {
14464
14465 if (isset($guestsInService['content'])) {
14466
14467 $details .= "\n " . $guestsInService['content'];
14468
14469 }
14470
14471 }
14472
14473 }
14474
14475 array_push($detailsList, $details);
14476 array_push($detailsListExcludedGuests, $detailsExcludedGuests);
14477 array_push($detailsListExcludedGuestsAndCosts, $detailsExcludedGuestsAndCosts);
14478
14479 $no = 0;
14480 foreach ((array) $service['options'] as $option) {
14481
14482 if (intval($option['selected']) == 1) {
14483
14484 $no++;
14485 $details = "#".$no." ".$option['name']." ";
14486 $detailsExcludedGuests = "#".$no." ".$option['name']." ";
14487 $detailsExcludedGuestsAndCosts = "#".$no." ".$option['name']." ";
14488 $responseCostInOption = $this->getCostsInService($calendarAccount, $option, $guestsList);
14489 #$costs = $responseCostInOption['costs'];
14490 $subtotalInOption = $responseCostInOption['totalCost'];
14491 if ($subtotalInOption > 0) {
14492
14493 $details .= ' ' . $this->formatCost($subtotalInOption, $currency);
14494 $detailsExcludedGuests .= ' ' . $this->formatCost($subtotalInOption, $currency);
14495
14496 }
14497
14498 /**
14499 if (is_int(intval($costs[0])) === true && intval($costs[0]) != 0) {
14500
14501 #$details .= $this->formatCost($option['cost'], $currency);
14502 if ($responseCostInOption['hasMultipleCosts'] === true) {
14503
14504 #$details .= ' ' . sprintf(__('%s to %s', 'booking-package'), $this->formatCost($responseCostInOption['min'], $currency), $this->formatCost($responseCostInOption['max'], $currency));
14505 #$detailsExcludedGuests .= ' ' . sprintf(__('%s to %s', 'booking-package'), $this->formatCost($responseCostInOption['min'], $currency), $this->formatCost($responseCostInOption['max'], $currency));
14506 $details .= ' ' . $this->formatCost($subtotalInOption, $currency);
14507 $detailsExcludedGuests .= ' ' . $this->formatCost($subtotalInOption, $currency);
14508
14509 } else {
14510
14511 #$details .= ' ' . $this->formatCost($costs[0], $currency);
14512 #$detailsExcludedGuests .= ' ' . $this->formatCost($costs[0], $currency);
14513 $details .= ' ' . $this->formatCost($subtotalInOption, $currency);
14514 $detailsExcludedGuests .= ' ' . $this->formatCost($subtotalInOption, $currency);
14515
14516 }
14517
14518 }
14519 **/
14520
14521 if ($reflectService > 0) {
14522
14523 foreach ($responseCostInOption['guests'] as $guestsInServiceKey => $guestsInService) {
14524
14525 if (isset($guestsInService['content'])) {
14526
14527 $details .= "\n " . $guestsInService['content'];
14528
14529 }
14530
14531 }
14532
14533 }
14534
14535 array_push($detailsList, $details);
14536 array_push($detailsListExcludedGuests, $detailsExcludedGuests);
14537 array_push($detailsListExcludedGuestsAndCosts, $detailsExcludedGuestsAndCosts);
14538
14539 }
14540
14541 }
14542
14543 }
14544
14545 $contents = str_replace('[service]', implode("\n", $detailsList), $contents);
14546 $contents = str_replace('[services]', implode("\n", $detailsList), $contents);
14547 $contents = str_replace('[servicesExcludedGuests]', implode("\n", $detailsListExcludedGuests), $contents);
14548 $contents = str_replace('[servicesExcludedGuestsAndCosts]', implode("\n", $detailsListExcludedGuestsAndCosts), $contents);
14549
14550 } else {
14551
14552 $contents = str_replace('[service]', $service, $contents);
14553 $contents = str_replace('[services]', $service, $contents);
14554 $contents = str_replace('[servicesExcludedGuests]', implode("\n", $detailsListExcludedGuests), $contents);
14555 $contents = str_replace('[servicesExcludedGuestsAndCosts]', implode("\n", $detailsListExcludedGuestsAndCosts), $contents);
14556
14557 }
14558
14559 }
14560
14561 $visitorEmail = array();
14562 $visitorSMS = array();
14563 $content = "";
14564 for ($i = 0; $i < count($form); $i++) {
14565
14566 if ($form[$i]['active'] == '') {
14567
14568 continue;
14569
14570 }
14571
14572 $value = $form[$i]['value'];
14573 if (is_array($value)) {
14574
14575 $value = implode("\r\n", $form[$i]['value']);
14576
14577 }
14578
14579 if ($emailFormat == "text") {
14580
14581 $content .= $form[$i]['name'] . "\r\n" . $value . "\r\n";
14582
14583 } else {
14584
14585 $content .= '<div style="width: 100%; display: table;"><div style="width: 30%; display: table-cell; vertical-align: middle;">' . $form[$i]['name'] . '</div><div style="width: 70%; display: table-cell; vertical-align: middle;">' . $value . '</div></div>';
14586
14587 }
14588
14589 if ($form[$i]['isEmail'] == 'true' && !empty($form[$i]['value'])) {
14590
14591 if (array_search($form[$i]['value'], $response['visitorEmail']) === false) {
14592
14593 array_push($response['visitorEmail'], $form[$i]['value']);
14594
14595 }
14596
14597 }
14598
14599 if (isset($form[$i]['isSMS']) && $form[$i]['isSMS'] == 'true' && !empty($form[$i]['value'])) {
14600
14601 if (array_search($form[$i]['value'], $response['visitorSMS']) === false) {
14602
14603 array_push($response['visitorSMS'], $form[$i]['value']);
14604
14605 }
14606
14607 }
14608
14609 }
14610
14611 $contents = str_replace('[customerDetails]', $content, $contents);
14612
14613 for ($i = 0; $i < count($form); $i++) {
14614
14615 $id = '[' . $form[$i]['id'] . ']';
14616 $value = $form[$i]['value'];
14617 if (is_array($value)) {
14618
14619 $value = implode("\r\n", $form[$i]['value']);
14620
14621 }
14622
14623 $contents = str_replace($id, $value, $contents);
14624
14625 }
14626
14627 //if ($contentsKey == 'body' && $emailKey == 'admin' && $email_id != 'booking_deleted_notification') {
14628 if ($contentsKey == 'body' && $emailKey == 'admin') {
14629
14630 $contents = str_replace('[customerDetailsUrl]', $customerDetailsUrl, $contents);
14631
14632 }
14633
14634 $contents = stripslashes($contents);
14635
14636 if ($contentsKey == 'subject') {
14637
14638 $emailSubject = $contents;
14639
14640 } else {
14641
14642 $emailBody = $contents;
14643
14644 }
14645
14646 }
14647
14648
14649 $response['emailSubject'] = $emailSubject;
14650 $response['emailBody'] = $emailBody;
14651 $response['servicesDetails'] = $servicesDetails;
14652 return $response;
14653
14654 }
14655
14656 private function createEmailMessage($accountKey, $email_id, $bookingID) {
14657
14658 global $wpdb;
14659
14660 $enableEmail = 0;
14661 $enableSMS = 0;
14662 $attachICalendarInEmail = 0;
14663 $notifyAdministrator = 1;
14664 $calendarAccount = $this->getCalendarAccount($accountKey);
14665 $to = trim( get_option($this->prefix . "email_to", null) );
14666 if (!empty($to) || !empty($calendarAccount['email_to'])) {
14667
14668 $to = explode(',', str_replace(" ", "", $to) );
14669 $calendarToEmail = array();
14670 if (!empty($calendarAccount['email_to']) ) {
14671
14672 $calendarToEmail = explode(',', str_replace(" ", "", trim($calendarAccount['email_to']) ) );
14673
14674 }
14675 $to_emails = array_merge($to, $calendarToEmail);
14676 $to_emails = array_values($to_emails);
14677 $to_emails = array_unique($to_emails);
14678 $to_emails = array_filter($to_emails, function ($value) {
14679
14680 return $value !== null && trim($value) !== '';
14681
14682 });
14683 $to = implode(',', $to_emails);
14684
14685 }
14686
14687 if (empty($to)) {
14688
14689 $to = get_bloginfo('admin_email');
14690
14691 }
14692
14693 $from = $this->emailFormat(get_option($this->prefix . "email_from", null), get_option($this->prefix . "email_title_from", null));
14694 if (!empty($calendarAccount['email_from'])) {
14695
14696 $from = $this->emailFormat($calendarAccount['email_from'], $calendarAccount['email_from_title']);
14697
14698 }
14699
14700 if (empty($from)) {
14701
14702 $from = $this->emailFormat(get_bloginfo('admin_email'), get_bloginfo('name'));
14703
14704 }
14705
14706 $customer = $this->getCustomer($bookingID, null);
14707 $local = $customer['locale'];
14708 $table_name = $wpdb->prefix . "booking_package_email_settings";
14709 $sql = $wpdb->prepare(
14710 "SELECT * FROM " . $table_name . " WHERE `accountKey` = %d AND `mail_id` = %s;",
14711 array(intval($accountKey), $email_id)
14712 );
14713 $row = $wpdb->get_row($sql, ARRAY_A);
14714 $event_data = array('ical_subject' => '', 'ical_location' => '', 'ical_description' => '');
14715 $string_array = array('customer_email_subject' => $row['subject'], 'customer_email_body' => $row['content'], 'admin_email_subject' => $row['subjectForAdmin'], 'admin_email_body' => $row['contentForAdmin'], 'ical_subject' => $row['subjectForIcalendar'], 'ical_location' => $row['locationForIcalendar'], 'ical_description' => $row['contentForIcalendar'], 'options' => array() );
14716 $translated_texts = apply_filters('booking_package_get_translate_text', $string_array, 'notification', $row['mail_id'], intval($accountKey), $local);
14717 if (is_array($translated_texts) && array_key_exists('customer_email_subject', $translated_texts) && array_key_exists('customer_email_body', $translated_texts) && array_key_exists('admin_email_subject', $translated_texts) && array_key_exists('admin_email_body', $translated_texts) && array_key_exists('ical_subject', $translated_texts) && array_key_exists('ical_location', $translated_texts) && array_key_exists('ical_description', $translated_texts) ) {
14718
14719 $row['subject'] = $translated_texts['customer_email_subject'];
14720 $row['content'] = $translated_texts['customer_email_body'];
14721 $row['subjectForAdmin'] = $translated_texts['admin_email_subject'];
14722 $row['contentForAdmin'] = $translated_texts['admin_email_body'];
14723
14724 $event_data['ical_subject'] = $translated_texts['ical_subject'];
14725 $event_data['ical_location'] = $translated_texts['ical_location'];
14726 $event_data['ical_description'] = $translated_texts['ical_description'];
14727
14728 }
14729
14730
14731 $emailSubject = $row['subject'];
14732 $emailBody = $row['content'];
14733 $emailFormat = $row['format'];
14734 $enableEmail = intval($row['enable']);
14735 $enableSMS = intval($row['enableSMS']);
14736 $attachICalendarInEmail = intval($row['attachICalendar']);
14737 $notifyAdministrator = intval($row['notifyAdministrator']);
14738 if (empty($row['subjectForAdmin'])) {
14739
14740 $row['subjectForAdmin'] = $row['subject'];
14741
14742 }
14743
14744 if (empty($row['contentForAdmin'])) {
14745
14746 $row['contentForAdmin'] = $row['content'];
14747
14748 }
14749
14750 $sendEamilList = array(
14751 'visitor' => array("subject" => $row['subject'], 'content' => $row['content']),
14752 'admin' => array("subject" => $row['subjectForAdmin'], 'content' => $row['contentForAdmin']),
14753 );
14754
14755 if ($enableEmail == 0 && $enableSMS == 0) {
14756
14757 return null;
14758
14759 }
14760
14761
14762 /**
14763 for ($i = 0; $i < count($email_id); $i++) {
14764
14765 $sql = $wpdb->prepare(
14766 "SELECT * FROM " . $table_name . " WHERE `accountKey` = %d AND `mail_id` = %s;",
14767 array(intval($accountKey), $email_id[$i])
14768 );
14769 $row = $wpdb->get_row($sql, ARRAY_A);
14770
14771 $string_array = array('customer_email_subject' => $row['subject'], 'customer_email_body' => $row['content'], 'admin_email_subject' => $row['subjectForAdmin'], 'admin_email_body' => $row['contentForAdmin'], 'options' => array() );
14772 $translated_texts = apply_filters('booking_package_get_translate_text', $string_array, 'notification', $row['mail_id'], intval($accountKey), get_locale() );
14773 if (is_array($translated_texts) && array_key_exists('customer_email_subject', $translated_texts) && array_key_exists('customer_email_body', $translated_texts) && array_key_exists('admin_email_subject', $translated_texts) && array_key_exists('admin_email_body', $translated_texts) ) {
14774
14775 $row['subject'] = $translated_texts['customer_email_subject'];
14776 $row['content'] = $translated_texts['customer_email_body'];
14777 $row['subjectForAdmin'] = $translated_texts['admin_email_subject'];
14778 $row['contentForAdmin'] = $translated_texts['admin_email_body'];
14779
14780 }
14781
14782
14783 $emailSubject = $row['subject'];
14784 $emailBody = $row['content'];
14785 $emailFormat = $row['format'];
14786 $enableEmail = intval($row['enable']);
14787 $enableSMS = intval($row['enableSMS']);
14788 $attachICalendarInEmail = intval($row['attachICalendar']);
14789 $notifyAdministrator = intval($row['notifyAdministrator']);
14790 if (empty($row['subjectForAdmin'])) {
14791
14792 $row['subjectForAdmin'] = $row['subject'];
14793
14794 }
14795
14796 if (empty($row['contentForAdmin'])) {
14797
14798 $row['contentForAdmin'] = $row['content'];
14799
14800 }
14801
14802 $sendEamilList = array(
14803 'visitor' => array("subject" => $row['subject'], 'content' => $row['content']),
14804 'admin' => array("subject" => $row['subjectForAdmin'], 'content' => $row['contentForAdmin']),
14805 );
14806
14807 if ($enableEmail == 0 && $enableSMS == 0) {
14808
14809 return null;
14810
14811 }
14812
14813 }
14814 **/
14815
14816 if ($notifyAdministrator === 0) {
14817
14818 unset($sendEamilList['admin']);
14819
14820 }
14821
14822 foreach ((array) $sendEamilList as $emailKey => $target) {
14823
14824 $emailSubject = $target['subject'];
14825 $emailSubject = stripslashes($emailSubject);
14826 $emailBody = $target['content'];
14827
14828 $emailBody = htmlspecialchars_decode($emailBody, ENT_QUOTES|ENT_HTML5);
14829 if ($emailFormat != "text") {
14830
14831 $emailBody = str_replace(PHP_EOL, '', $emailBody);
14832
14833 }
14834
14835 if (strpos($emailBody, '[stop_email]') !== false) {
14836
14837 continue;
14838
14839 }
14840
14841 $emailData = array('subject' => $emailSubject, 'body' => $emailBody);
14842
14843 $notificationContents = $this->getNotificationContents($calendarAccount, $customer, $email_id, $emailKey, $emailData, $emailFormat);
14844 $emailSubject = $notificationContents['emailSubject'];
14845 $emailBody = $notificationContents['emailBody'];
14846 $visitorEmail = $notificationContents['visitorEmail'];
14847 $visitorSMS = $notificationContents['visitorSMS'];
14848
14849 $emailSubject = str_replace(array("\r\n", "\r", "\n"), '', $emailSubject);
14850
14851 $headers = array("From: " . $from . "\r\n", "Return-Path: " . $from . "\r\n", "Reply-To: " . $from . "\r\n");
14852 $attachments = array();
14853 $attachICalendar = array();
14854 if ($attachICalendarInEmail === 1) {
14855
14856 #array_push($headers, 'Content-Disposition: attachment; filename=' . $attachICalendar['temp_file_name']);
14857 $ical = new booking_package_iCal($this->prefix, $this->pluginName, $this->currencies);
14858 $attachICalendar = $ical->attachICalendar($calendarAccount, $event_data, $email_id, $bookingID, null, 'attach');
14859 if ($attachICalendar['status'] === true) {
14860
14861 array_push($attachments, $attachICalendar['temp_file']);
14862
14863 }
14864
14865 }
14866
14867 if ($emailFormat == "text") {
14868
14869 $emailBody = strip_tags($emailBody);
14870
14871 } else {
14872
14873 array_push($headers, "Content-Type: text/html; charset=UTF-8");
14874 $bodyStyle = 'word-wrap: break-word; white-space: pre;';
14875 $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
14876 $header .= '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Booking email</title></head>';
14877 $header .= '<body style="'.$bodyStyle.'">';
14878 #$emailBody = $header.$emailBody."</body></html>";
14879
14880 }
14881
14882 $responseList = array('body' => $emailBody, 'to' => $to, 'from' => $from, 'sendVisitor' => null, 'headers' => $headers, 'visitorEmail' => $visitorEmail, 'response' => array(), 'params' => array(), 'enabledSMS' => $enableSMS);
14883 if (function_exists('mb_language')) {
14884
14885 mb_language("uni");
14886
14887 }
14888
14889 if (function_exists('mb_internal_encoding')) {
14890
14891 mb_internal_encoding("UTF-8");
14892
14893 }
14894
14895 if ($enableEmail == 1) {
14896
14897 $sendVisitor = false;
14898 if (count($visitorEmail) != 0 && $emailKey == 'visitor') {
14899
14900 $sendVisitor = wp_mail($visitorEmail, $emailSubject, $emailBody, $headers, $attachments);
14901 $responseList['sendVisitor'] = $sendVisitor;
14902
14903 } else if ($emailKey == 'admin') {
14904
14905 if (!empty($to)) {
14906
14907 $sendControl = wp_mail($to, $emailSubject, $emailBody, $headers, $attachments);
14908 $responseList['sendControl'] = $sendControl;
14909
14910 }
14911
14912 }
14913
14914
14915 }
14916
14917 if ($attachICalendarInEmail === 1 && $attachICalendar['status'] === true) {
14918
14919 unlink($attachICalendar['temp_file']);
14920
14921 }
14922
14923 if ($enableSMS == 1 && $emailKey == 'visitor') {
14924
14925 #$this->sendMessagingServices($calendarAccount, $visitorSMS, '', $emailBody);
14926 $responseList['twilioSMS'] = $this->twilioSMS($visitorSMS, $emailBody);
14927
14928 }
14929
14930 }
14931
14932 return $responseList;
14933
14934 }
14935
14936 private function sendMessagingServices($calendarAccount, $customers, $subject, $body) {
14937
14938 $messagingServices = $calendarAccount['messagingService'];
14939
14940 if ($messagingServices === 'whatsApp') {
14941
14942 $this->sendWhatsApp($customers, $body);
14943
14944 } else if ($messagingServices === 'twilio') {
14945
14946 $response = $this->twilioSMS($customers, $body);
14947
14948 }
14949
14950 }
14951
14952 private function sendWhatsApp($customers, $body) {
14953
14954 $isExtensionsValid = $this->getExtensionsValid();
14955 if ($isExtensionsValid === false) {
14956
14957 return false;
14958
14959 } else {
14960
14961 $body = str_replace(PHP_EOL, "\n", $body);
14962 $whatsApp_active = get_option($this->prefix . "whatsApp_active", 0);
14963 $whatsApp_countryCode = get_option($this->prefix . 'whatsApp_countryCode', 0);
14964 $whatsApp_phoneId = get_option($this->prefix . 'whatsApp_phoneId', 0);
14965 $whatsApp_token = get_option($this->prefix . 'whatsApp_token', 0);
14966 if (intval($whatsApp_active) === 1 && !empty($whatsApp_phoneId) && !empty($whatsApp_token)) {
14967
14968 for ($i = 0; $i < count($customers); $i++) {
14969
14970 $phoneNumber = $customers[$i];
14971 if (substr($phoneNumber, 0, 1) === '0') {
14972 $phoneNumber = substr($phoneNumber, 1);
14973 }
14974
14975 $phoneNumber = $whatsApp_countryCode . $phoneNumber;
14976 if (preg_match( '/^\+/', $customers[$i])) {
14977
14978 $phoneNumber = $customers[$i];
14979
14980 }
14981 $phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
14982 var_dump($phoneNumber);
14983
14984 $params = array(
14985 'messaging_product' => 'whatsapp',
14986 'recipient_type' => 'individual',
14987 'type' => 'text',
14988 'to' => $phoneNumber,
14989 'text' => array(
14990 'preview_url' => false,
14991 'body' => $body,
14992 )
14993 );
14994 $args = array(
14995 'method' => 'POST',
14996 'timeout' => $this->request_timeout,
14997 'body' => json_encode($params),
14998 'headers' => array(
14999 'content-type' => 'application/json',
15000 'Authorization' => 'Bearer ' . trim($whatsApp_token) .'',
15001 )
15002 );
15003 #var_dump($args);
15004 $response = wp_remote_request('https://graph.facebook.com/v17.0/' . $whatsApp_phoneId . '/messages', $args);
15005 $statusCode = wp_remote_retrieve_response_code($response);
15006 $response = json_decode(wp_remote_retrieve_body($response), true);
15007 var_dump($response);
15008
15009 }
15010
15011 }
15012
15013 }
15014
15015 }
15016
15017 private function twilioSMS($visitorSMS, $body) {
15018
15019 $body = str_replace(PHP_EOL, "\n", $body);
15020
15021 $twilio_active = get_option($this->prefix . "twilio_active", 0);
15022 $twilio_sendingMethod = get_option($this->prefix . "twilio_sendingMethod", "phoneNumber");
15023 $twilio_sid = get_option($this->prefix . "twilio_sid", null);
15024 $twilio_service_sid = get_option($this->prefix . "twilio_service_sid", null);
15025 $twilio_token = get_option($this->prefix . "twilio_token", null);
15026 $twilio_countryCode = get_option($this->prefix . "twilio_countryCode", '');
15027 $twilio_number = get_option($this->prefix . "twilio_number", null);
15028 if (intval($twilio_active) == 1 && !empty($twilio_sid) && !empty($twilio_token)) {
15029
15030 for ($i = 0; $i < count($visitorSMS); $i++) {
15031
15032 $phoneNumber = $twilio_countryCode . $visitorSMS[$i];
15033 if (preg_match( '/^\+/', $visitorSMS[$i])) {
15034
15035 $phoneNumber = $visitorSMS[$i];
15036
15037 }
15038 $phoneNumber = preg_replace('/[- ()]/', '', $phoneNumber);
15039
15040 $send = true;
15041 $params = array();
15042 if ($twilio_sendingMethod == 'phoneNumber' && !empty($twilio_number)) {
15043
15044 $twilio_number = preg_replace('/[- ()]/', '', $twilio_number);
15045 $params = array('Body' => $body, 'From' => $twilio_number, 'To' => $phoneNumber);
15046
15047 } else if ($twilio_sendingMethod == 'senderID') {
15048
15049 $params = array('Body' => $body, 'To' => $phoneNumber, 'MessagingServiceSid' => $twilio_service_sid);
15050
15051 } else {
15052
15053 $send = false;
15054
15055 }
15056
15057 if ($send === true) {
15058
15059 $args = array(
15060 'method' => 'POST',
15061 'timeout' => $this->request_timeout,
15062 'body' => $params,
15063 'headers' => array(
15064 'Authorization' => 'Basic ' . base64_encode($twilio_sid . ':' . $twilio_token)
15065 )
15066 );
15067 $response = wp_remote_request("https://api.twilio.com/2010-04-01/Accounts/". $twilio_sid . "/Messages.json", $args);
15068 $statusCode = wp_remote_retrieve_response_code($response);
15069 $response = json_decode(wp_remote_retrieve_body($response), true);
15070
15071 } else {
15072
15073 #return false;
15074
15075 }
15076
15077 }
15078
15079 return true;
15080
15081 } else {
15082
15083 return false;
15084
15085 }
15086
15087 }
15088
15089 public function sendMail($user_email, $subject, $body, $emailFormat = 'text', $accountKey = null){
15090
15091 $to = get_option($this->prefix . "email_to", null);
15092 $from = $this->emailFormat(get_option($this->prefix . "email_from", null), get_option($this->prefix . "email_title_from", null));
15093
15094 if (!is_null($accountKey)) {
15095
15096 $calendarAccount = $this->getCalendarAccount($accountKey);
15097 if (!empty($calendarAccount['email_to'])) {
15098
15099 $to = $calendarAccount['email_to'];
15100
15101 }
15102
15103 if (!empty($calendarAccount['email_from'])) {
15104
15105 $from = $this->emailFormat($calendarAccount['email_from'], $calendarAccount['email_from_title']);
15106
15107 }
15108
15109 }
15110
15111 if (empty($to)) {
15112
15113 $to = get_bloginfo('admin_email');
15114
15115 }
15116
15117 if (empty($from)) {
15118
15119 $from = $this->emailFormat(get_bloginfo('admin_email'), get_bloginfo('name'));
15120
15121 }
15122
15123 $headers = array("From: ".$from."\r\n", "Return-Path: ".$from."\r\n", "Reply-To: ".$from."\r\n");
15124 #$headers = array("From: " . $from . "\r\n", "Reply-To: " . $from . "\r\n");
15125 $responseList = array('body' => $body, 'to' => $to, 'from' => $from, 'sendVisitor' => null, 'headers' => $headers, 'visitorEmail' => null, 'response' => array(), 'params' => array());
15126
15127 if (function_exists('mb_language')) {
15128
15129 mb_language("uni");
15130
15131 }
15132
15133 if (function_exists('mb_internal_encoding')) {
15134
15135 mb_internal_encoding("UTF-8");
15136
15137 }
15138
15139 $sendVisitor = false;
15140 $sendVisitor = wp_mail($user_email, $subject, $body, $headers);
15141 $responseList['sendVisitor'] = $sendVisitor;
15142 return $responseList;
15143
15144 }
15145
15146
15147
15148 public function scriptError($errors) {
15149
15150 global $wpdb;
15151 $params = array();
15152 $date = date('U') - (1440 * 60);
15153
15154 if (isset($errors['source']) === false) {
15155
15156 $errors['source'] = '';
15157
15158 }
15159
15160 $table_name = $wpdb->prefix . "booking_package_error";
15161 $sql = $wpdb->prepare(
15162 "SELECT `key` FROM `" . $table_name . "` WHERE `date` > %d AND `message` = %s;",
15163 array(intval($date), sanitize_textarea_field($errors['msg']))
15164 );
15165 $row = $wpdb->get_row($sql, ARRAY_A);
15166
15167 if (is_null($row)) {
15168
15169 $wpdb->insert(
15170 $table_name,
15171 array(
15172 'file' => sanitize_text_field($errors['file']),
15173 'url' => sanitize_text_field($errors['url']),
15174 'line' => intval($errors['line']),
15175 'col' => intval($errors['col']),
15176 'code' => sanitize_text_field($errors['code']),
15177 'version' => sanitize_text_field($errors['version']),
15178 'browser' => sanitize_text_field($errors['browser']),
15179 'message' => sanitize_textarea_field($errors['msg']),
15180 'date' => intval(date('U')),
15181 ),
15182 array('%s', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d')
15183 );
15184
15185 $url = BOOKING_PACKAGE_EXTENSION_URL;
15186 $response = array('status' => 'success', 'url' => $url);
15187
15188 $params = array(
15189 'mode' => 'scriptError',
15190 'type' => sanitize_text_field($errors['type']),
15191 'url' => sanitize_text_field($errors['url']),
15192 'file' => sanitize_text_field($errors['file']),
15193 'msg' => sanitize_text_field($errors['msg']),
15194 'line' => sanitize_text_field($errors['line']),
15195 'col' => sanitize_text_field($errors['col']),
15196 'version' => sanitize_text_field($errors['version']),
15197 'code' => sanitize_text_field($errors['code']),
15198 'browser' => sanitize_text_field($errors['browser']),
15199 'source' => sanitize_text_field($errors['source']),
15200 'page' => $errors['page'],
15201 'error' => $errors['error'],
15202 );
15203
15204 if (isset($errors['responseText'])) {
15205
15206 $params['responseText'] = $errors['responseText'];
15207
15208 }
15209
15210 if (isset($params['message'])) {
15211
15212 $params['msg'] = sanitize_text_field($errors['message']);
15213
15214 }
15215
15216 if (isset($errors['name'])) {
15217
15218 $params['name'] = sanitize_text_field($errors['name']);
15219
15220 }
15221
15222 if (isset($errors['values'])) {
15223
15224 $params['values'] = sanitize_text_field($errors['values']);
15225
15226 }
15227
15228 if (intval($params['line']) > 0 && empty($params['file']) === false) {
15229
15230 $response['params'] = $params;
15231
15232 $args = array(
15233 'method' => 'POST',
15234 'timeout' => $this->request_timeout,
15235 'body' => $params
15236 );
15237 $response = wp_remote_request("https://saasproject.net/lib/scriptError.php", $args);
15238 $statusCode = wp_remote_retrieve_response_code($response);
15239 $response = json_decode(wp_remote_retrieve_body($response), true);
15240 $params['sendStatus'] = true;
15241
15242 }
15243
15244 } else {
15245
15246 $params['sendStatus'] = false;
15247
15248 }
15249
15250 return $params;
15251
15252 }
15253
15254 public function changeMaxAccountScheduleDay(){
15255
15256 global $wpdb;
15257 $maxAccountScheduleDay = get_option($this->prefix."maxAccountScheduleDay", 14);
15258 $unavailableDaysFromToday = get_option($this->prefix."unavailableDaysFromToday", 1);
15259
15260 $table_name = $wpdb->prefix . "booking_package_calendar_accounts";
15261 #$sql = $wpdb->prepare("SELECT * FROM `".$table_name."`;", array());
15262 $rows = $wpdb->get_results("SELECT * FROM `".$table_name."`;", ARRAY_A);
15263 foreach ((array) $rows as $row) {
15264
15265 $bool = $wpdb->update(
15266 $table_name,
15267 array(
15268 'maxAccountScheduleDay' => intval($maxAccountScheduleDay),
15269 'unavailableDaysFromToday' => intval($unavailableDaysFromToday),
15270 ),
15271 array('key' => intval($row['key'])),
15272 array('%d', '%d'),
15273 array('%d')
15274 );
15275
15276 }
15277
15278 }
15279
15280 public function booking_notification() {
15281
15282 global $wpdb;
15283 $calendarAccountList = $this->getCalendarAccountListData();
15284 for ($i = 0; $i < count($calendarAccountList); $i++) {
15285
15286 $calendarAccount = $calendarAccountList[$i];
15287 if ($calendarAccount['status'] != 'open') {
15288
15289 continue;
15290
15291 }
15292
15293 date_default_timezone_set($calendarAccount['timezone']);
15294 $current_reminder_notification_time = intval($calendarAccount['bookingReminder']);
15295 $reminder_notification_time = apply_filters( 'booking_package_override_reminder_notification_time', $current_reminder_notification_time, intval($calendarAccount['key']) );
15296 if ( !is_numeric( $reminder_notification_time ) || $reminder_notification_time < 60 || $reminder_notification_time % 60 !== 0 ) {
15297
15298 $reminder_notification_time = $current_reminder_notification_time;
15299
15300 } else {
15301
15302 $reminder_notification_time = intval($reminder_notification_time);
15303
15304 }
15305
15306 $unixTime = date('U') + $reminder_notification_time * 60;
15307 $month = date('m', $unixTime);
15308 $day = date('d', $unixTime);
15309 $year = date('Y', $unixTime);
15310 $hour = date('H', $unixTime);
15311
15312 $table_name = $wpdb->prefix . "booking_package_email_settings";
15313 $sql = $wpdb->prepare(
15314 "SELECT * FROM ".$table_name." WHERE `accountKey` = %d AND `mail_id` = %s;",
15315 array(intval($calendarAccount['key']), 'booking_reminder_notification')
15316 );
15317 $row = $wpdb->get_row($sql, ARRAY_A);
15318 if (!empty($row) && intval($row['enable']) == 0 && intval($row['enableSMS']) == 0) {
15319
15320 continue;
15321
15322 }
15323
15324 $table_name = $wpdb->prefix . "booking_package_booked_customers";
15325 $sql = $wpdb->prepare(
15326 "SELECT * FROM `" . $table_name . "` WHERE `status` = 'approved' AND `bookingReminder` = 0 AND `accountKey` = %d AND `scheduleUnixTime` >= %d AND `scheduleUnixTime` <= %d;",
15327 array(
15328 intval($calendarAccount['key']),
15329 intval(mktime($hour, 0, 0, $month, $day, $year)),
15330 intval(mktime($hour, 59, 59, $month, $day, $year)),
15331 )
15332 );
15333 $rows = $wpdb->get_results($sql, ARRAY_A);
15334 if (!is_null($rows)) {
15335
15336 foreach ((array) $rows as $row) {
15337
15338 $coupon = null;
15339 if (isset($row['coupon']) && !empty($row['coupon'])) {
15340
15341 $coupon = json_decode($row['coupon'], true);
15342
15343 }
15344
15345 $responseGuests = $this->jsonDecodeForGuests($row['guests']);
15346 $servicesDetails = $this->getSelectedServices($calendarAccount, json_decode($row['options'], true), $responseGuests['guests'], "options", $coupon, $row['applicantCount'], false);
15347 $services = $servicesDetails['object'];
15348
15349 $email = $this->createEmailMessage($calendarAccount['key'], 'booking_reminder_notification', intval($row['key']));
15350
15351 $wpdb->query("START TRANSACTION");
15352 #$wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
15353 try {
15354
15355 $bool = $wpdb->update(
15356 $table_name,
15357 array('bookingReminder' => 1),
15358 array('key' => intval($row['key'])),
15359 array('%d'),
15360 array('%d')
15361 );
15362 $wpdb->query('COMMIT');
15363 #$wpdb->query('UNLOCK TABLES');
15364
15365 } catch (Exception $e) {
15366
15367 $wpdb->query('ROLLBACK');
15368 #$wpdb->query('UNLOCK TABLES');
15369
15370 }/** finally {
15371
15372 $wpdb->query('UNLOCK TABLES');
15373
15374 }**/
15375
15376 }
15377
15378 }
15379
15380 }
15381
15382 }
15383
15384 private function jsonDecodeForGuests($json) {
15385
15386 $responseGuests = json_decode($json, true);
15387 if (isset($responseGuests['guests']) === false) {
15388
15389 $responseGuests['guests'] = null;
15390
15391 }
15392
15393 return $responseGuests;
15394
15395 }
15396
15397 public function getCustomer($bookingID, $token = null) {
15398
15399 global $wpdb;
15400 $table_name = $wpdb->prefix . "booking_package_booked_customers";
15401 $sql = $wpdb->prepare("SELECT * FROM `" . $table_name . "` WHERE `key` = %d;", array(intval($bookingID)));
15402 $customer = $wpdb->get_row($sql, ARRAY_A);
15403 return $customer;
15404
15405 }
15406
15407 public function deleteCustomers() {
15408
15409 $period = get_option($this->prefix . 'dataRetentionPeriod', 0);
15410 if (intval($period) <= 0) {
15411
15412 return null;
15413
15414 }
15415
15416 $periodUnixTime = date('U') - ($period * 1440 * 60);
15417
15418 global $wpdb;
15419 $table_name = $wpdb->prefix . "booking_package_booked_customers";
15420 $wpdb->query("START TRANSACTION");
15421 #$wpdb->query("LOCK TABLES `" . $table_name . "` WRITE");
15422 try {
15423
15424 $sql = $wpdb->prepare(
15425 "DELETE FROM `" . $table_name . "` WHERE `scheduleUnixTime` <= %d;",
15426 array(intval($periodUnixTime))
15427 );
15428 $wpdb->query($sql);
15429 $wpdb->query('COMMIT');
15430 #$wpdb->query('UNLOCK TABLES');
15431
15432 } catch (Exception $e) {
15433
15434 $wpdb->query('ROLLBACK');
15435 #$wpdb->query('UNLOCK TABLES');
15436
15437 }/** finally {
15438
15439 $wpdb->query('UNLOCK TABLES');
15440
15441 }**/
15442
15443 }
15444
15445 public function getOnlyNumbers($value) {
15446
15447 if (function_exists('mb_convert_kana')) {
15448
15449 $value = mb_convert_kana($value, 'n');
15450
15451 }
15452 $value = preg_replace('/[^0-9]/', '', $value);
15453 return $value;
15454
15455 }
15456
15457 public function requestAjaxFrontEnd($prefix, $mode) {
15458
15459 $response = array('status' => 'error', 'mode' => $mode);
15460
15461 if ($mode == $prefix . 'getReservationData') {
15462
15463 $response = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), false, true);
15464
15465 }
15466
15467 if ($mode == $prefix . 'sendVerificationCode') {
15468
15469 $response = $this->sendVerificationCode();
15470
15471 }
15472
15473 if ($mode == $prefix . 'checkVerificationCode') {
15474
15475 $response = $this->checkVerificationCode();
15476
15477 }
15478
15479 if ($mode == 'getReservationData') {
15480
15481 $response = $this->getReservationData(intval($_POST['month']), intval($_POST['day']), intval($_POST['year']), false, true);
15482
15483 }
15484
15485 if ($mode == 'serachCoupons') {
15486
15487 $response = $this->serachCoupons(intval($_POST['unixTime']), $_POST['couponID'], intval($_POST['accountKey']));
15488
15489 }
15490
15491 if ($mode == 'intentForStripe') {
15492
15493 $response = $this->intentForStripe();
15494
15495 }
15496
15497 if ($mode == 'intentForStripeExpressCheckout') {
15498
15499 $response = $this->intentForStripeExpressCheckout();
15500
15501 }
15502
15503 if ($mode == 'intentForStripeKonbini') {
15504
15505 $response = $this->intentForStripeKonbini();
15506
15507 }
15508
15509 if ($mode == 'intentForStripePayPay') {
15510
15511 $response = $this->intentForStripePayPay();
15512
15513 }
15514
15515 if ($mode == 'updateIntentForStripe') {
15516
15517 $response = $this->updateIntentForStripe();
15518
15519 }
15520
15521 if ($mode == 'sendBooking') {
15522
15523 $response = $this->sendBooking();
15524
15525 }
15526
15527 if ($mode == 'scriptError') {
15528
15529 $response = $this->scriptError($_POST);
15530
15531 }
15532
15533 if ($mode == 'createUser') {
15534
15535 $response = $this->createUser(0, intval($_POST['accountKey']));
15536
15537 }
15538
15539 if ($mode == 'user_login_for_frontend') {
15540
15541 $response = $this->user_login_for_frontend($_POST['user_login'], $_POST['user_password'], $_POST['remember']);
15542
15543 }
15544
15545 if ($mode == 'logout') {
15546
15547 $response = $this->logout();
15548
15549 }
15550
15551 if ($mode == 'updateUser') {
15552
15553 $response = $this->updateUser(0, $_POST['accountKey']);
15554
15555 }
15556
15557 if ($mode == 'createCustomer') {
15558
15559 $response = $this->createCustomer();
15560
15561 }
15562
15563 if ($mode == 'deleteSubscription') {
15564
15565 $response = $this->deleteSubscription($_POST['product']);
15566
15567 }
15568
15569 if ($mode == 'deleteUser') {
15570
15571 $response = $this->deleteUser(0);
15572
15573 }
15574
15575 if ($mode == 'cancelBookingData' && isset($_POST['key']) && isset($_POST['token'])) {
15576
15577 $response = $this->cancelBookingData(intval($_POST['key']), $_POST['token'], 'canceled');
15578
15579 }
15580
15581 if ($mode == 'getUsersBookedList') {
15582
15583 $user = $this->get_user();
15584 if (intval($user['status']) == 1 && intval($user['user']['current_member_id']) == intval($_POST['user_id'])) {
15585
15586 $response = $this->getUsersBookedList($_POST['user_id'], $_POST['locale'], intval($_POST['offset']), true);
15587 $response['reload'] = 0;
15588
15589 } else {
15590
15591 $response = array('status' => 'error', 'reload' => 1);
15592
15593 }
15594
15595 }
15596
15597 if ($mode == 'cancelUserBooking') {
15598
15599 $user = $this->get_user();
15600 if (intval($user['status']) == 1 && intval($user['user']['current_member_id']) == intval($_POST['user_id'])) {
15601
15602 $response = $this->updateStatus(intval($_POST['key']), $_POST['token'], 'canceled');
15603 $response['reload'] = 0;
15604
15605 } else {
15606
15607 $response = array('status' => 'error', 'reload' => 1);
15608
15609 }
15610
15611 }
15612
15613 return $response;
15614
15615 }
15616
15617 }
15618
15619
15620
15621
15622
15623
15624 ?>