PluginProbe
WP Directory Kit / 1.5.7
WP Directory Kit v1.5.7
1.5.9 1.5.7 1.5.6 1.5.5 1.5.4 1.5.3 trunk 1.1.0 1.1.6 1.1.8 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 1.3.6 1.3.8 All 37 releases
wpdirectorykit / application / helpers / Basic.php

Basic.php in WP Directory Kit 1.5.7, at application/helpers/Basic.php

5,433 lines 211.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if ( ! defined( 'ABSPATH' ) ) {
4 exit; // Exit if accessed directly.
5 }
6
7 function wdk_generate_fields($fields, $db_data, $form = NULL)
8 {
9 if(is_array($fields))
10 foreach($fields as $field)
11 {
12 $field = (object) $field;
13
14 $field_type = $field->field_type;
15
16 $field_view_path = WPDIRECTORYKIT_PATH.'application/views/fields_edit/'.$field_type.'.php';
17
18 if(file_exists($field_view_path))
19 {
20 include $field_view_path;
21 }
22 else
23 {
24 echo __('Missing VIEW file:', 'wpdirectorykit').' '.esc_html($field_type).'.php';
25 }
26 }
27 }
28
29 if ( ! function_exists('wdk_generate_search_form'))
30 {
31 function wdk_generate_search_form($form_id=1, $subfolder='', $print = TRUE, $predefinedfields_query = array())
32 {
33 /* load WMVC data */
34 $WMVC = &wdk_get_instance();
35 $WMVC->model('searchform_m');
36 $WMVC->model('field_m');
37 $output = '';
38
39 /* get WMVC form data */
40 $fields = $WMVC->searchform_m->get($form_id, TRUE);
41 $user_fields = NULL;
42
43 /* get WMVC form fields */
44 if(is_object($fields))
45 $user_fields = json_decode($fields->searchform_json);
46 /* generate WMVC form fields html */
47 if(is_array($user_fields))
48 foreach($user_fields as $used_field)
49 {
50
51 if($used_field->field_id == 'cat') {
52 $field = array(
53 "idfield" => 'category',
54 "field_type" => 'CATEGORY',
55 "field_label" => __('Category', 'wpdirectorykit'),
56 "prefix" => '',
57 "suffix" => '',
58 "values_list" => '',
59 "placeholder" => '',
60 );
61 }else if($used_field->field_id == 'loc') {
62 $field = array(
63 "idfield" => 'location',
64 "field_type" => 'LOCATION',
65 "field_label" => __('Location', 'wpdirectorykit'),
66 "prefix" => '',
67 "suffix" => '',
68 "values_list" => '',
69 "placeholder" => '',
70 );
71 }else if($used_field->field_id == 'address') {
72 $field = array(
73 "idfield" => 'address',
74 "field_type" => 'INPUTBOX',
75 "field_label" => __('Address', 'wpdirectorykit'),
76 "prefix" => '',
77 "suffix" => '',
78 "values_list" => '',
79 "placeholder" => '',
80 );
81 }else if($used_field->field_id == 'post_title') {
82 $field = array(
83 "idfield" => 'post_title',
84 "field_type" => 'INPUTBOX',
85 "field_label" => __('Title', 'wpdirectorykit'),
86 "prefix" => '',
87 "suffix" => '',
88 "values_list" => '',
89 "placeholder" => '',
90 );
91 }else if($used_field->field_id == 'search') {
92 $field = array(
93 "idfield" => 'search',
94 "field_type" => 'INPUTBOX',
95 "field_label" => __('Search', 'wpdirectorykit'),
96 "prefix" => '',
97 "suffix" => '',
98 "values_list" => '',
99 "placeholder" => '',
100 );
101 }else if(function_exists('run_wdk_bookings') && $used_field->field_id == 'booking_date') {
102 $field = array(
103 "idfield" => 'booking_date',
104 "field_type" => 'BOOKINGS_DATE',
105 "field_label" => __('Booking Date', 'wpdirectorykit'),
106 "prefix" => '',
107 "suffix" => '',
108 "values_list" => '',
109 "placeholder" => '',
110 );
111 }else if(function_exists('run_wdk_bookings') && $used_field->field_id == 'booking_guest') {
112 $field = array(
113 "idfield" => 'booking_guest',
114 "field_type" => 'NUMBER',
115 "field_label" => __('Booking Max Guests', 'wpdirectorykit'),
116 "prefix" => '',
117 "suffix" => '',
118 "values_list" => '',
119 "placeholder" => '',
120 );
121 }else if($used_field->field_id == 'more') {
122 $field = array(
123 "idfield" => 'MORE',
124 "field_type" => 'MORE',
125 "field_label" => __('MORE', 'wpdirectorykit'),
126 "prefix" => '',
127 "suffix" => '',
128 "values_list" => '',
129 "placeholder" => '',
130 );
131 } else {
132 $field_data = $WMVC->field_m->get_fields_data($used_field->field_id);
133 if($field_data) {
134 if($used_field->query_type == 'slider_range') {
135 $field = array(
136 "idfield" => wmvc_show_data('idfield', $field_data),
137 "field_type" => 'SLIDER_RANGE',
138 "field_label" =>wmvc_show_data('field_label', $field_data),
139 "prefix" => wmvc_show_data('prefix', $field_data),
140 "suffix" => wmvc_show_data('suffix', $field_data),
141 "value_min" => wmvc_show_data('value_min', $used_field),
142 "value_max" => wmvc_show_data('value_max', $used_field),
143 "values_list" => wmvc_show_data('values_list', $field_data),
144 "placeholder" => wmvc_show_data('placeholder', $field_data)
145 );
146 } else {
147 $field = array(
148 "idfield" => wmvc_show_data('idfield', $field_data),
149 "field_type" => wmvc_show_data('field_type', $field_data),
150 "field_label" =>wmvc_show_data('field_label', $field_data),
151 "prefix" => wmvc_show_data('prefix', $field_data),
152 "suffix" => wmvc_show_data('suffix', $field_data),
153 "values_list" => wmvc_show_data('values_list', $field_data),
154 "placeholder" => wmvc_show_data('placeholder', $field_data),
155 "is_select_2_ajax_field_db_suggestion" => wmvc_show_data('is_select_2_ajax_field_db_suggestion', $used_field),
156 );
157 }
158 }
159 }
160
161 /* if field not detected or remove from fields list, skip field in search */
162 if(empty($field)) continue;
163
164 /* add from user fields data */
165 $field['field_id'] = wmvc_show_data('field_id', $used_field);
166 $field['class'] = wmvc_show_data('class', $used_field);
167 $field['query_type'] = wmvc_show_data('query_type', $used_field);
168 $field['columns'] = wmvc_show_data('columns', $used_field);
169
170
171 $field_data = array();
172 $field_data ['field_data'] = $field;
173 $field_data ['predefinedfields_query'] = $predefinedfields_query;
174
175 if(in_array(wmvc_show_data('field_type', $field),array('SECTION'))) {
176 continue;
177 }
178
179 $field_view_path = WPDIRECTORYKIT_PATH.'application/views/search_fields/'.$subfolder.(wmvc_show_data('field_type', $field)).'.php';
180 if(file_exists($field_view_path))
181 {
182 $output .= $WMVC->view('search_fields/'.$subfolder.(wmvc_show_data('field_type', $field)), $field_data, FALSE);
183 }
184 else
185 {
186 /* show missing view file of field, only if print enable */
187 if($print)
188 $output .= __('Missing VIEW file:', 'wpdirectorykit').' '.esc_html($subfolder).(wmvc_show_data('field_type', $field)).'.php';
189 }
190
191 }
192
193 if($print){
194 echo $output;
195 return FALSE;
196 }
197
198 return $output;
199 }
200 }
201
202 if ( ! function_exists('wdk_generate_search_form_fields_elementor'))
203 {
204 function wdk_generate_search_form_fields_elementor($fields_array = array(), $subfolder='', $print = TRUE, $predefinedfields_query = array())
205 {
206 /* load WMVC data */
207 $WMVC = &wdk_get_instance();
208 $WMVC->model('searchform_m');
209 $WMVC->model('field_m');
210 $output = '';
211
212 foreach ($fields_array as $key => $el_field_data) {
213 $field_id = wmvc_show_data('field_id', $el_field_data, '');
214 if(empty($field_id)) continue;
215
216 if(strpos($field_id,'__') !== FALSE){
217 $field_id = substr($field_id, strpos($field_id,'__')+2);
218 }
219
220 $field = NULL;
221 if($field_id == 'category_id') {
222 $field = array(
223 "idfield" => 'category',
224 "field_type" => 'CATEGORY',
225 "field_label" => __('Category', 'wpdirectorykit'),
226 "prefix" => '',
227 "suffix" => '',
228 "values_list" => '',
229 "placeholder" => '',
230 );
231 }else if($field_id == 'location_id') {
232 $field = array(
233 "idfield" => 'location',
234 "field_type" => 'LOCATION',
235 "field_label" => __('Location', 'wpdirectorykit'),
236 "prefix" => '',
237 "suffix" => '',
238 "values_list" => '',
239 "placeholder" => '',
240 );
241 }else if($field_id == 'address') {
242 $field = array(
243 "idfield" => 'address',
244 "field_type" => 'INPUTBOX',
245 "field_label" => __('Address', 'wpdirectorykit'),
246 "prefix" => '',
247 "suffix" => '',
248 "values_list" => '',
249 "placeholder" => '',
250 );
251 }else if($field_id == 'post_title') {
252 $field = array(
253 "idfield" => 'post_title',
254 "field_type" => 'INPUTBOX',
255 "field_label" => __('Title', 'wpdirectorykit'),
256 "prefix" => '',
257 "suffix" => '',
258 "values_list" => '',
259 "placeholder" => '',
260 );
261 }else if($field_id == 'search') {
262 $field = array(
263 "idfield" => 'search',
264 "field_type" => 'INPUTBOX',
265 "field_label" => __('Search', 'wpdirectorykit'),
266 "prefix" => '',
267 "suffix" => '',
268 "values_list" => '',
269 "placeholder" => '',
270 );
271 }else if(function_exists('run_wdk_bookings') && $field_id == 'booking_date') {
272 $field = array(
273 "idfield" => 'booking_date',
274 "field_type" => 'BOOKINGS_DATE',
275 "field_label" => __('Booking Date', 'wpdirectorykit'),
276 "prefix" => '',
277 "suffix" => '',
278 "values_list" => '',
279 "placeholder" => '',
280 );
281 }else if($field_id == 'more') {
282 $field = array(
283 "idfield" => 'MORE',
284 "field_type" => 'MORE',
285 "field_label" => __('MORE', 'wpdirectorykit'),
286 "prefix" => '',
287 "suffix" => '',
288 "values_list" => '',
289 "placeholder" => '',
290 );
291 } else {
292 $field_data = $WMVC->field_m->get_fields_data($field_id);
293
294 if($field_data) {
295 if(wmvc_show_data('search_type', $el_field_data, '') == 'slider_range') {
296 $field = array(
297 "idfield" => wmvc_show_data('idfield', $field_data),
298 "field_type" => 'SLIDER_RANGE',
299 "field_label" =>wmvc_show_data('field_label', $field_data),
300 "prefix" => wmvc_show_data('prefix', $field_data),
301 "suffix" => wmvc_show_data('suffix', $field_data),
302 "value_min" => wmvc_show_data('value_min', $el_field_data),
303 "value_max" => wmvc_show_data('value_max', $el_field_data),
304 "values_list" => wmvc_show_data('values_list', $field_data),
305 "placeholder" => wmvc_show_data('placeholder', $field_data)
306 );
307 } else {
308 $field = array(
309 "idfield" => wmvc_show_data('idfield', $field_data),
310 "field_type" => wmvc_show_data('field_type', $field_data),
311 "field_label" =>wmvc_show_data('field_label', $field_data),
312 "prefix" => wmvc_show_data('prefix', $field_data),
313 "suffix" => wmvc_show_data('suffix', $field_data),
314 "values_list" => wmvc_show_data('values_list', $field_data),
315 "placeholder" => wmvc_show_data('placeholder', $field_data)
316 );
317 }
318 }
319 }
320
321 if(wmvc_show_data('field_placeholder', $el_field_data, false)) {
322 $field['placeholder'] = wmvc_show_data('field_placeholder', $el_field_data, false);
323 }
324
325 if(wmvc_show_data('search_type_tree_hide', $el_field_data, false)) {
326 $field['search_type_tree_hide'] = wmvc_show_data('search_type_tree_hide', $el_field_data, false);
327 }
328
329 /* if field not detected or remove from fields list, skip field in search */
330 if(empty($field)) continue;
331
332 /* add from user fields data */
333 $field['field_id'] = wmvc_show_data('idfield', $field);
334 $field['class'] = wmvc_show_data('field_css_class', $el_field_data);
335 $field['query_type'] = wmvc_show_data('search_type', $el_field_data);
336 $field['columns'] = wmvc_show_data('field_columns_number', $el_field_data);
337
338
339 $field_data = array();
340 $field_data ['field_data'] = $field;
341 $field_data ['predefinedfields_query'] = $predefinedfields_query;
342
343 if(in_array(wmvc_show_data('field_type', $field),array('SECTION'))) {
344 continue;
345 }
346
347 $field_suffix = strtoupper(wmvc_show_data('search_type_tree', $el_field_data,''));
348
349 $field_view_path = WPDIRECTORYKIT_PATH.'application/views/search_fields/'.$subfolder.(wmvc_show_data('field_type', $field)).$field_suffix.'.php';
350 if(file_exists($field_view_path))
351 {
352 $output .= $WMVC->view('search_fields/'.$subfolder.(wmvc_show_data('field_type', $field)).$field_suffix, $field_data, FALSE);
353 }
354 else
355 {
356 /* show missing view file of field, only if print enable */
357 if($print)
358 $output .= __('Missing VIEW file:', 'wpdirectorykit').' '.esc_html($subfolder).(wmvc_show_data('field_type', $field)).$field_suffix.'.php';
359 }
360 }
361
362 if($print){
363 echo $output;
364 return FALSE;
365 }
366
367 return $output;
368 }
369 }
370
371
372 function &wdk_get_instance()
373 {
374 global $Winter_MVC_WDK;
375
376 if(empty($Winter_MVC_WDK))
377 {
378 $Winter_MVC_WDK = new MVC_Loader(plugin_dir_path( __FILE__ ).'../../');
379
380 $Winter_MVC_WDK->load_helper('basic');
381 }
382
383 return $Winter_MVC_WDK;
384 }
385
386 function wdk_prepare_search_query_GET($columns = array(), $model_name = NULL, $external_columns = array(), $custom_parameters = array(), $skip_postget = FALSE)
387 {
388
389 global $Winter_MVC_WDK;
390 $WMVC = &$Winter_MVC_WDK;
391 $wdk_bookings_joinded = false;
392 static $available_fields_listings = NULL;
393 static $available_fields_static = array();
394 static $list_fields_static = NULL;
395 $fields_type = array();
396
397 /* add if missing columns */
398 if(!in_array('post_id', $columns)) {
399 $columns[] = $Winter_MVC_WDK->db->prefix.'wdk_listings.post_id';
400 }
401
402 $_GET_clone = array();
403
404 if(!$skip_postget)
405 $_GET_clone = array_merge($_GET, $_POST);
406
407 if(isset($_GET_clone['order_by']) && $_GET_clone['order_by'] =='undefined') {
408 unset($_GET_clone['order_by']);
409 }
410
411 if(isset($custom_parameters['order_by'])) {
412
413 if(isset($_GET_clone['order_by']) && !empty($_GET_clone['order_by'])) {
414 $_GET_clone['order_by'] = ((!empty($custom_parameters['order_by'])) ? $custom_parameters['order_by'].', ':'').sanitize_text_field($_GET_clone['order_by']);
415 } elseif(!empty( $custom_parameters['order_by'])) {
416 $_GET_clone['order_by'] = $custom_parameters['order_by'];
417 }
418
419 unset($custom_parameters['order_by']);
420 }
421
422
423 if(!empty($custom_parameters))
424 $_GET_clone = array_merge($_GET_clone, $custom_parameters);
425
426 $WMVC->model('listing_m');
427 $WMVC->model('field_m');
428 $WMVC->model('listingfield_m');
429
430 $smart_search = '';
431 if(isset($_GET_clone['search']))
432 $smart_search = wdk_esc_sql(sanitize_text_field($_GET_clone['search']));
433
434 if(isset($_GET_clone['field_search']))
435 $smart_search = wdk_esc_sql(sanitize_text_field($_GET_clone['field_search']));
436
437 if(!isset($available_fields_static[$model_name]))
438 {
439 $available_fields = $WMVC->$model_name->get_available_fields();
440
441 $available_fields_static[$model_name] = $available_fields;
442 }
443 else
444 {
445 $available_fields = $available_fields_static[$model_name];
446 }
447
448 if($available_fields_listings === NULL)
449 $available_fields_listings = $WMVC->listingfield_m->get_available_fields();
450
451 /* Пet column names from wdk_listings_fields and add to allow search +
452 in _GET_clone replace field_#id to field_id_TYPE*/
453
454 if($list_fields_static === NULL)
455 {
456 $WMVC->db->where(array('field_type !='=> 'SECTION'));
457 $list_fields = $WMVC->field_m->get();
458 $list_fields_static = $list_fields;
459 }
460 else
461 {
462 $list_fields = $list_fields_static;
463 }
464
465
466 foreach($list_fields as $field_data) {
467
468 $field_id = wmvc_show_data('idfield',$field_data);
469 $field_type = wmvc_show_data('field_type',$field_data);
470
471 $fields_type[$field_id] = $field_type;
472 $column_name ='field_'.$field_id.'_'.$field_type;
473 if(!isset($available_fields_listings[$column_name])) continue;
474
475 if(isset($_GET_clone['field_'.$field_id])) {
476
477 if($field_type == 'DROPDOWNMULTIPLE') {
478 $_GET_clone['field_'.$field_id.'_'.$field_type] = $_GET_clone['field_'.$field_id];
479 } else {
480 $_GET_clone['field_'.$field_id.'_'.$field_type] = apply_filters( 'wdk-currency-conversion/convert/default_value',sanitize_text_field($_GET_clone['field_'.$field_id]), $field_id);
481 }
482 }
483
484 if(isset($_GET_clone['field_'.$field_id.'_max'])) {
485 $_GET_clone['field_'.$field_id.'_'.$field_type.'_max'] = apply_filters( 'wdk-currency-conversion/convert/default_value',sanitize_text_field($_GET_clone['field_'.$field_id.'_max']), $field_id);
486 }
487 if(isset($_GET_clone['field_'.$field_id.'_min'])) {
488 $_GET_clone['field_'.$field_id.'_'.$field_type.'_min'] = apply_filters( 'wdk-currency-conversion/convert/default_value',sanitize_text_field($_GET_clone['field_'.$field_id.'_min']), $field_id);
489 }
490 if(isset($_GET_clone['field_'.$field_id.'_exactly'])) {
491 $_GET_clone['field_'.$field_id.'_'.$field_type.'_exactly'] = wdk_clean_mixed($_GET_clone['field_'.$field_id.'_exactly']);
492 }
493
494 $columns[] = $column_name;
495 $columns[] = $column_name.'_max';
496 $columns[] = $column_name.'_min';
497 $columns[] = $column_name.'_exactly';
498 $external_columns[] = $column_name;
499 $external_columns[] = $column_name.'_max';
500 $external_columns[] = $column_name.'_min';
501 $external_columns[] = $column_name.'_exactly';
502 }
503
504 if(isset($_GET_clone['search_agents_ids'])) {
505 $column_name ='agents_ids';
506 $_GET_clone[$column_name] = $_GET_clone['search_agents_ids'];
507 $columns[] = $column_name;
508 $external_columns[] = $column_name;
509 }
510
511 if(isset($_GET_clone['search_user_editor_ids'])) {
512 $column_name ='user_editor_ids';
513 $_GET_clone[$column_name] = $_GET_clone['search_user_editor_ids'];
514 $columns[] = $column_name;
515 $external_columns[] = $column_name;
516 }
517
518 if(isset($_GET_clone['search_location'])) {
519 $column_name ='location_id';
520 $_GET_clone[$column_name] = $_GET_clone['search_location'];
521 $columns[] = $column_name;
522 $external_columns[] = $column_name;
523 }
524
525 if(isset($_GET_clone['search_category'])) {
526 $column_name ='category_id';
527 $_GET_clone[$column_name] = $_GET_clone['search_category'];
528 $columns[] = $column_name;
529 $external_columns[] = $column_name;
530 }
531
532 if(isset($_GET_clone['search_gps'])) {
533 $column_name ='gps';
534 $_GET_clone[$column_name] = $_GET_clone['search_gps'];
535 $columns[] = $column_name;
536 $external_columns[] = $column_name;
537 }
538
539 if(isset($_GET_clone['field_address'])) {
540 $column_name ='address';
541 $_GET_clone[$column_name] = $_GET_clone['field_address'];
542 $columns[] = $column_name;
543 $external_columns[] = $column_name;
544 }
545
546 if(isset($_GET_clone['field_post_id'])) {
547 $column_name ='ID_exactly';
548 $_GET_clone[$column_name] = sanitize_text_field($_GET_clone['field_post_id']);
549 $columns[] = $column_name;
550 $external_columns[] = $column_name;
551 }
552
553 if(isset($_GET_clone['field_post_date'])) {
554 $column_name ='post_DATE';
555 $_GET_clone[$column_name] = ($_GET_clone['field_post_date']);
556 $columns[] = $column_name;
557 $external_columns[] = $column_name;
558 }
559
560 if(isset($_GET_clone['field_post_date_min'])) {
561 $column_name ='post_DATE_min';
562 $_GET_clone[$column_name] = ($_GET_clone['field_post_date_min']);
563 $columns[] = $column_name;
564 $external_columns[] = $column_name;
565 }
566
567 if(isset($_GET_clone['field_post_date_max'])) {
568 $column_name ='post_DATE_max';
569 $_GET_clone[$column_name] = ($_GET_clone['field_post_date_max']);
570 $columns[] = $column_name;
571 $external_columns[] = $column_name;
572 }
573
574 if (function_exists('run_wdk_bookings') && isset($_GET_clone['field_booking_date_from'])) {
575 $column_name ='field_booking_date_from';
576 $_GET_clone[$column_name] = $_GET_clone['field_booking_date_from'];
577 $columns[] = $column_name;
578 $external_columns[] = $column_name;
579 }
580
581 if (function_exists('run_wdk_bookings') && isset($_GET_clone['field_booking_date_to'])) {
582 $column_name ='field_booking_date_to';
583 $_GET_clone[$column_name] = $_GET_clone['field_booking_date_to'];
584 $columns[] = $column_name;
585 $external_columns[] = $column_name;
586 }
587
588 if (function_exists('run_wdk_bookings') && isset($_GET_clone['field_booking_guest'])) {
589 $column_name ='field_booking_guest';
590 $_GET_clone[$column_name] = $_GET_clone['field_booking_guest'];
591 $columns[] = $column_name;
592 $external_columns[] = $column_name;
593 }
594
595 if (isset($_GET_clone['search_rank'])) {
596 $column_name ='`rank`';
597 $_GET_clone[$column_name] = $_GET_clone['search_rank'];
598 $columns[] = $column_name;
599 $external_columns[] = $column_name;
600 }
601
602 if (isset($_GET_clone['search_rank_min'])) {
603 $column_name ='`rank`_min';
604 $_GET_clone[$column_name] = $_GET_clone['search_rank_min'];
605 $columns[] = $column_name;
606 $external_columns[] = $column_name;
607 }
608
609 if (isset($_GET_clone['search_rank_max'])) {
610 $column_name ='`rank`_max';
611 $_GET_clone[$column_name] = $_GET_clone['search_rank_max'];
612 $columns[] = $column_name;
613 $external_columns[] = $column_name;
614 }
615
616 //$table_name = substr($model_name, 0, -2);
617 $columns_original = array();
618 foreach($columns as $key=>$val)
619 {
620 $columns_original[$val] = $val;
621
622 // if column contain also "table_name.*"
623 $splited = explode('.', $val);
624 if(wmvc_count($splited) == 2)
625 $val = $splited[1];
626
627 if(isset($available_fields[$val]))
628 {
629
630 }
631 else
632 {
633 if(!in_array($columns[$key], $external_columns))
634 {
635 unset($columns[$key]);
636 }
637 }
638 }
639
640 if(wmvc_count($_GET_clone) > 0)
641 {
642 unset($_GET_clone['search']);
643 unset($_GET_clone['field_search']);
644
645 $WMVC->db->join($WMVC->listing_m->_table_name.' ON '.$WMVC->listing_m->_table_name.'.post_id = '.$WMVC->db->prefix.'posts'.'.ID', NULL, 'LEFT');
646
647 // For quick/smart search
648 if(wmvc_count($columns) > 0 && !empty($smart_search))
649 {
650 $gen_q = '';
651 foreach($columns as $key=>$value)
652 {
653
654 if($value == 'field_booking_date_from' || $value == 'field_booking_date_to' || $value == 'agents_ids' || $value == 'gps' || $value == 'is_featured' || $value == 'field_booking_guest') continue;
655
656 if(strpos($value, '_CHECKBOX') !== FALSE) continue;
657
658 // if smart is number, search only im number fields
659
660
661 if(is_intval($smart_search)) {
662 if(strpos($value, '_NUMBER') === FALSE /*&& $value != 'category_id' && $value != 'location_id'*/ && strpos($value, 'post_id') === FALSE ) continue;
663 } else {
664 if($value == 'category_id' || $value == 'location_id' || strpos($value, 'post_id') !== FALSE) continue;
665 }
666
667 if(substr_count($value, 'id') > 0 && is_numeric($smart_search))
668 {
669 $gen_q.="$value = $smart_search OR ";
670 }
671 else if(substr_count($value, 'date') > 0)
672 {
673 $gen_search = $smart_search;
674
675 $gen_q.="$value LIKE '%$gen_search%' OR ";
676 }
677 elseif(substr($value, -8) == '_exactly')
678 {
679
680 }
681 elseif(substr($value, -4) == '_max')
682 {
683
684 }
685 else if(substr($value, -4) == '_min')
686 {
687
688 }
689 else if(strpos($value, '_NUMBER') !== FALSE)
690 {
691 if(is_intval($smart_search)){
692 $gen_search = $smart_search;
693 $gen_q.="$value = $gen_search OR ";
694 }
695 }
696 else
697 {
698 $gen_q.="$value LIKE '%$smart_search%' OR ";
699 }
700 }
701
702 /* location / categories */
703 if(!is_intval($smart_search)) {
704 $gen_q.="location_title LIKE '%$smart_search%' OR ";
705 $gen_q.="category_title LIKE '%$smart_search%' OR ";
706
707
708 $gen_q.="`category_table`.`titles_for_search` LIKE '%$smart_search%' OR ";
709 $gen_q.="`location_table`.`titles_for_search` LIKE '%$smart_search%' OR ";
710
711 }
712 /* get address and gps */
713 if(strlen($smart_search) > 5) {
714 $coordinates_center = wdk_get_gps($smart_search);
715 $search_radius = 5;
716 if($coordinates_center && $coordinates_center['lat'] != 0 && is_numeric($search_radius))
717 {
718 $distance_unit = 'km';
719 if(__('km', 'wpdirectorykit') == 'm')
720 {
721 $distance_unit = 'm';
722 }
723
724 // calculate rectangle
725 $rectangle_ne = wdk_getDueCoords($coordinates_center['lat'], $coordinates_center['lng'], 45, $search_radius, $distance_unit);
726 $rectangle_sw = wdk_getDueCoords($coordinates_center['lat'], $coordinates_center['lng'], 225, $search_radius, $distance_unit);
727
728 $gps_ne = explode(', ', $rectangle_ne);
729 $gps_sw = explode(', ', $rectangle_sw);
730
731 $gen_q .="(".$WMVC->db->prefix."wdk_listings.lat < '$gps_ne[0]' AND ".$WMVC->db->prefix."wdk_listings.lat > '$gps_sw[0]' AND
732 ".$WMVC->db->prefix."wdk_listings.lng < '$gps_ne[1]' AND ".$WMVC->db->prefix."wdk_listings.lng > '$gps_sw[1]') OR ";
733
734 }
735 }
736
737 /* detect is gps */
738 if(wdk_is_gps($smart_search)) {
739 $gps = explode(',',$smart_search);
740 $coordinates_center = array('lat'=>trim($gps[0]),'lng'=>trim($gps[1]));
741 $search_radius = 5;
742 if($coordinates_center && $coordinates_center['lat'] != 0 && is_numeric($search_radius))
743 {
744 $distance_unit = 'km';
745 if(__('km', 'wpdirectorykit') == 'm')
746 {
747 $distance_unit = 'm';
748 }
749
750 // calculate rectangle
751 $rectangle_ne = wdk_getDueCoords($coordinates_center['lat'], $coordinates_center['lng'], 45, $search_radius, $distance_unit);
752 $rectangle_sw = wdk_getDueCoords($coordinates_center['lat'], $coordinates_center['lng'], 225, $search_radius, $distance_unit);
753
754 $gps_ne = explode(', ', $rectangle_ne);
755 $gps_sw = explode(', ', $rectangle_sw);
756
757 $gen_q .="(".$WMVC->db->prefix."wdk_listings.lat < '$gps_ne[0]' AND ".$WMVC->db->prefix."wdk_listings.lat > '$gps_sw[0]' AND
758 ".$WMVC->db->prefix."wdk_listings.lng < '$gps_ne[1]' AND ".$WMVC->db->prefix."wdk_listings.lng > '$gps_sw[1]') OR ";
759
760 }
761 }
762
763 $gen_q = substr($gen_q, 0, -4);
764
765 if(!empty($gen_q))
766 $WMVC->db->where("($gen_q)");
767 }
768
769 // For column search
770 if(isset($_GET_clone))
771 {
772 $gen_q = '';
773 foreach($_GET_clone as $key=>$val)
774 {
775 if(!empty($val) && in_array($key, $columns))
776 {
777 $col_name = $key;
778
779 $val = esc_sql($val);
780 //if(isset($key))
781 // $col_name = $key;
782
783 if(strpos($key, 'skip') !== FALSE) continue;
784
785 if($key == 'field_booking_guest')
786 {
787 if(!$wdk_bookings_joinded){
788 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_price ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_price.post_id', NULL, 'LEFT');
789 $WMVC->db->distinct($WMVC->db->prefix.'posts.ID');
790 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_reservation ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_reservation.post_id', NULL, 'LEFT');
791 $wdk_bookings_joinded = true;
792 $gen_q.= $WMVC->db->prefix.'wdk_booking_price.is_activated = 1 AND ';
793 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_calendar ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_calendar.post_id', NULL, 'LEFT');
794 }
795
796 $gen_q.= $WMVC->db->prefix."wdk_booking_calendar.guests >='".intval($val)."' AND ";
797
798 }
799 elseif($key == 'field_booking_date_from')
800 {
801 if(!$wdk_bookings_joinded){
802 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_price ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_price.post_id', NULL, 'LEFT');
803 $WMVC->db->distinct($WMVC->db->prefix.'posts.ID');
804 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_reservation ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_reservation.post_id', NULL, 'LEFT');
805 $wdk_bookings_joinded = true;
806 $gen_q.= $WMVC->db->prefix.'wdk_booking_price.is_activated = 1 AND ';
807 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_calendar ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_calendar.post_id', NULL, 'LEFT');
808 }
809
810 if(wdk_is_date($val))
811 {
812 if(!get_option('wdk_bookings_is_hours_enabled')) {
813 $gen_search = wdk_normalize_date_db($val, 'Y-m-d H:i:s', 'Y-m-d');
814 $gen_q.= "DATE_FORMAT(".$WMVC->db->prefix."wdk_booking_price.date_from, '%Y-%m-%d') <= '".$gen_search."' AND ";
815 } else {
816 $gen_search = wdk_normalize_date_db($val);
817 $gen_q.= $WMVC->db->prefix."wdk_booking_price.date_from >'".$gen_search."' AND ";
818 }
819 }
820
821 if( isset($_GET_clone['field_booking_date_from']) && isset($_GET_clone['field_booking_date_to'])) {
822
823 if(!get_option('wdk_bookings_is_hours_enabled')) {
824 $gen_search_from = wdk_normalize_date_db($_GET_clone['field_booking_date_from'], 'Y-m-d H:i:s', 'Y-m-d');
825 $gen_search_to = wdk_normalize_date_db($_GET_clone['field_booking_date_to'], 'Y-m-d H:i:s', 'Y-m-d');
826
827 $gen_q.= $WMVC->db->prefix."posts.ID NOT IN (
828 SELECT post_id
829 FROM ".$WMVC->db->prefix."wdk_booking_reservation
830 WHERE
831 ".$WMVC->db->prefix."wdk_booking_reservation.is_approved = 1
832 AND
833 DATE_FORMAT(".$WMVC->db->prefix."wdk_booking_reservation.date_from, '%Y-%m-%d') < '".$gen_search_to."'
834 AND
835 DATE_FORMAT(".$WMVC->db->prefix."wdk_booking_reservation.date_to, '%Y-%m-%d') > '".$gen_search_from."'
836 ) AND ";
837
838 } else {
839 $gen_search_from = wdk_normalize_date_db($_GET_clone['field_booking_date_from']);
840 $gen_search_to = wdk_normalize_date_db($_GET_clone['field_booking_date_to']);
841
842 $gen_q.= $WMVC->db->prefix."posts.ID NOT IN (
843 SELECT post_id
844 FROM ".$WMVC->db->prefix."wdk_booking_reservation
845 WHERE
846 ".$WMVC->db->prefix."wdk_booking_reservation.is_approved = 1
847 AND
848 ".$WMVC->db->prefix."wdk_booking_reservation.date_from < '".$gen_search_to."'
849 AND
850 ".$WMVC->db->prefix."wdk_booking_reservation.date_to > '".$gen_search_from."'
851 ) AND ";
852 }
853 }
854
855 }
856 elseif($key == 'field_booking_date_to')
857 {
858 if(!$wdk_bookings_joinded){
859 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_price ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_price.post_id',NULL, 'LEFT');
860 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_reservation ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_reservation.post_id',NULL, 'LEFT');
861 $wdk_bookings_joinded = true;
862 $gen_q.= $WMVC->db->prefix.'wdk_booking_price.is_activated = 1 AND ';
863 $WMVC->db->join($WMVC->db->prefix.'wdk_booking_calendar ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_booking_calendar.post_id', NULL, 'LEFT');
864 }
865
866 if(wdk_is_date($val))
867 {
868 if(!get_option('wdk_bookings_is_hours_enabled')) {
869 $gen_search = wdk_normalize_date_db($val, 'Y-m-d H:i:s', 'Y-m-d');
870 $gen_q.= "DATE_FORMAT(".$WMVC->db->prefix."wdk_booking_price.date_to, '%Y-%m-%d') >= '".$gen_search."' AND ";
871 } else {
872 $gen_search = wdk_normalize_date_db($val);
873 $gen_q.= $WMVC->db->prefix."wdk_booking_price.date_to >'".$gen_search."' AND ";
874 }
875 }
876
877 }
878 elseif(substr($key, -8) == '_exactly')
879 {
880 $col_name = substr($key, 0, -8);
881
882 if(is_string($val) && strpos($val, ',') !== FALSE){
883 $val =explode(',', $val);
884 } elseif(is_string($val)){
885 $val =array($val);
886 }
887
888 if(is_array($val))
889 {
890 $sql_search = '';
891 foreach ($val as $v) {
892 if(empty($v)) continue;
893
894 if(!empty($sql_search))
895 $sql_search .= " OR ";
896
897 $sql_search .= " ".$col_name." = '".$v."' ";
898 }
899
900 if(!empty($sql_search))
901 $gen_q.=" ( ".$sql_search." ) AND ";
902 } else {
903
904 $gen_q.=$col_name." = '".$val."' AND ";
905 }
906 }
907 elseif(substr($key, -4) == '_max')
908 {
909 $col_name = substr($key, 0, -4);
910
911 if(strpos($key, 'NUMBER') !== FALSE) {
912 $gen_q.=$col_name." <= ".intval($val)." AND ";
913 } else if(strpos($key, 'DATE') !== FALSE) {
914 if(wdk_is_date($val))
915 {
916 $gen_search = wdk_normalize_date_db($val, 'Y-m-d H:i:s', 'Y-m-d H:i:s');
917 $gen_q.=$col_name." <= '".$gen_search."' AND ";
918 }
919 } else {
920 $gen_q.=$col_name." <= '".$val."' AND ";
921 }
922 }
923 else if(substr($key, -4) == '_min')
924 {
925 $col_name = substr($key, 0, -4);
926
927 if(strpos($key, 'NUMBER') !== FALSE) {
928 $gen_q.=$col_name." >= ".intval($val)." AND ";
929 } else if(strpos($key, 'DATE') !== FALSE) {
930 if(wdk_is_date($val))
931 {
932 $gen_search = wdk_normalize_date_db($val, 'Y-m-d H:i:s', 'Y-m-d H:i:s');
933 $gen_q.=$col_name." >= '".$gen_search."' AND ";
934 }
935 } else {
936 $gen_q.=$col_name." >= '".$val."' AND ";
937 }
938 }
939 elseif(substr_count($key, 'id') > 0 && is_numeric($val) && $key != 'agents_ids' && $key !='user_editor_ids' && $key !='location_id' && $key !='category_id')
940 {
941 // ID is always numeric
942
943 if($key == 'location_id') {
944 /* $gen_q .= "(`location_table`.`parent_path` = ".$val." OR ";
945 $gen_q .= "`location_2`.`parent_path` = ".$val." OR ";*/
946 $gen_q .= "(`location_table`.`parent_id` = ".$val." OR ";
947 //$gen_q .= "`".$WMVC->db->prefix."wdk_locations `.`level_0_id` = ".$val." OR ";
948
949 $gen_q .= $col_name." = ".$val.") AND ";
950 } elseif($key == 'category_id') {
951 $gen_q .= "('parent_path' = ".$val." OR ";
952 $gen_q .= $col_name." = ".$val.") AND ";
953 } else {
954 $gen_q.=$col_name." = ".$val." AND ";
955 }
956 }
957 else if(substr_count($key, '_DATE') > 0)
958 {
959 // DATE VALUES
960
961 $gen_search = $val;
962 if(wdk_is_date($val))
963 {
964 $gen_search = wdk_normalize_date_db($gen_search, 'Y-m-d H:i:s', 'Y-m-d');
965 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
966 }
967 else
968 {
969 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
970
971 }
972 }
973 else if(substr_count($key, 'is_') > 0)
974 {
975 // CHECKBOXES
976
977 if($val=='on')
978 {
979 $gen_search = 1;
980 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
981 }
982 else if($val=='off')
983 {
984 $gen_q.=$col_name." IS NULL AND ";
985 }
986 }
987 elseif($key == 'agents_ids')
988 {
989 if(is_string($val) && strpos($val, ',') !== FALSE){
990 $val =explode(',', $val);
991 } elseif(is_string($val)){
992 $val =array($val);
993 }
994
995 if(is_array($val)) {
996
997 $WMVC->db->join($WMVC->db->prefix.'wdk_listings_users ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'wdk_listings_users.post_id', NULL, 'LEFT');
998 $WMVC->db->distinct($WMVC->listing_m->_table_name.'.post_id');
999 $sql_search = '';
1000 foreach ($val as $v) {
1001 if(empty($v)) continue;
1002
1003 if(!empty($sql_search))
1004 $sql_search .= " OR ";
1005
1006
1007 $sql_search .=" ".$WMVC->listing_m->_table_name.".`user_id_editor` = ".intval($v)." OR `".$WMVC->db->prefix."wdk_listings_users`.`user_id` = ".intval($v)." ";
1008 }
1009
1010 if(!empty($sql_search))
1011 $gen_q.=" ( ".$sql_search." ) AND ";
1012
1013 } elseif(is_string($val) && !empty($val)) {
1014 $WMVC->db->join($WMVC->db->prefix.'wdk_listings_users ON '.$WMVC->db->prefix.'posts.post_id = '.$WMVC->db->prefix.'wdk_listings_users.post_id', NULL, 'LEFT');
1015 $WMVC->db->distinct($WMVC->listing_m->_table_name.'.post_id');
1016 $sql_search =" ".$WMVC->listing_m->_table_name.".`user_id_editor` = ".intval($val)." OR `".$WMVC->db->prefix."wdk_listings_users`.`user_id` = ".intval($val)." ";
1017 $gen_q.=" ( ".$sql_search." ) AND ";
1018 }
1019 }
1020 elseif($key == 'user_editor_ids')
1021 {
1022
1023 if(is_array($val)) {
1024
1025 $sql_search = '';
1026 foreach ($val as $v) {
1027 if(empty($v)) continue;
1028
1029 if(!empty($sql_search))
1030 $sql_search .= " OR ";
1031
1032
1033 $sql_search .=" ".$WMVC->listing_m->_table_name.".`user_id_editor` = ".intval($v)." ";
1034 }
1035
1036 if(!empty($sql_search))
1037 $gen_q.=" ( ".$sql_search." ) AND ";
1038
1039 } elseif(is_string($val) && !empty($val)) {
1040 $sql_search =" ".$WMVC->listing_m->_table_name.".`user_id_editor` = ".intval($val)." ";
1041 $gen_q.=" ( ".$sql_search." ) AND ";
1042 }
1043 }
1044 elseif($key == 'location_id')
1045 {
1046 if(empty($val)) continue;
1047
1048 if(is_string($val) && strpos($val, ',') !== FALSE){
1049 $val =explode(',', $val);
1050 } elseif(is_string($val)){
1051 $val =array($val);
1052 }
1053
1054 if(is_array($val)) {
1055
1056 if(false){
1057 $WMVC->db->join($WMVC->db->prefix.'wdk_listings_locations ON '.$WMVC->listing_m->_table_name.'.post_id = '.$WMVC->db->prefix.'wdk_listings_locations.post_id', NULL, 'LEFT');
1058 $WMVC->db->distinct($WMVC->listing_m->_table_name.'.post_id');
1059 }
1060
1061 $sql_search = '';
1062 foreach ($val as $v) {
1063 if(empty($v) || !is_intval($v)) continue;
1064
1065 if(!empty($sql_search))
1066 $sql_search .= " OR ";
1067
1068 $sql_search .= " ".$WMVC->listing_m->_table_name.".`location_id`=".intval($v)."";
1069 $sql_search .= " OR `location_table`.`parent_id`=".intval($v)."";
1070
1071 $sql_search .= " OR CONCAT(',', location_table.parent_path, ',') LIKE CONCAT('%,', ".intval($v).", ',%')";
1072
1073 /* other locations */
1074 /* multi select */
1075 if(false){
1076 $sql_search .= " OR `".$WMVC->db->prefix."wdk_listings`.`post_id` IN (SELECT `post_id` FROM `".$WMVC->db->prefix."wdk_listings_locations` WHERE `location_id` = ".intval($v).") ";
1077 } elseif(false) {
1078 $sql_search .= " OR ".$WMVC->db->prefix."wdk_listings_locations.location_id=".intval($v)."";
1079 } else {
1080 $sql_search .= " OR ".$WMVC->listing_m->_table_name.".locations_list LIKE '%,".intval($v).",%'";
1081 }
1082
1083 }
1084
1085 if(!empty($sql_search))
1086 $gen_q.=" ( ".$sql_search." ) AND ";
1087 }
1088 }
1089 elseif($key == 'category_id')
1090 {
1091
1092 if(empty($val)) continue;
1093
1094 if(is_string($val) && strpos($val, ',') !== FALSE){
1095 $val =explode(',', $val);
1096 } elseif(is_string($val)){
1097 $val =array($val);
1098 }
1099
1100
1101 if(is_array($val)) {
1102 if(false){
1103 $WMVC->db->join($WMVC->db->prefix.'wdk_listings_categories ON '.$WMVC->listing_m->_table_name.'.post_id = '.$WMVC->db->prefix.'wdk_listings_categories.post_id', NULL, 'LEFT');
1104 }
1105
1106 $sql_search = '';
1107 foreach ($val as $v) {
1108 if(empty($v) || !is_intval($v)) continue;
1109
1110 if(!empty($sql_search))
1111 $sql_search .= " OR ";
1112
1113 $sql_search .= " ".$WMVC->db->prefix."wdk_listings.`category_id` = ".intval($v)."";
1114 $sql_search .= " OR `category_table`.`parent_id`=".intval($v)."";
1115 $sql_search .= " OR CONCAT(',', category_table.parent_path, ',') LIKE CONCAT('%,', ".intval($v).", ',%')";
1116
1117 /* other categories */
1118 if(false){
1119 $sql_search .= " OR `".$WMVC->db->prefix."wdk_listings`.`post_id` IN (SELECT `post_id` FROM `".$WMVC->db->prefix."wdk_listings_categories` WHERE `category_id` = ".intval($v).")";
1120 } elseif(false) {
1121 $sql_search .= " OR ".$WMVC->db->prefix."wdk_listings_categories.category_id=".intval($v)."";
1122 } else {
1123 $sql_search .= " OR ".$WMVC->listing_m->_table_name.".categories_list LIKE '%,".intval($v).",%'";
1124 }
1125
1126 }
1127
1128 if(!empty($sql_search))
1129 $gen_q.=" ( ".$sql_search." ) AND ";
1130 }
1131 }
1132 elseif(is_string($val))
1133 {
1134
1135 if(strpos($val, ',') !== FALSE){
1136 $val = explode(',', $val);
1137 }
1138
1139 if(is_array($val)) {
1140 $sql_search = '';
1141 foreach ($val as $v) {
1142 if(empty($v)) continue;
1143
1144 if(!empty($sql_search))
1145 $sql_search .= " OR ";
1146
1147 $sql_search .= $col_name." LIKE '%".$v."%'";
1148
1149 }
1150
1151 if(!empty($sql_search))
1152 $gen_q.=" ( ".$sql_search." ) AND ";
1153 } else {
1154 $gen_q.=$col_name." LIKE '%".$val."%' AND ";
1155 }
1156
1157 }
1158 elseif(is_array($val))
1159 {
1160 $sql_search = '';
1161 foreach ($val as $v) {
1162 if(empty($v)) continue;
1163
1164 if(!empty($sql_search))
1165 $sql_search .= " OR ";
1166
1167 $sql_search .= " ".$col_name." LIKE '%".esc_sql($v)."%' ";
1168 }
1169
1170 if(!empty($sql_search))
1171 $gen_q.=" ( ".$sql_search." ) AND ";
1172 }
1173 } elseif ($val == 0) {
1174 $col_name = $key;
1175 $val = esc_sql($val);
1176 if(in_array($col_name, ['`rank`'])) {
1177 $gen_q.=" ( ".$col_name." = 0 OR ".$col_name." IS NULL ) AND ";
1178 }
1179 }
1180 }
1181
1182 $gen_q = substr($gen_q, 0, -5);
1183
1184 if(!empty($gen_q))
1185 $WMVC->db->where("($gen_q)");
1186 }
1187
1188 //if(defined( 'WP_DEBUG' ) && WP_DEBUG)
1189 if(function_exists('pll_current_language'))
1190 {
1191 $lang_term_id = pll_current_language('term_id');
1192
1193 if(is_numeric($lang_term_id))
1194 {
1195 //echo $lang_term_id.'<br />';
1196 $WMVC->db->join($WMVC->db->prefix.'term_relationships ON '.$WMVC->db->prefix.'posts.ID = '.$WMVC->db->prefix.'term_relationships.object_id', NULL, NULL);
1197 $WMVC->db->where("({$WMVC->db->prefix}term_relationships.term_taxonomy_id = $lang_term_id)");
1198 }
1199 }
1200
1201 // [RECTANGLE SEARCH]
1202 if(isset($_GET_clone['rectangle_ne']) && isset($_GET_clone['rectangle_sw']))
1203 {
1204 if(wdk_is_gps($_GET_clone['rectangle_ne']) && wdk_is_gps($_GET_clone['rectangle_sw'])) {
1205
1206 $gps_ne = explode(',', $_GET_clone['rectangle_ne']);
1207 $gps_sw = explode(',', $_GET_clone['rectangle_sw']);
1208
1209 $WMVC->db->where("(".$WMVC->db->prefix."wdk_listings.lat < '$gps_ne[0]' AND ".$WMVC->db->prefix."wdk_listings.lat > '$gps_sw[0]' AND
1210 ".$WMVC->db->prefix."wdk_listings.lng > '$gps_ne[1]' AND ".$WMVC->db->prefix."wdk_listings.lng < '$gps_sw[1]')");
1211 }
1212 }
1213 // [/RECTANGLE SEARCH]
1214
1215 // order
1216 if (isset($_GET_clone['order_by'])) {
1217 // Merge available fields + system columns
1218 $order_columns = [
1219 'post_id' => $WMVC->db->prefix . 'wdk_listings.post_id',
1220 'counter_views' => $WMVC->db->prefix . 'wdk_listings.counter_views',
1221 'date_modified' => $WMVC->db->prefix . 'wdk_listings.date_modified',
1222 'post_title' => $WMVC->db->prefix . 'posts.post_title',
1223 'address' => $WMVC->db->prefix . 'wdk_listings.address',
1224 'category_id' => $WMVC->db->prefix . 'wdk_listings.category_id',
1225 'location_id' => $WMVC->db->prefix . 'wdk_listings.location_id',
1226 'rank' => $WMVC->db->prefix . 'wdk_listings.rank'
1227 ];
1228
1229 $order_columns = apply_filters('wdk/listings/order_columns', $order_columns);
1230
1231 $_GET_clone['order_by'] = str_replace(
1232 'post_id',
1233 $WMVC->db->prefix . 'wdk_listings.post_id',
1234 sanitize_text_field($_GET_clone['order_by'])
1235 );
1236
1237 // Fix common typos: ask → asc, desk → desc
1238 $_GET_clone['order_by'] = str_ireplace([' ask', ' desk'], [' asc', ' desc'], $_GET_clone['order_by']);
1239
1240 /* we no need field type in get link now */
1241 $_GET_clone['order_by'] = str_ireplace(['_NUMBER', '_SECTION', '_TEXTAREA', '_DATE', '_DROPDOWN', '_DROPDOWNMULTIPLE', '_CHECKBOX'], '', $_GET_clone['order_by']);
1242
1243 // Parse order_by string into parts
1244 $order_by_array = explode(',', $_GET_clone['order_by']);
1245 $final_order_by = [];
1246
1247 foreach ($order_by_array as $order_part) {
1248 $order_part = trim($order_part);
1249
1250 // detect direction asc/desc
1251 $direction = 'DESC';
1252 if (stripos($order_part, ' asc') !== false) {
1253 $direction = 'ASC';
1254 } elseif (stripos($order_part, ' desc') !== false) {
1255 $direction = 'DESC';
1256 }
1257
1258 $order_part = str_ireplace(['desc', 'asc'], '', $order_part);
1259 $order_part = esc_sql(sanitize_textarea_field(str_replace(' ', '', $order_part)));
1260
1261 // Try to detect field_(id)
1262 if (preg_match('/field_(\d+)\b/', $order_part, $matches)) {
1263
1264 $search_field_id = $matches[1];
1265 if (!empty($fields_type[$search_field_id])) {
1266 $field_name = "field_{$search_field_id}_{$fields_type[$search_field_id]}";
1267
1268 // Check if field exists in order_columns
1269 if (isset($available_fields_listings[$field_name])) {
1270 $final_order_by[] = $field_name . ' ' . $direction;
1271 }
1272 }
1273
1274 // else → skip invalid field automatically
1275
1276 } else {
1277 // Extract only the part after the last '.' if exists, else use entire string
1278 $col_field = $order_part;
1279 if (strpos($col_field, '.') !== false) {
1280 $parts = explode('.', $col_field);
1281 $col_field = end($parts);
1282 }
1283
1284 // Check if field exists in order_columns
1285 if (isset($order_columns[$col_field])) {
1286 $safe_column = $order_columns[$col_field];
1287 $final_order_by[] = "$safe_column $direction";
1288 }
1289 }
1290 }
1291
1292 // Apply final order if any valid fields left
1293 if (!empty($final_order_by)) {
1294 $_GET_clone['order_by'] = implode(', ', $final_order_by);
1295 $WMVC->db->order_by($_GET_clone['order_by']);
1296 } else {
1297 $WMVC->db->order_by('');
1298 }
1299
1300 }
1301
1302 }
1303 }
1304
1305 function wdk_users_prepare_search_query_GET($columns = array(), $model_name = NULL, $external_columns = array(), $custom_parameters = array(), $skip_postget = FALSE)
1306 {
1307 global $Winter_MVC_WDK;
1308 $WMVC = &$Winter_MVC_WDK;
1309
1310 $_GET_clone = array();
1311
1312 if(!$skip_postget)
1313 $_GET_clone = array_merge($_GET, $_POST);
1314
1315 if(isset($custom_parameters['order_by'])) {
1316
1317 if(isset($_GET_clone['order_by']) && !empty($_GET_clone['order_by'])) {
1318 $_GET_clone['order_by'] = $custom_parameters['order_by'].', '.sanitize_text_field($_GET_clone['order_by']);
1319 } else {
1320 $_GET_clone['order_by'] = $custom_parameters['order_by'];
1321 }
1322
1323 unset($custom_parameters['order_by']);
1324 }
1325
1326
1327 if(!empty($custom_parameters))
1328 $_GET_clone = array_merge($_GET_clone, $custom_parameters);
1329
1330 $WMVC->model($model_name);
1331
1332 $smart_search = '';
1333 if(isset($_GET_clone['profile_search']))
1334 $smart_search = wdk_esc_sql(sanitize_text_field($_GET_clone['profile_search']));
1335
1336 $available_fields = array('user_login','user_nicename','user_email','user_url','display_name');
1337
1338 if(isset($_GET_clone['is_activated'])){
1339 $_GET_clone[$WMVC->$model_name->_table_name.'.is_activated'] = sanitize_text_field($_GET_clone['is_activated']);
1340 unset($_GET_clone['is_activated']);
1341 }
1342
1343 if(isset($_GET_clone['is_approved'])){
1344 $_GET_clone[$WMVC->$model_name->_table_name.'.is_approved'] = sanitize_text_field($_GET_clone['is_approved']);
1345 unset($_GET_clone['is_approved']);
1346 }
1347
1348
1349 //$table_name = substr($model_name, 0, -2);
1350 $columns_original = array();
1351 foreach($columns as $key=>$val)
1352 {
1353 $columns_original[$val] = $val;
1354
1355 // if column contain also "table_name.*"
1356 $splited = explode('.', $val);
1357 if(wmvc_count($splited) == 2)
1358 $val = $splited[1];
1359
1360 if(isset($available_fields[$val]))
1361 {
1362
1363 }
1364 else
1365 {
1366 if(!in_array($columns[$key], $external_columns))
1367 {
1368 unset($columns[$key]);
1369 }
1370 }
1371 }
1372
1373 if(wmvc_count($_GET_clone) > 0)
1374 {
1375 unset($_GET_clone['search']);
1376
1377 // For quick/smart search
1378 if(wmvc_count($columns) > 0 && !empty($smart_search))
1379 {
1380 $gen_q = '';
1381 foreach($columns as $key=>$value)
1382 {
1383
1384 if($value == 'post_type')
1385 {
1386 $value = $WMVC->$model_name->_table_name.'.'.$value;
1387 }
1388
1389 if(substr_count($value, 'id') > 0 && is_numeric($smart_search))
1390 {
1391 $gen_q.="$value = $smart_search OR ";
1392 }
1393 else if(substr_count($value, 'date') > 0)
1394 {
1395 //$gen_search = wmvc_generate_slug($smart_search, ' ');
1396
1397 $gen_search = $smart_search;
1398
1399 $gen_q.="$value LIKE '%$gen_search%' OR ";
1400 }
1401 else
1402 {
1403 $gen_q.="$value LIKE '%$smart_search%' OR ";
1404 }
1405 }
1406 $gen_q = substr($gen_q, 0, -4);
1407
1408 if(!empty($gen_q))
1409 $WMVC->db->where("($gen_q)");
1410 }
1411
1412 // For column search
1413 if(isset($_GET_clone))
1414 {
1415 $gen_q = '';
1416
1417 foreach($_GET_clone as $key=>$val)
1418 {
1419 if(!empty($val) && in_array($key, $columns))
1420 {
1421 $col_name = $key;
1422
1423 if($col_name == 'post_type')
1424 {
1425 $col_name = $WMVC->$model_name->_table_name.'.'.$col_name;
1426 }
1427
1428 //if(isset($key))
1429 // $col_name = $key;
1430
1431 if(strpos($key, 'skip') !== FALSE) continue;
1432
1433 if(substr($key, -8) == '_exactly')
1434 {
1435 $col_name = substr($key, 0, -8);
1436 $gen_q.=$col_name." = '".$val."' AND ";
1437 }
1438 elseif(substr($key, -4) == '_max')
1439 {
1440 $col_name = substr($key, 0, -4);
1441 $gen_q.=$col_name." <= '".$val."' AND ";
1442 }
1443 else if(substr($key, -4) == '_min')
1444 {
1445 $col_name = substr($key, 0, -4);
1446
1447 $gen_q.=$col_name." >= '".$val."' AND ";
1448 }
1449 elseif(substr_count($key, 'id') > 0 && is_numeric($val))
1450 {
1451 // ID is always numeric
1452
1453 $gen_q.=$col_name." = ".$val." AND ";
1454 }
1455 else if(substr_count($key, 'date') > 0)
1456 {
1457 // DATE VALUES
1458
1459 $gen_search = $val;
1460
1461 if(wdk_is_date($val))
1462 {
1463 $gen_search = wdk_normalize_date_db($gen_search);
1464 $gen_q.=$col_name." > '".$gen_search."' AND ";
1465 }
1466 else
1467 {
1468 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
1469 }
1470 }
1471 else if(substr_count($key, 'is_') > 0)
1472 {
1473 // CHECKBOXES
1474
1475 if($val=='on')
1476 {
1477 $gen_search = 1;
1478 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
1479 }
1480 else if($val=='off')
1481 {
1482 $gen_q.=$col_name." IS NULL AND ";
1483 }
1484 }
1485 else
1486 {
1487 $gen_q.=$col_name." LIKE '%".$val."%' AND ";
1488 }
1489 }
1490
1491 }
1492
1493 $gen_q = substr($gen_q, 0, -5);
1494
1495 if(!empty($gen_q))
1496 $WMVC->db->where("($gen_q)");
1497 }
1498
1499 // order
1500 if(isset($_GET_clone['order_by']))
1501 {
1502 $_GET_clone['order_by'] = str_replace('post_id', $WMVC->db->prefix.'wdk_favorite.post_id', $_GET_clone['order_by']);
1503 $WMVC->db->order_by(wdk_esc_sql(sanitize_text_field($_GET_clone['order_by'])));
1504 }
1505
1506 }
1507 }
1508
1509 function wdk_messages_prepare_search_query_GET($columns = array(), $model_name = NULL, $external_columns = array())
1510 {
1511 global $Winter_MVC_WDK;
1512 $WMVC = &$Winter_MVC_WDK;
1513 $_GET_clone = array_merge($_GET, $_POST);
1514
1515 $_GET_clone = ($_GET_clone);
1516
1517 //$WMVC->model('listing_m');
1518
1519 $smart_search = '';
1520 if(isset($_GET_clone['search']))
1521 $smart_search = wdk_esc_sql(sanitize_text_field($_GET_clone['search']));
1522
1523 $available_fields = $WMVC->$model_name->get_available_fields();
1524
1525 /* Пet column names from wdk_package and add to allow search +
1526 in _GET_clone replace field_#id to field_id_TYPE*/
1527 $list_fields = $WMVC->db->list_fields( $WMVC->db->prefix.'wdk_messages');
1528
1529
1530 //$table_name = substr($model_name, 0, -2);
1531 $columns_original = array();
1532 foreach($columns as $key=>$val)
1533 {
1534 $columns_original[$val] = $val;
1535
1536 // if column contain also "table_name.*"
1537 $splited = explode('.', $val);
1538 if(wmvc_count($splited) == 2)
1539 $val = $splited[1];
1540
1541 if(isset($available_fields[$val]))
1542 {
1543
1544 }
1545 else
1546 {
1547 if(!in_array($columns[$key], $external_columns))
1548 {
1549 unset($columns[$key]);
1550 }
1551 }
1552 }
1553
1554 if(wmvc_count($_GET_clone) > 0)
1555 {
1556 unset($_GET_clone['search']);
1557
1558 // For quick/smart search
1559 if(wmvc_count($columns) > 0 && !empty($smart_search))
1560 {
1561 $gen_q = '';
1562 foreach($columns as $key=>$value)
1563 {
1564 if(substr_count($value, 'id') > 0 && is_numeric($smart_search))
1565 {
1566 $gen_q.="$value = $smart_search OR ";
1567 }
1568 else if(substr_count($value, 'date') > 0)
1569 {
1570 //$gen_search = wmvc_generate_slug($smart_search, ' ');
1571
1572 $gen_search = $smart_search;
1573
1574 $gen_q.="$value LIKE '%$gen_search%' OR ";
1575 }
1576 else
1577 {
1578 $gen_q.="$value LIKE '%$smart_search%' OR ";
1579 }
1580 }
1581 $gen_q = substr($gen_q, 0, -4);
1582
1583 if(!empty($gen_q))
1584 $WMVC->db->where("($gen_q)");
1585 }
1586
1587 // For column search
1588 if(isset($_GET_clone))
1589 {
1590 $gen_q = '';
1591
1592 foreach($_GET_clone as $key=>$val)
1593 {
1594 if(!empty($val) && in_array($key, $columns))
1595 {
1596 $col_name = $key;
1597 //if(isset($key))
1598 // $col_name = $key;
1599
1600 if(strpos($key, 'skip') !== FALSE) continue;
1601
1602 if(substr($key, -8) == '_exactly')
1603 {
1604 $col_name = substr($key, 0, -8);
1605 $gen_q.=$col_name." = '".$val."' AND ";
1606 }
1607 elseif(substr($key, -4) == '_max')
1608 {
1609 $col_name = substr($key, 0, -4);
1610 $gen_q.=$col_name." <= '".$val."' AND ";
1611 }
1612 else if(substr($key, -4) == '_min')
1613 {
1614 $col_name = substr($key, 0, -4);
1615
1616 $gen_q.=$col_name." >= '".$val."' AND ";
1617 }
1618 elseif(substr_count($key, 'id') > 0 && is_numeric($val))
1619 {
1620 // ID is always numeric
1621
1622 $gen_q.=$col_name." = ".$val." AND ";
1623 }
1624 else if(substr_count($key, 'date') > 0)
1625 {
1626 // DATE VALUES
1627
1628 $gen_search = $val;
1629
1630 $detect_date = strtotime($gen_search);
1631
1632 if(wdk_payments_is_date($val) && $detect_date > 1000)
1633 {
1634 $gen_search = date('Y-m-d H:i:s', $detect_date);
1635 $gen_q.=$col_name." > '".$gen_search."' AND ";
1636 }
1637 else
1638 {
1639 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
1640 }
1641 }
1642 else if(substr_count($key, 'is_') > 0)
1643 {
1644 // CHECKBOXES
1645
1646 if($val=='on')
1647 {
1648 $gen_search = 1;
1649 $gen_q.=$col_name." LIKE '%".$gen_search."%' AND ";
1650 }
1651 else if($val=='off')
1652 {
1653 $gen_q.=$col_name." IS NULL AND ";
1654 }
1655 }
1656 else
1657 {
1658 $gen_q.=$col_name." LIKE '%".$val."%' AND ";
1659 }
1660 }
1661
1662 }
1663
1664 $gen_q = substr($gen_q, 0, -5);
1665
1666 if(!empty($gen_q))
1667 $WMVC->db->where("($gen_q)");
1668 }
1669
1670 // order
1671 if(isset($_GET_clone['order_by']))
1672 {
1673 $_GET_clone['order_by'] = str_replace('post_id', $WMVC->db->prefix.'wdk_messages.post_id', $_GET_clone['order_by']);
1674 $WMVC->db->order_by(wdk_esc_sql(sanitize_text_field($_GET_clone['order_by']), true));
1675 }
1676
1677 }
1678 }
1679
1680 function wdk_date() {
1681 $date_format = get_option('date_format');
1682 $time_format = get_option('time_format');
1683 $date = date("{$date_format} {$time_format}", current_time('timestamp'));
1684 return $date;
1685 }
1686
1687 if(!function_exists('wdk_placeholder_image_src')) {
1688 function wdk_placeholder_image_src () {
1689 $i = WPDIRECTORYKIT_URL.'public/img/placeholder.jpg';
1690
1691 if(wdk_get_option('wdk_placeholder')) {
1692 $image = wp_get_attachment_image_src(wdk_get_option('wdk_placeholder'), 'full' );
1693 if(!empty($image) && file_exists(str_replace(WP_CONTENT_URL, WP_CONTENT_DIR, $image[0])))
1694 $i = $image[0];
1695 }
1696
1697 return $i;
1698 }
1699 }
1700
1701
1702 function wdk_wp_frontend_paginate($total_items, $per_page = 10, $page_var = 'wmvc_paged', $texts = array(), $enable_latest_first = TRUE, $enable_count = FALSE, $enable_compact = FALSE, $limit_items = 1)
1703 {
1704 $current_page = 1;
1705
1706 if(isset($_GET[$page_var]))
1707 $current_page = intval(wmvc_xss_clean($_GET[$page_var]));
1708
1709 if(!isset($texts['previous_page']))$texts['previous_page'] = esc_html__('Previous page', 'wpdirectorykit');
1710 if(!isset($texts['next_page']))$texts['next_page'] = esc_html__('Next page', 'wpdirectorykit');
1711 if(!isset($texts['first_page']))$texts['first_page'] = '';
1712 if(!isset($texts['last_page']))$texts['last_page'] = '';
1713 if(!isset($texts['items']))$texts['items'] = esc_html__('items', 'wpdirectorykit');
1714
1715 if(empty($current_page))$current_page = 1;
1716
1717 // get url
1718 $url = strtok(wdk_server_current_url(), '?');
1719
1720
1721 $qs_parameters = wmvc_xss_clean( $_GET );
1722 unset($qs_parameters[$page_var]);
1723 $qs_part = http_build_query($qs_parameters);
1724 $url = wdk_url_suffix($url, $qs_part);
1725
1726 // total pages
1727 $total_pages = intval($total_items/$per_page+0.99);
1728
1729 if($current_page == 1) {
1730 $limit_items = $limit_items * 2;
1731 }
1732
1733 if($current_page == $total_pages) {
1734 $limit_items = $limit_items * 2;
1735 }
1736
1737 $output = '<nav class="wdk-pagination navigation pagination" role="navigation">';
1738 if($enable_count){
1739 $output.= '<span class="displaying-num">'.$total_items.' '.$texts['items'].'</span>';
1740 }
1741
1742 $output .= '<div class="nav-links">';
1743
1744 if($enable_latest_first && $current_page-1 > 0)
1745 $output.= '<a class="next page-numbers scroll-ignore" href="'.esc_url($url).'#results"><span class="screen-reader-text">'.esc_html($texts['first_page']).'</span><span aria-hidden="true">«</span></a>';
1746
1747 if ($current_page-1 > 0) {
1748
1749 $output.= '<a class="next page-numbers scroll-ignore" href="'.esc_url(wdk_url_suffix($url,esc_attr($page_var).'='.esc_attr($current_page-1))).'#results"><span class="screen-reader-text">'.esc_html($texts['previous_page']).'</span><span aria-hidden="true">‹</span></a>';
1750 } elseif($enable_compact)
1751 {
1752 $output.= '<span class="next page-numbers disabled " href=""><span class="screen-reader-text">'.esc_html($texts['previous_page']).'</span><span aria-hidden="true">‹</span></span>';
1753 }
1754
1755 if (!$enable_compact) {
1756 for ($i = 1 ; $i <= $total_pages; $i++) {
1757 $class = ($current_page == $i) ? "active" : "";
1758 if(($current_page-$limit_items) <= $i && ($current_page+$limit_items) >= $i) {
1759 if (($current_page == $i)) {
1760 $output.= '<span aria-current="page" class="page-numbers current">'.$i.'</span>';
1761 } else {
1762 $output.= '<a class="page-numbers scroll-ignore" href="'.esc_url(wdk_url_suffix($url, esc_attr($page_var).'='.esc_attr($i))).'#results">'.esc_attr($i).'</a>';
1763 }
1764 }
1765 }
1766 } else {
1767 $output.= '<span class="wdk_pages_range">'.$current_page.' '.esc_html__('of','wpdirectorykit').' '.$total_pages.'</span>';
1768 }
1769
1770 if($current_page+1 <= $total_pages)
1771 {
1772 $output.= '<a class="next page-numbers scroll-ignore" href="'.esc_url(wdk_url_suffix($url, esc_attr($page_var).'='.esc_attr($current_page+1))).'#results"><span class="screen-reader-text">'.esc_html($texts['next_page']).'</span><span aria-hidden="true">›</span></a>';
1773 }
1774 elseif($enable_compact)
1775 {
1776 $output.= '<a class="next page-numbers disabled scroll-ignore" href=""><span class="screen-reader-text">'.esc_html($texts['next_page']).'</span><span aria-hidden="true">›</span></a>';
1777 }
1778
1779 if($enable_latest_first && $current_page+1 <= $total_pages)
1780 $output.= '<a class="next page-numbers scroll-ignore" href="'.esc_url(wdk_url_suffix($url, esc_attr($page_var).'='.esc_attr($total_pages))).'#results"><span class="screen-reader-text">'.esc_html($texts['last_page']).'</span><span aria-hidden="true">»</span></a>';
1781
1782
1783 $output.= '</div>';
1784 $output.= '</nav>';
1785
1786 return $output;
1787 }
1788
1789 function wdk_viewe($content) {
1790 // @codingStandardsIgnoreStart
1791 echo wp_kses_post($content); // WPCS: XSS ok, sanitization ok.
1792 // @codingStandardsIgnoreEnd
1793 }
1794
1795
1796 if(!function_exists('wdk_search_fields_toggle')){
1797 function wdk_search_fields_toggle ($class_add = NULL){
1798 static $wdk_visible_filters = 0;
1799 global $wdk_visible_filters_limit;
1800 global $wdk_button_search_defined;
1801 global $wdk_enable_search_fields_toggle;
1802 global $wdk_activate_more;
1803
1804 if(!$wdk_enable_search_fields_toggle) return false;
1805
1806 global $wdk_search_fields_toggle_reset;
1807 if($wdk_search_fields_toggle_reset) {
1808 $wdk_visible_filters = 0;
1809 $wdk_search_fields_toggle_reset = false;
1810 }
1811
1812 $wdk_visible_filters++;
1813
1814 if($wdk_activate_more || (!empty($wdk_visible_filters_limit) && !$wdk_button_search_defined && $wdk_visible_filters == $wdk_visible_filters_limit)){
1815 $wdk_button_search_defined=true;
1816 $wdk_activate_more = false;
1817
1818 global $wdk_text_search_button;
1819 if(empty($wdk_text_search_button))
1820 $wdk_text_search_button = esc_html__('Search','wpdirectorykit');
1821
1822 global $wdk_text_reset_button;
1823 if(empty($wdk_text_reset_button))
1824 $wdk_text_reset_button = esc_html__('Reset','wpdirectorykit');
1825
1826 global $wdk_text_more_button;
1827 if(empty($wdk_text_more_button))
1828 $wdk_text_more_button = esc_html__('More','wpdirectorykit');
1829
1830 $form_closed = 'display: none;';
1831 if(isset($_GET['wdk_search_additional_opened']) && wmvc_xss_clean($_GET['wdk_search_additional_opened']) == 1) {
1832 $form_closed = '';
1833 }
1834
1835 ?>
1836 <div class="wdk-col wdk-col-btns">
1837 <div class="wdk-field wdk-field-btn">
1838 <div class="wdk-field-group wdk-field-group-additional">
1839 <button id="wdk-search-additional" type="button" class="wdk-search-additional-btn"><?php echo esc_html($wdk_text_more_button); ?><i class="wdk-toggle-icon"></i></button>
1840 <input type='checkbox' style="display: none !important" value='1' <?php if(isset($_GET['wdk_search_additional_opened']) && wmvc_xss_clean($_GET['wdk_search_additional_opened']) == 1):?> checked <?php endif;?> name='wdk_search_additional_opened' />
1841 </div>
1842 <div class="wdk-field-group wdk-field-group-reset">
1843 <button title="<?php echo esc_attr__('Reset','wpdirectorykit');?>" id="wdk-reset-primary" type="reset" class="wdk-search-start wdk-search-reset wdk-click-load-animation"><?php echo esc_html($wdk_text_reset_button);?></button>
1844 </div>
1845 <?php if (function_exists('fpai_register_settings')):?>
1846 <div class="wdk-field-group wdk-field-group-ai-search">
1847 <button title="<?php echo esc_attr__('Ai Search','wpdirectorykit');?>" type="button" class="wdk-ai-search"><?php echo esc_html__('Ai Search','wpdirectorykit');?></button>
1848 </div>
1849 <?php endif;?>
1850 <div class="wdk-field-group wdk-field-group-search">
1851 <button title="<?php echo esc_attr__('Search','wpdirectorykit');?>" id="wdk-start-primary" type="submit" class="wdk-search-start wdk-click-load-animation">&nbsp;&nbsp;<?php echo esc_html($wdk_text_search_button);?>&nbsp;<i class="fa fa-spinner fa-spin fa-ajax-indicator" style="display: none;"></i>&nbsp;</button>
1852
1853 <?php if(function_exists('run_wdk_save_search') && get_option('wdk_save_search_show_on_searchform')):?>
1854 <div class="section-widget-control right">
1855 <a class="wdk-c-btn wdk-c-edit wdk-save-search-button" href="#" data-url="<?php echo esc_url(admin_url('admin-ajax.php')); ?>" title="<?php echo esc_attr_e('Save Search', 'selio'); ?>" target="_blank">
1856 <i class="fas fa-save" aria-hidden="true"></i>
1857 <i class="fa fa-spinner fa-spin fa-ajax-indicator"></i>
1858 </a>
1859 </div>
1860 <?php endif;?>
1861 </div>
1862
1863 </div>
1864 </div>
1865 <div id='wdk-form-additional' class="wdk-col" style="<?php echo esc_attr($form_closed) ;?>">
1866 <div class="wdk-row">
1867 <?php
1868 }
1869 }
1870 }
1871
1872
1873 /*
1874 * @param $filter_ids string|array, included ids, what will be visible, other skiped, if set 1_fetch_child, where 1 is category_id, will be detected all childs and filtered, for visible
1875 *
1876 */
1877 if ( ! function_exists('wdk_treefield_option'))
1878 {
1879 function wdk_treefield_option($name = '', $table=NULL, $selected = NULL,
1880 $column = 'category_title', $language_id=NULL, $empty_value='', $filter_ids = '', $user_check = FALSE, $sql_where='', $hide_fields = '')
1881 {
1882 $WMVC = &wdk_get_instance();
1883
1884 if(is_array($filter_ids)) $filter_ids = implode(',', $filter_ids);
1885
1886 static $counter = 0;
1887
1888 $model_name = $table;
1889 if($table == 'calendar_listing_m')
1890 $model_name = 'listing_m';
1891
1892 $table_name = str_replace('_m', '', $table);
1893
1894 $attribute_id = 'id'.$table_name;
1895
1896 if($table_name == 'icons_list') {
1897
1898 } else {
1899 $WMVC->model($model_name);
1900 $attribute_id = $WMVC ->$model_name->_primary_key;
1901 $selected = (int) $selected;
1902 }
1903
1904 if(empty($selected))
1905 $selected='';
1906
1907 $form = '<input name="'.$name.'" value="'.$selected.'" class="wdk-hidden" type="text" id="wdktreeelem'.$counter.'" readonly/>';
1908
1909 $skip_id = '';
1910 //load javascript library
1911 if($counter==0)
1912 {
1913 wp_enqueue_script('wdk-treefield');
1914 wp_enqueue_style('wdk-treefield');
1915 }
1916 ?>
1917 <script>
1918 jQuery(document).ready(function($) {
1919 $('#wdktreeelem<?php echo esc_js($counter);?>:not(.init)').wdkTreefield({
1920 ajax_url: '<?php echo admin_url('admin-ajax.php'); ?>',
1921 ajax_param: {
1922 "page": 'wdk_frontendajax',
1923 "function": 'treefieldid',
1924 "action": 'wdk_public_action',
1925 "wdk_secure": '<?php echo wp_create_nonce( 'wdk_secure_treefieldid' );?>',
1926 "table": '<?php echo esc_js($table); ?>',
1927 "filter_ids": '<?php echo esc_js($filter_ids); ?>',
1928 "start_id": '<?php if(!empty($filter_ids)) esc_js($selected); else echo ""; ?>',
1929 "empty_value": '<?php echo esc_js($empty_value); ?>',
1930 "user_check": '<?php echo esc_js($user_check); ?>',
1931 "sql_where": '<?php echo esc_js($sql_where); ?>',
1932 "hide_fields": '<?php echo esc_js($hide_fields); ?>'
1933 },
1934 attribute_id: '<?php echo esc_js($attribute_id); ?>',
1935 language_id: '<?php echo esc_js($language_id); ?>',
1936 attribute_value: '<?php echo esc_js($column); ?>',
1937 skip_id: '<?php echo esc_js($skip_id); ?>',
1938 empty_value: ' - ',
1939 text_search: '<?php esc_html_e('Search term', 'wpdirectorykit');?>',
1940 text_no_results: '<?php esc_html_e('No results found', 'wpdirectorykit');?>',
1941 callback_selected: function(key) {
1942 $('#wdktreeelem<?php echo esc_js($counter);?>').trigger("change");
1943 }
1944 }).addClass('init');
1945 });
1946 </script>
1947 <?php
1948 $counter++;
1949 return $form;
1950 }
1951 }
1952
1953 /*
1954 * @param $filter_ids string|array, included ids, what will be visible, other skiped, if set 1_fetch_child, where 1 is category_id, will be detected all childs and filtered, for visible
1955 *
1956 */
1957 if ( ! function_exists('wdk_treefield_option_checkboxes'))
1958 {
1959 function wdk_treefield_option_checkboxes($name = '', $table=NULL, $selected = NULL,
1960 $column = 'category_title', $language_id=NULL, $empty_value='', $filter_ids = '', $user_check = FALSE, $sql_where='', $hide_fields = '')
1961 {
1962 $WMVC = &wdk_get_instance();
1963
1964 if(is_array($filter_ids)) $filter_ids = implode(',', $filter_ids);
1965
1966 static $counter = 0;
1967
1968 $model_name = $table;
1969
1970 $table_name = str_replace('_m', '', $table);
1971
1972 $attribute_id = 'id'.$table_name;
1973
1974
1975 $WMVC->model($model_name);
1976 $attribute_id = $WMVC ->$model_name->_primary_key;
1977
1978 $values = '';
1979 if(!empty($selected)){
1980 $ids = array();
1981 if(is_string($selected) && strpos($selected, ',') !== FALSE){
1982 $val_selected = explode(',', $selected);
1983 } elseif($selected){
1984 $val_selected = array($selected);
1985 }
1986
1987 foreach($val_selected as $selected_item) {
1988 if(!empty($selected_item) && is_intval($selected_item)) {
1989 $ids [] = $selected_item;
1990 }
1991 }
1992
1993 /* where in */
1994 if(!empty($ids)){
1995 $WMVC->db->select($WMVC->$table->_table_name.'.*');
1996 $WMVC->db->where($WMVC->$table->_table_name.'.'.$WMVC->$table->_primary_key.' IN(' . implode(',', $ids) . ')', null, false);
1997 $WMVC->db->order_by('FIELD('.$WMVC->$table->_table_name.'.'.$WMVC->$table->_primary_key.', '. implode(',', $ids) . ')');
1998
1999 $results = $WMVC->$table->get();
2000 foreach ($results as $item) {
2001 if($item) {
2002 $values .= wmvc_show_data($column, $item, false, TRUE, TRUE).',';
2003 }
2004 }
2005 $values = substr($values,0,-1);
2006
2007 if(strlen($values)>23) {
2008 $values = substr($values,0,20).'...';
2009 }
2010 }
2011 }
2012
2013 if(empty($values)) {
2014 $values = $empty_value;
2015 }
2016
2017 $form = '<input name="'.$name.'" value="'.esc_html($selected).'" data-placehoder="'.esc_html($values).'" class="wdk-hidden" type="text" id="wdktreeelem_checkbox'.$counter.'" readonly/>';
2018
2019 $skip_id = '';
2020 //load javascript library
2021 if($counter==0)
2022 {
2023 wp_enqueue_script('wdk-treefield');
2024 wp_enqueue_style('wdk-treefield');
2025 }
2026 ?>
2027 <script>
2028 jQuery(document).ready(function($) {
2029 $('#wdktreeelem_checkbox<?php echo esc_js($counter);?>:not(.init)').wdkTreefieldCheckboxes({
2030 ajax_url: '<?php echo admin_url('admin-ajax.php'); ?>',
2031 ajax_param: {
2032 "page": 'wdk_frontendajax',
2033 "function": 'treefieldid_checkboxes',
2034 "action": 'wdk_public_action',
2035 "wdk_secure": '<?php echo wp_create_nonce( 'wdk_secure_treefieldid_checkboxes' );?>',
2036 "table": '<?php echo esc_js($table); ?>',
2037 "filter_ids": '<?php echo esc_js($filter_ids); ?>',
2038 "empty_value": '<?php echo esc_js($empty_value); ?>',
2039 "user_check": '<?php echo esc_js($user_check); ?>',
2040 "hide_fields": '<?php echo esc_js($hide_fields); ?>',
2041 },
2042 selected: '<?php echo esc_js($selected); ?>',
2043 attribute_id: '<?php echo esc_js($attribute_id); ?>',
2044 language_id: '<?php echo esc_js($language_id); ?>',
2045 attribute_value: '<?php echo esc_js($column); ?>',
2046 skip_id: '<?php echo esc_js($skip_id); ?>',
2047 empty_value: ' - ',
2048 text_search: '<?php esc_html_e('Search term', 'wpdirectorykit');?>',
2049 text_no_results: '<?php esc_html_e('No results found', 'wpdirectorykit');?>',
2050 callback_selected: function(key) {
2051 $('#wdktreeelem_checkbox<?php echo esc_js($counter);?>').trigger("change");
2052 }
2053 }).addClass('init');
2054 });
2055 </script>
2056 <?php
2057 $counter++;
2058 return $form;
2059 }
2060 }
2061
2062 if ( ! function_exists('wdk_filter_decimal'))
2063 {
2064 function wdk_filter_decimal($string = '')
2065 {
2066 if(wdk_get_option('wdk_enable_filter_zero_decimal')) {
2067 if(substr($string, -3, 3) === ",00") {
2068 return substr($string, 0, -3);
2069 }
2070 if(substr($string, -3, 3) === ".00") {
2071 return substr($string, 0, -3);
2072 }
2073 if(substr($string, -3, 1) === "." && substr($string, -1, 1) === "0") {
2074 return substr($string, 0, -1);
2075 }
2076 }
2077
2078 return $string;
2079 }
2080 }
2081
2082 if ( ! function_exists('wdk_is_date'))
2083 {
2084 function wdk_is_date($date, $format = 'Y-m-d H:i:s')
2085 {
2086
2087 /* check is date on strtotime */
2088 if((bool)strtotime($date)){
2089 return true;
2090 }
2091
2092 /* check is date from argument */
2093 $d = \DateTime::createFromFormat($format, $date);
2094 if($d) {
2095 return true;
2096 }
2097
2098 /* check is date from wp date and time */
2099 $d = \DateTime::createFromFormat(get_option('date_format').' '.get_option('time_format'), $date);
2100 if($d) {
2101 return true;
2102 }
2103
2104 /* check is date from wp date */
2105 $d = \DateTime::createFromFormat(get_option('date_format'), $date);
2106 if($d) {
2107 return true;
2108 }
2109
2110 /* try with default */
2111 if('Y-m-d H:i:s' != $format) {
2112 $d = \DateTime::createFromFormat('Y-m-d H:i:s', $date);
2113 if($d) {
2114 return true;
2115 }
2116
2117 $d = \DateTime::createFromFormat('Y-m-d', $date);
2118 if($d) {
2119 return true;
2120 }
2121 }
2122
2123 /* issue with pm/am inside date, example bug format like "2023 01 19 pm8:06" => 'Y n j ag:i' */
2124 $format = get_option('date_format').' '.get_option('time_format');
2125 if(strpos($format, 'a') !== FALSE) {
2126 $format = str_replace('a', '',$format).' a';
2127 if(strpos($date, 'am') !== FALSE) {
2128 $date = str_replace('am', '',$date).' am';
2129 }
2130 if(strpos($date, 'pm') !== FALSE) {
2131 $date = str_replace('pm', '',$date).' pm';
2132 }
2133 $d = \DateTime::createFromFormat($format, $date);
2134 if($d) {
2135 return true;
2136 }
2137 }
2138
2139 return false;
2140 }
2141 }
2142
2143
2144 if ( ! function_exists('wdk_normalize_date_db'))
2145 {
2146 /**
2147 * Convert date to db format, from wp format
2148 * @param string $date Date in string
2149 * @param string $format Special format
2150 * @param string $format Special format
2151 * @param string $return_format return date format
2152 * @return string date in format Y-m-d H:i:s
2153 */
2154 function wdk_normalize_date_db($date, $format = 'Y-m-d H:i:s', $return_format = 'Y-m-d H:i:s')
2155 {
2156
2157 /* check is date from argument */
2158 $d = \DateTime::createFromFormat($format, $date);
2159 if($d) {
2160 return $d->format($return_format);
2161 }
2162
2163 /* check is date from wp date and time */
2164 $d = \DateTime::createFromFormat(get_option('date_format').' '.get_option('time_format'), $date);
2165 if($d) {
2166 return $d->format($return_format);
2167 }
2168
2169 /* check is date from wp date */
2170 $d = \DateTime::createFromFormat(get_option('date_format'), $date);
2171 if($d) {
2172 return $d->format($return_format);
2173 }
2174
2175 /* try with default */
2176 if('Y-m-d H:i:s' != $format) {
2177 $d = \DateTime::createFromFormat('Y-m-d H:i:s', $date);
2178 if($d) {
2179 return $d->format($return_format);
2180 }
2181
2182 $d = \DateTime::createFromFormat('Y-m-d', $date);
2183 if($d) {
2184 return $d->format($return_format);
2185 }
2186 }
2187
2188 /* issue with pm/am inside date, example bug format like "2023 01 19 pm8:06" => 'Y n j ag:i' */
2189 $format = get_option('date_format').' '.get_option('time_format');
2190 if(strpos($format, 'a') !== FALSE) {
2191 $format = str_replace('a', '',$format).' a';
2192 if(strpos($date, 'am') !== FALSE) {
2193 $date = str_replace('am', '',$date).' am';
2194 }
2195 if(strpos($date, 'pm') !== FALSE) {
2196 $date = str_replace('pm', '',$date).' pm';
2197 }
2198 $d = \DateTime::createFromFormat($format, $date);
2199 if($d) {
2200 return $d->format($return_format);
2201 }
2202 }
2203
2204 /* check is date on strtotime */
2205 if((bool)strtotime($date)){
2206 return date($return_format, strtotime($date));
2207 }
2208
2209 return false;
2210 }
2211 }
2212
2213 if ( ! function_exists('wdk_url_suffix'))
2214 {
2215 function wdk_url_suffix($base_url, $extension_url="")
2216 {
2217 if(substr($base_url, -1) == '?'){
2218 $base_url .='';
2219 } elseif(strpos($base_url,'?') !== FALSE){
2220 $base_url .='&';
2221 } else {
2222 $base_url .='?';
2223 }
2224 return $base_url.$extension_url;
2225 }
2226 }
2227
2228
2229 /**
2230 * Insert an attachment from a remote URL.
2231 *
2232 * @param string $url Remote file URL.
2233 * @param int|null $parent_post_id Post ID to attach the image to.
2234 * @return int|false Attachment ID or false on failure.
2235 */
2236 function wdk_insert_attachment_from_cloud_url($url, $parent_post_id = null) {
2237 // Request with headers (Google blocks requests without UA sometimes)
2238 $response = wp_remote_get($url, array(
2239 'timeout' => 30,
2240 'redirection' => 5,
2241 'headers' => array(
2242 'User-Agent' => 'Mozilla/5.0 (WordPress)',
2243 'Referer' => home_url()
2244 )
2245 ));
2246
2247 if (is_wp_error($response)) {
2248 return false;
2249 }
2250
2251 $code = wp_remote_retrieve_response_code($response);
2252 if ($code != 200) {
2253 return false;
2254 }
2255
2256 $body = wp_remote_retrieve_body($response);
2257 if (empty($body)) {
2258 return false;
2259 }
2260
2261 // Try to get filename from URL or headers
2262 $filename = basename(parse_url($url, PHP_URL_PATH));
2263
2264 // If filename empty (Google Drive case)
2265 if (!$filename || strpos($filename, '.') === false) {
2266 // Try content-disposition header
2267 $headers = wp_remote_retrieve_headers($response);
2268 if (!empty($headers['content-disposition']) &&
2269 preg_match('/filename="?([^"]+)"?/i', $headers['content-disposition'], $matches)) {
2270 $filename = sanitize_file_name($matches[1]);
2271 }
2272 }
2273
2274 // If still no extension, detect from mime
2275 $ext = pathinfo($filename, PATHINFO_EXTENSION);
2276 if (empty($ext)) {
2277 $data = getimagesizefromstring($body);
2278 if (!$data || empty($data['mime'])) {
2279 return false;
2280 }
2281 $ext = wdk_mime2ext($data['mime']);
2282 $filename = time() . '-' . wp_generate_password(6, false) . '.' . $ext;
2283 }
2284
2285 // Save file to uploads dir
2286 $upload = wp_upload_bits($filename, null, $body);
2287 if (!empty($upload['error'])) {
2288 return false;
2289 }
2290
2291 $file_path = $upload['file'];
2292 $file_name = basename($file_path);
2293 $file_type = wp_check_filetype($file_name, null);
2294 $wp_upload_dir = wp_upload_dir();
2295
2296 $post_info = array(
2297 'guid' => $wp_upload_dir['url'] . '/' . $file_name,
2298 'post_mime_type' => $file_type['type'],
2299 'post_title' => sanitize_file_name(pathinfo($file_name, PATHINFO_FILENAME)),
2300 'post_content' => '',
2301 'post_status' => 'inherit',
2302 );
2303
2304 // Insert attachment
2305 $attach_id = wp_insert_attachment($post_info, $file_path, $parent_post_id);
2306
2307 if (!$attach_id) {
2308 return false;
2309 }
2310
2311 // Generate metadata
2312 require_once ABSPATH . 'wp-admin/includes/image.php';
2313 $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
2314 wp_update_attachment_metadata($attach_id, $attach_data);
2315
2316 return $attach_id;
2317 }
2318
2319 /**
2320 * Insert an attachment from an URL address.
2321 *
2322 * @param String $url
2323 * @param Int $parent_post_id
2324 * @return Int Attachment ID
2325 */
2326 function wdk_insert_attachment_from_url($url, $parent_post_id = null) {
2327
2328 if( !class_exists( 'WP_Http' ) )
2329 include_once( ABSPATH . WPINC . '/class-http.php' );
2330
2331 $http = new WP_Http();
2332 $response = $http->request( $url );
2333 if( is_wp_error($response) || $response['response']['code'] != 200 ) {
2334 return false;
2335 }
2336
2337 $filename = basename($url);
2338 if(strpos($filename, '?')!==FALSE) {
2339 $filename = substr($filename, 0, strpos($filename, '?'));
2340 }
2341
2342 /* if unsoported extension */
2343 if(in_array(wdk_file_extension($filename), array('php','asp')) || strlen(wdk_file_extension($filename)) > 5){
2344 $data = getimagesizefromstring($response['body']);
2345 if(!$data) return false;
2346 if(empty($data['mime'])) return false;
2347
2348 $filename = time().rand(0000,9999).'.'.wdk_mime2ext($data['mime']);
2349 }
2350 $upload = wp_upload_bits( $filename, null, $response['body'] );
2351
2352 if( !empty( $upload['error'] ) ) {
2353 return false;
2354 }
2355
2356 $file_path = $upload['file'];
2357 $file_name = basename( $file_path );
2358 $file_type = wp_check_filetype( $file_name, null );
2359 $attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
2360 $wp_upload_dir = wp_upload_dir();
2361
2362 $post_info = array(
2363 'guid' => $wp_upload_dir['url'] . '/' . $file_name,
2364 'post_mime_type' => $file_type['type'],
2365 'post_title' => $attachment_title,
2366 'post_content' => '',
2367 'post_status' => 'inherit',
2368 );
2369 // Create the attachment
2370 $attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );
2371
2372 // Include image.php
2373 require_once( ABSPATH . 'wp-admin/includes/image.php' );
2374
2375 // Define attachment metadata
2376 $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
2377
2378 // Assign metadata to attachment
2379 wp_update_attachment_metadata( $attach_id, $attach_data );
2380
2381 return $attach_id;
2382
2383 }
2384
2385 if(!function_exists('wdk_jsdateformat')) {
2386 function wdk_jsdateformat($format = '') {
2387 $date_specific = array(
2388 // Day
2389 'd' => 'dd',
2390 'D' => 'D',
2391 'j' => 'd',
2392 'l' => 'DD',
2393 'N' => '',
2394 'S' => '',
2395 'w' => '',
2396 'z' => 'o',
2397 // Week
2398 'W' => '',
2399 // Month
2400 'F' => 'MM',
2401 'm' => 'mm',
2402 'M' => 'M',
2403 'n' => 'm',
2404 't' => '',
2405 // Year
2406 'L' => '',
2407 'o' => '',
2408 'y' => 'y',
2409 'Y' => 'yy',
2410 // Time
2411 'a' => '',
2412 'A' => '',
2413 'B' => '',
2414 'g' => '',
2415 'G' => '',
2416 'h' => '',
2417 'H' => '',
2418 'i' => '',
2419 's' => '',
2420 'u' => ''
2421 );
2422 return str_replace(array_keys($date_specific), array_values($date_specific), $format);
2423 }
2424
2425 }
2426
2427 function wdk_current_url()
2428 {
2429 global $wp;
2430 return add_query_arg( $wp->query_vars, home_url( $wp->request ) );
2431 }
2432
2433 if(!function_exists('wdk_generate_profile_permalink')) {
2434 /**
2435 * Insert user id and return link on user profile page
2436 *
2437 * @return Int user ID
2438 */
2439
2440 function wdk_generate_profile_permalink($profile = array())
2441 {
2442 $profile_slug = '';
2443 if(is_intval($profile)){
2444 $profile_data = get_userdata($profile);
2445 if(wmvc_show_data('wdk_slug', $profile_data, false)){
2446 $profile_slug = wmvc_show_data('wdk_slug', $profile);
2447 }elseif(wmvc_show_data('user_login', $profile_data, false)){
2448 $profile_slug = wmvc_show_data('user_login', $profile_data);
2449 } else {
2450 $profile_slug = $profile;
2451 }
2452 } else if(wmvc_show_data('user_login', $profile, false)){
2453 $profile_slug = wmvc_show_data('user_login', $profile);
2454 if(wmvc_show_data('wdk_slug', $profile))
2455 $profile_slug = wmvc_show_data('wdk_slug', $profile);
2456 }
2457
2458 $user_profile_page = get_option('wdk_membership_profile_preview_page');
2459 if(!$user_profile_page) {
2460 return '#';
2461 }
2462 // for polylang to detect translated page version
2463 if(function_exists('pll_get_post'))
2464 $user_profile_page = pll_get_post($user_profile_page);
2465
2466 return wdk_url_suffix(get_permalink($user_profile_page), 'slug='. $profile_slug);
2467 }
2468 }
2469
2470 if(!function_exists('wdk_get_profile_page_id')) {
2471 /**
2472 * Insert user id and return link on user profile page
2473 *
2474 * @return Int user ID
2475 */
2476
2477 function wdk_get_profile_page_id()
2478 {
2479 global $wp_query;
2480 if(get_option('wdk_membership_profile_preview_page') && isset($wp_query->post) && get_option('wdk_membership_profile_preview_page') == $wp_query->post->ID) {
2481 if (wmvc_show_data('slug', $_GET, false)) {
2482 if(is_intval(wmvc_show_data('slug', $_GET))) {
2483 return wmvc_show_data('slug', $_GET);
2484 } else {
2485
2486 $args = array(
2487 'meta_key' => 'wdk_slug',
2488 'meta_value' => sanitize_text_field(wmvc_show_data('slug', $_GET)),
2489 'meta_compare' => '='
2490 );
2491 $by_slug_user_detected = get_users($args);
2492
2493 $profile = false;
2494 if(!empty($by_slug_user_detected)) {
2495 $profile = $by_slug_user_detected[0];
2496 } else {
2497 $profile = get_user_by('login',wmvc_show_data('slug', $_GET));
2498 }
2499
2500 return (wmvc_show_data('ID', $profile, false)) ? wmvc_show_data('ID', $profile, false) : false;
2501 }
2502 }
2503 }
2504
2505 return false;
2506 }
2507 }
2508
2509 if(!function_exists('wdk_get_date')) {
2510 /**
2511 * Return date in format
2512 *
2513 */
2514 function wdk_get_date($datetime = NULL, $time = TRUE, $default='timestamp')
2515 {
2516 $init_datetime = $datetime;
2517 if(is_null($datetime))
2518 {
2519 if($default == 'timestamp')
2520 {
2521 $datetime = current_time('timestamp');
2522 }
2523 else
2524 {
2525 return $default;
2526 }
2527 }
2528 else if(!is_numeric($datetime))
2529 {
2530 $datetime = strtotime($datetime);
2531 }
2532
2533 $date_format = get_option('date_format');
2534
2535 $time_format = ($time && strpos($init_datetime, '00:00:00')===FALSE) ? get_option('time_format') : '';
2536
2537 $date = date_i18n("{$date_format} {$time_format}", $datetime);
2538 return $date;
2539 }
2540 }
2541
2542 if(!function_exists('wdk_login_url')) {
2543 /**
2544 * Return date in format
2545 * @param string|url redirect url
2546 * @param string custom_message, showed on login form like alert, visible only on wdk login form
2547 */
2548 function wdk_login_url($url_redirect = '', $custom_message = '')
2549 {
2550 $url = wp_login_url($url_redirect);
2551
2552 if(get_option('wdk_membership_login_page')){
2553 $url = wdk_url_suffix(get_permalink(get_option('wdk_membership_login_page')));
2554 if(!empty($url_redirect)) {
2555 $url = wdk_url_suffix(get_permalink(get_option('wdk_membership_login_page')), 'redirect_to='. urlencode($url_redirect));
2556 }
2557 if(!empty($custom_message)) {
2558 $url = wdk_url_suffix(get_permalink(get_option('wdk_membership_login_page')), 'custom_message='. urlencode($custom_message));
2559 }
2560 }
2561
2562 return trim($url, '?');
2563 }
2564 }
2565
2566 if(!function_exists('wdk_mail')) {
2567 /**
2568 * Return date in format
2569 * @param string|url redirect url
2570 */
2571 function wdk_mail( $email_to, $subject = '', $data = array(), $layout = 'default', $email_from = '', $attachments = array(), $reply_to = '')
2572 {
2573 $WMVC = &wdk_get_instance();
2574
2575 $ret = false;
2576 if(empty($email_from))
2577 $email_from = get_bloginfo('admin_email');
2578
2579 if(empty($subject))
2580 $subject = __("New message", "wpdirectorykit");
2581
2582 $headers = array('Content-Type: text/html; charset=UTF-8');
2583 $headers[] = 'From: "'.get_bloginfo('name').'" <'.$email_from.'>';
2584
2585 if(!empty($reply_to)) {
2586 $headers[] = 'Reply-To: '.$reply_to;
2587 } else {
2588 $headers[] = 'Reply-To: '.$email_from;
2589 }
2590
2591 $data['subject'] = $subject;
2592
2593 $message = $WMVC->view('email/'.$layout, $data, FALSE);
2594 $ret = wp_mail( $email_to, $subject, $message, $headers, $attachments );
2595
2596 return $ret;
2597 }
2598 }
2599
2600 if(!function_exists('wdk_show_data')) {
2601 function wdk_show_data($field_name, &$db_value = NULL, $default = '', $xss_clean = TRUE, $skip_post = FALSE)
2602 {
2603 if(!$skip_post && isset($_POST[$field_name]))
2604 {
2605 if($xss_clean === FALSE)
2606 return stripslashes($_POST[$field_name]);
2607
2608 return wmvc_xss_clean(stripslashes($_POST[$field_name]));
2609 }
2610
2611
2612 if(is_array($db_value))
2613 {
2614 if(isset($db_value[$field_name]))
2615 {
2616 if($xss_clean === FALSE)
2617 return $db_value[$field_name];
2618
2619 return wmvc_xss_clean($db_value[$field_name]);
2620 }
2621 else
2622 {
2623 return $default;
2624 }
2625 }
2626
2627 if(is_object($db_value))
2628 {
2629 if(isset($db_value->$field_name))
2630 {
2631 if($xss_clean === FALSE)
2632 return $db_value->$field_name;
2633
2634 return wmvc_xss_clean($db_value->$field_name);
2635 }
2636 else
2637 {
2638 return $default;
2639 }
2640 }
2641
2642 if(!empty($db_value))
2643 {
2644 if($xss_clean === FALSE)
2645 return $db_value;
2646
2647 return wmvc_xss_clean($db_value);
2648 }
2649
2650 if($xss_clean === FALSE)
2651 return $default;
2652
2653 return wmvc_xss_clean($default);
2654 }
2655 }
2656
2657
2658 if (!function_exists('wdk_input_checked'))
2659 {
2660 function wdk_input_checked($field_id, $db_data, $value = 1)
2661 {
2662
2663 if(wmvc_show_data($field_id, $db_data, false) && wmvc_show_data($field_id, $db_data) == $value)
2664 {
2665 return 'checked';
2666 }
2667
2668 return '';
2669 }
2670 }
2671
2672 function wdk_upload_file($field_name, $file_id)
2673 {
2674 static $media_element_counter = 0;
2675
2676 $media_element_counter++;
2677
2678 $img_field = $field_name.'_'.$media_element_counter;
2679
2680 wp_register_script( 'wpmediaelement_file', WPDIRECTORYKIT_URL . 'admin/js/jquery.wpmediaelement_file.js', array( 'jquery' ), false, false );
2681 wp_enqueue_script( 'wpmediaelement_file' );
2682 wp_enqueue_media();
2683
2684 ?>
2685 <div id="<?php echo esc_attr($field_name); ?>meta-box-id" class="postbox-upload">
2686 <?php
2687 // Get WordPress' media upload URL
2688 $upload_link = '#';
2689
2690 // Get the file src
2691
2692 // Get the file src
2693 $your_file_src = get_attached_file(intval( $file_id));
2694
2695 // For convenience, see if the array is valid
2696 $you_have_file = false;
2697 if($your_file_src)
2698 $you_have_file = basename($your_file_src);
2699
2700 ?>
2701
2702 <!-- Your file container, which can be manipulated with js -->
2703 <div class="custom-img-container">
2704 <?php if ( $you_have_file ) : ?>
2705 <?php echo esc_html($you_have_file); ?>
2706 <?php endif; ?>
2707 </div>
2708
2709 <?php //if(sw_user_in_role('administrator')): ?>
2710 <!-- Your add & remove file links -->
2711 <p class="hide-if-no-js">
2712 <a class="upload-custom-img <?php if ( $you_have_file ) { echo 'hidden'; } ?>"
2713 href="<?php echo esc_url($upload_link) ?>">
2714 <?php echo esc_html__('Select file','wmvc_win') ?>
2715 </a>
2716 <a class="delete-custom-img <?php if ( ! $you_have_file ) { echo 'hidden'; } ?>"
2717 href="#">
2718 <?php echo esc_html__('Remove all files','wmvc_win') ?>
2719 </a>
2720 </p>
2721 <?php //endif; ?>
2722
2723 <!-- A hidden input to set and post the chosen file id -->
2724 <input class="logo_file_id" type="hidden" id="<?php echo esc_attr($field_name); ?>" name="<?php echo esc_attr($field_name); ?>" value="<?php echo esc_attr($file_id); ?>" />
2725 </div>
2726
2727 <?php
2728 $custom_js ='';
2729 $custom_js .=" jQuery(function($) {
2730 if( typeof jQuery.fn.wpMediaElementFile == 'function')
2731 $('#".esc_js($field_name)."meta-box-id.postbox-upload').wpMediaElementFile();
2732 });";
2733
2734 echo "<script>".$custom_js."</script>";
2735
2736 ?>
2737
2738 <?php
2739 }
2740
2741 if ( ! function_exists('wdk_file_extension'))
2742 {
2743 function wdk_file_extension($filepath)
2744 {
2745
2746 /* filters */
2747 if(strpos($filepath, '?') !== FALSE) {
2748 $filepath = $filepath;
2749 $filepath = substr($filepath, 0,strpos($filepath, '?'));
2750 }
2751 if(strpos($filepath, '#') !== FALSE) {
2752 $filepath = $filepath;
2753 $filepath = substr($filepath, 0,strpos($filepath, '#'));
2754 }
2755
2756 return substr($filepath, strrpos($filepath, '.')+1);
2757 }
2758 }
2759
2760 if ( ! function_exists('wdk_file_extension_type'))
2761 {
2762 /**
2763 * Get image type based on extension
2764 *
2765 * @param string $filepath string path(url) to file with extension
2766 * @return string type of file (image,video,docs)
2767 */
2768 function wdk_file_extension_type($filepath = NULL)
2769 {
2770
2771 if(in_array(wdk_file_extension($filepath),array('jpg','jpeg','bmp','png','webp'))) {
2772 return 'image';
2773 }
2774 if(in_array(wdk_file_extension($filepath),array('mp4','mov','flv','mkv','avi','webm'))) {
2775 return 'video';
2776 }
2777
2778 return 'docs';
2779 }
2780 }
2781
2782 function wdk_upload_multi_files($field_name, $image_ids='', $texts = array())
2783 {
2784 static $media_element_counter = 0;
2785
2786 if(!isset($texts['file_select']))$texts['file_select'] = esc_html__('Select file','wmvc_win');
2787 if(!isset($texts['file_remove']))$texts['file_remove'] = esc_html__('Remove all files','wmvc_win');
2788
2789 $media_element_counter++;
2790
2791 $img_field = $field_name.'_'.$media_element_counter;
2792
2793 wp_enqueue_script( 'wpmediamultiple' );
2794 wp_enqueue_script( 'jquery-ui-mouse' );
2795 wp_enqueue_media();
2796
2797 ?>
2798 <div id="<?php echo esc_attr($field_name); ?>meta-box-id" class="postbox-upload-multiple">
2799 <?php
2800 // Get WordPress' media upload URL
2801 $upload_link = '#';
2802
2803
2804 // Get the image src
2805
2806 $your_img_src = array();
2807
2808 foreach(explode(',', $image_ids) as $image_id)
2809 {
2810 if(is_numeric($image_id)){
2811 $src = wp_get_attachment_url( $image_id, 'full' );
2812 if(!in_array(wdk_file_extension($src),array('jpg','jpeg','bmp','png','webp'))) {
2813 if(file_exists(WPDIRECTORYKIT_PATH.'/public/img/filetype/'.wdk_file_extension($src).'.png')) {
2814 $src = WPDIRECTORYKIT_URL.'public/img/filetype/'.wdk_file_extension($src).'.png';
2815 } else {
2816 $src = WPDIRECTORYKIT_URL.'public/img/filetype/_blank.png';
2817 }
2818 }
2819 $your_img_src[$image_id] = $src;
2820 }
2821 }
2822
2823 // For convenience, see if the array is valid
2824 $you_have_img = count($your_img_src) > 0;
2825 ?>
2826
2827 <!-- Your image container, which can be manipulated with js -->
2828 <div class="custom-img-container winter_mvc-media">
2829 <?php if($you_have_img)foreach($your_img_src as $image_id => $img_src) : ?>
2830 <div class="winter_mvc-media-card" data-media-id="<?php echo esc_attr($image_id);?>">
2831 <img src="<?php echo esc_attr($img_src); ?>" style="object-fit: contain;" alt="<?php echo esc_attr__('thumb', 'wmvc_win');?>" style="max-width:100%;" class="thumbnail"/>
2832 <a href="#" class="remove"></a>
2833 </div>
2834 <?php endforeach; ?>
2835 </div>
2836 <br style="clear:both;" />
2837
2838 <?php //if(sw_user_in_role('administrator')): ?>
2839 <!-- Your add & remove image links -->
2840 <p class="hide-if-no-js">
2841 <a class="button button-primary upload-custom-img <?php if ( $you_have_img ) { echo ''; } ?>"
2842 href="<?php echo esc_url($upload_link) ?>">
2843 <?php echo esc_html($texts['file_select']) ?>
2844 </a>
2845 <a class="button button-secondary delete-custom-img <?php if ( ! $you_have_img ) { echo 'hidden'; } ?>"
2846 href="#">
2847 <?php echo esc_html($texts['file_remove']) ?>
2848 </a>
2849 </p>
2850 <?php //endif; ?>
2851
2852 <!-- A hidden input to set and post the chosen image id -->
2853 <input class="logo_image_id" type="hidden" id="<?php echo esc_attr(esc_html($field_name)); ?>" name="<?php echo esc_attr($field_name); ?>" value="<?php echo esc_attr($image_ids); ?>" />
2854 </div>
2855 <?php
2856 $custom_js ='';
2857 $custom_js .=" jQuery(function($) {
2858 if( typeof jQuery.fn.wpMediaMultiple == 'function')
2859 $('#".esc_js($field_name)."meta-box-id.postbox-upload-multiple').wpMediaMultiple({
2860 frame: {
2861 title: '".esc_js(__('Upload and select your images here for use with your listing','wpdirectorykit'))."',
2862 button: '".esc_js(__('Use this media','wpdirectorykit'))."',
2863 },
2864 library: {
2865 type: ['application', 'image', 'video']
2866 },
2867 });
2868 /* order */
2869 var re_order = function(media_element){
2870 var list_media = '';
2871 media_element.find('.winter_mvc-media-card').each(function(){
2872 if(list_media !='')
2873 list_media +=',';
2874
2875 list_media += $(this).attr('data-media-id');
2876 })
2877 media_element.closest('.postbox-upload-multiple').find('.logo_image_id').val(list_media);
2878 }
2879 /* Sort table */
2880 $( '.winter_mvc-media' ).sortable({
2881 update: function(event, ui) {
2882 re_order($(this));
2883 }
2884 });
2885 /* remove media */
2886 $( '.winter_mvc-media' ).find('.winter_mvc-media-card .remove').on('click', function(e){
2887 e.preventDefault();
2888 var media = $(this).closest('.winter_mvc-media')
2889 $(this).closest('.winter_mvc-media-card').remove();
2890 re_order(media)
2891 })
2892 });
2893 ";
2894
2895 echo "<script>".$custom_js."</script>";
2896
2897 ?>
2898
2899 <?php
2900 }
2901
2902
2903 if(!function_exists('wdk_access_check')) {
2904 /**
2905 * Generate listing card html
2906 *
2907 * @param array $listing The listing data.
2908 * @param array $settings The settings.
2909 * @param bool $json_output Encode for json, default false
2910 * @param string $html Html for sprintf(), where
2911 * %1$s - content
2912 * @return string
2913 */
2914 function wdk_access_check($model_name, $item_id, $user_id=NULL, $method='edit') {
2915
2916 if(!empty($item_id) && !is_numeric($item_id))
2917 exit('Issue with ID');
2918
2919 if (in_array($model_name, array('reviews_m','reviews_type_m','reviews_option_m','reviews_data_m'))) {
2920 global $Winter_MVC_wdk_reviews;
2921 $WMVC = $Winter_MVC_wdk_reviews;
2922 }elseif(in_array($model_name,array('package_m','payment_m'))) {
2923 global $Winter_MVC_wdk_payments;
2924 $WMVC = $Winter_MVC_wdk_payments;
2925 }elseif(in_array($model_name,array('favorite_m','favoritecategory_m'))) {
2926 global $Winter_MVC_wdk_favorites;
2927 $WMVC = $Winter_MVC_wdk_favorites;
2928 }elseif(in_array($model_name,array('currency_m'))) {
2929 global $Winter_MVC_wdk_currency;
2930 $WMVC = $Winter_MVC_wdk_currency;
2931 }elseif(in_array($model_name,array('calendar_m','price_m','reservation_m'))) {
2932 global $Winter_MVC_wdk_bookings;
2933 $WMVC = $Winter_MVC_wdk_bookings;
2934 }elseif(in_array($model_name,array('save_search_m'))) {
2935 global $Winter_MVC_wdk_save_search;
2936 $WMVC = $Winter_MVC_wdk_save_search;
2937 }elseif(in_array($model_name,array('messageschat_m'))) {
2938 global $Winter_MVC_wdk_messages_chat;
2939 $WMVC = $Winter_MVC_wdk_messages_chat;
2940 } else {
2941 $WMVC = &wdk_get_instance();
2942 }
2943
2944 if(empty($user_id))
2945 $user_id = get_current_user_id();
2946
2947 if(wmvc_user_in_role('administrator') || current_user_can('wdk_listings_manage')) {
2948 return true;
2949 }
2950
2951 if(substr($model_name,-2,2) == '_m')
2952 {
2953 // its model
2954 $WMVC->model($model_name);
2955
2956 if(empty($item_id) || $WMVC->$model_name->is_related($item_id, $user_id, $method))
2957 {
2958 // User is related
2959 return true;
2960 }
2961 else
2962 {
2963 //echo $CI->db->last_query();
2964 exit('Access denied ROLES RELATED');
2965 }
2966 }
2967 else
2968 {
2969 return true;
2970 }
2971
2972 exit('Access denied ROLES');
2973
2974 }
2975 }
2976
2977 if ( ! function_exists('wdk_recaptcha_field_v3'))
2978 {
2979 function wdk_recaptcha_field_v3($wdk_recaptcha_site_key=null, $wdk_recaptcha_secret_key=null, $load_script=true)
2980 {
2981 static $counter = 0;
2982
2983 if(empty($wdk_recaptcha_site_key) && empty($wdk_recaptcha_site_key)) {
2984 $wdk_recaptcha_site_key = get_option('wdk_recaptcha_site_key_v3');
2985 $wdk_recaptcha_secret_key = get_option('wdk_recaptcha_secret_key_v3');
2986 }
2987
2988 if($wdk_recaptcha_site_key && $wdk_recaptcha_secret_key)
2989 {
2990 if($load_script && $counter===0)
2991 {
2992 echo "<script src='https://www.google.com/recaptcha/api.js?render=".esc_attr(trim($wdk_recaptcha_site_key))."'></script>";
2993 }
2994 $counter++;
2995 ?>
2996 <input type="hidden" name="g-recaptcha-response" id="recaptcha_called_v3_count_<?php echo esc_html($counter);?>">
2997 <script>
2998 (function(){
2999 const field_token = document.getElementById('recaptcha_called_v3_count_<?php echo esc_html($counter);?>');
3000 grecaptcha.ready(function() {
3001 grecaptcha.execute('<?php echo esc_attr(trim($wdk_recaptcha_site_key));?>', {action: 'submit'}).then(function(token) {
3002 field_token.value = token;
3003 });
3004 });
3005
3006 // Reload token after form submit
3007 field_token.closest('form').addEventListener('submit', function(e) {
3008 e.preventDefault();
3009 grecaptcha.execute('<?php echo esc_attr(trim($wdk_recaptcha_site_key));?>', {action: 'submit'}).then(function(token) {
3010 field_token.value = token;
3011 });
3012 });
3013 })();
3014 </script>
3015 <?php
3016 }
3017 }
3018 }
3019
3020
3021 if ( ! function_exists('wdk_recaptcha_field'))
3022 {
3023 function wdk_recaptcha_field($is_compact=false, $style="", $load_script=true)
3024 {
3025 static $counter = 0;
3026 static $recaptcha_array = array();
3027
3028 if(get_option('wdk_recaptcha_site_key') !== FALSE && get_option('wdk_recaptcha_secret_key') !== NULL)
3029 {
3030 if($load_script && $counter===0)
3031 {
3032 echo "<script src='https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&amp;render=explicit'></script>";
3033 }
3034 $counter++;
3035
3036 $compact_tag='';
3037 $size_tag='';
3038 if($is_compact)
3039 {
3040 $compact_tag='data-size="compact"';
3041 $size_tag='compact';
3042 }
3043
3044 $recaptcha_array[$counter] = array('size'=>$size_tag);
3045
3046 echo '<div id="recaptcha_called_'.$counter.'" class="g-recaptcha" style="'.$style.'" '.$compact_tag.' data-sitekey="'.esc_attr(get_option('wdk_recaptcha_site_key')).'"></div>';
3047 ?>
3048
3049 <script>
3050 <?php if($counter===1)echo 'var ';?>CaptchaCallback = function(){
3051 <?php for($j=1;$j<=$counter;$j++): ?>
3052 grecaptcha.render(document.getElementById('recaptcha_called_<?php echo $j;?>'), {'size' : '<?php echo esc_attr($recaptcha_array[$j]['size']); ?>', 'sitekey' : '<?php echo esc_attr(get_option('wdk_recaptcha_site_key')); ?>'});
3053 <?php endfor; ?>
3054 };
3055 </script>
3056
3057 <?php
3058 }
3059 }
3060 }
3061
3062 function is_wdk_valid_recaptcha()
3063 {
3064 if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
3065 //your site secret key
3066 if(wdk_valid_recaptcha_curl($_POST['g-recaptcha-response']))
3067 {
3068 return TRUE;
3069 }
3070 }
3071 return FALSE;
3072 }
3073
3074 function wdk_valid_recaptcha_curl($g_recaptcha_response='') {
3075 $url = 'https://www.google.com/recaptcha/api/siteverify';
3076 $args = array(
3077 'timeout' => 200,
3078 'blocking' => true,
3079 'headers' => array(),
3080 'body' => array(
3081 'secret' => get_option('wdk_recaptcha_secret_key'),
3082 'response' => $g_recaptcha_response,
3083 'remoteip' => sanitize_textarea_field($_SERVER['REMOTE_ADDR'])
3084 ),
3085 'cookies' => array()
3086 );
3087 $response = wp_remote_post( $url, $args );
3088
3089 if ( is_wp_error( $response ) ) {
3090 /*$error_message = $response->get_error_message();*/
3091 return true;
3092 } else {
3093 $response = json_decode($response['body']);
3094 return $response->success;
3095 }
3096 }
3097
3098 if(!function_exists('wdk_get_option')) {
3099 /**
3100 * Cached and get wp options
3101 *
3102 * @param string option Option key
3103 * @return string alt or title
3104 */
3105
3106 function wdk_get_option($option_key = '') {
3107 return get_option($option_key);
3108 if(isset($options[$option_key])) {
3109 return $options[$option_key];
3110 }
3111
3112 $options[$option_key] = get_option($option_key);
3113
3114 return $options[$option_key];
3115 }
3116 }
3117
3118 if(!function_exists('wdk_server_current_url')) {
3119 /**
3120 * Get current url basic on $_SERVER, exists function wdk_current_url(), on some urls have issue on listing preview page
3121 *
3122 * @return string url
3123 */
3124
3125 function wdk_server_current_url()
3126 {
3127 return (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
3128 }
3129 }
3130
3131
3132 if(!function_exists('wdk_filter_date_decimal')) {
3133 /**
3134 * Filter 00:00:00 from date
3135 *
3136 * @param string
3137 * @return string date without 00:00:00
3138 */
3139
3140 function wdk_filter_date_decimal($data)
3141 {
3142 return str_replace(' 00:00:00','', $data);
3143 }
3144 }
3145
3146 function wdk_get_post()
3147 {
3148 $post = array();
3149
3150 foreach($_POST as $key => $val)
3151 {
3152 if(is_array($val))
3153 {
3154 return wdk_clean($_POST);
3155 }
3156 elseif(is_string($val))
3157 {
3158 if(strpos($val, '<iframe') === 0)
3159 $val = str_replace("'",'"', $val);
3160
3161 $post[sanitize_text_field($key)] = wp_kses_post($val);
3162 }
3163 }
3164
3165 return $post;
3166 }
3167
3168
3169 function wdk_get_get()
3170 {
3171 $log_array = array();
3172
3173 foreach($_GET as $key => $val)
3174 {
3175 if(is_array($val))
3176 {
3177 return wdk_clean($_POST);
3178 }
3179 else
3180 {
3181 $log_array[sanitize_text_field($key)] = wp_kses_post($val);
3182 }
3183 }
3184
3185 return $log_array;
3186 }
3187
3188 function wdk_clean($array)
3189 {
3190 $arr_cleaned = array();
3191 foreach($array as $key=>$val)
3192 {
3193 if(is_array($val))
3194 {
3195 $arr_cleaned[sanitize_text_field($key)] = wdk_clean($val);
3196 }
3197 elseif(is_string($val))
3198 {
3199 $arr_cleaned[sanitize_text_field($key)] = wp_kses_post($val);
3200 }
3201
3202 }
3203
3204 //dump($arr_cleaned);
3205
3206 return $arr_cleaned;
3207 }
3208
3209 function wdk_clean_mixed($item)
3210 {
3211 $arr_cleaned = array();
3212
3213 if(is_array($item))
3214 {
3215 foreach($item as $key=>$val)
3216 {
3217 if(is_array($val))
3218 {
3219 $arr_cleaned[sanitize_text_field($key)] = wdk_clean_mixed($val);
3220 }
3221 else
3222 {
3223 $arr_cleaned[sanitize_text_field($key)] = wp_kses_post($val);
3224 }
3225 }
3226 }
3227 else
3228 {
3229 return wp_kses_post($item);
3230 }
3231
3232 return $arr_cleaned;
3233 }
3234
3235 /*
3236 <select class="form-control" name="<?php echo 'control_operator_'.$i_fieldnum; ?>">
3237 <option value="CONTAINS">CONTAINS</option>
3238 <option value="NOT_CONTAINS">NOT_CONTAINS</option>
3239 </select>
3240 */
3241 function wdk_select_multi_option($field_name, $options = array(), $selected = NULL, $extra=NULL, $empty_text = NULL, $empty_val = '')
3242 {
3243 $output = '<select name="'.$field_name.'" '.$extra.' multiple="multiple">';
3244
3245 if(!is_null($empty_text))
3246 $output.= '<option value="'.esc_attr($empty_val).'">'.esc_html($empty_text).'</option>';
3247
3248 if(is_array($options) && count($options) > 0)
3249 foreach($options as $key=>$val)
3250 {
3251 $output.= '<option value="'.$key.'" '.($selected==$key&&$selected != ''?'selected':'').'>'.$val.'</option>';
3252 }
3253
3254 $output.= '</select>';
3255
3256 return $output;
3257 }
3258
3259
3260 if ( ! function_exists('wdk_treefield_select_ajax'))
3261 {
3262 /**
3263 * Return select2 ajax
3264 *
3265 * @param string option Option key
3266 * @return string alt or title
3267 */
3268 function wdk_treefield_select_ajax($name = '', $table=NULL, $selected = NULL,
3269 $column_print = 'category_title', $column_key = 'idcategory', $language_id=NULL, $empty_value='', $filter_ids = '', $attr = '')
3270 {
3271 $WMVC = &wdk_get_instance();
3272 $WMVC->model($table);
3273
3274 if(is_array($filter_ids)) $filter_ids = implode(',', $filter_ids);
3275
3276 static $counter = 0;
3277 $form = '<select data-ajax="'.admin_url('admin-ajax.php').'" name="'.$name.'" data-table="'.$table.'" '.$attr.' data-placeholder="'.$empty_value.'" class="form-control select_ajax" id="wdk_select2_'.$counter.'" multiple="">';
3278
3279
3280 if(false)
3281 if( $column_key == 'idcategory') {
3282 $form .= '<option selected="selected" value="">'.esc_html__('Select Category', 'wpdirectorykit').'</option>';
3283 } else {
3284 $form .= '<option selected="selected" value="">'.esc_html__('Select Location', 'wpdirectorykit').'</option>';
3285 }
3286
3287 if($selected) {
3288 if(is_array($selected)) {
3289
3290 $ids = array();
3291 foreach($selected as $selected_item) {
3292 if(!empty($selected_item)) {
3293 $ids [] = (int) $selected_item;
3294 }
3295 }
3296
3297 /* where in */
3298 if(!empty($ids)){
3299 $WMVC->db->select($WMVC->$table->_table_name.'.*');
3300 $WMVC->db->where($WMVC->$table->_table_name.'.'.$column_key.' IN(' . implode(',', $ids) . ')', null, false);
3301 $WMVC->db->order_by('FIELD('.$WMVC->$table->_table_name.'.'.$column_key.', '. implode(',', $ids) . ')');
3302
3303 $results = $WMVC->$table->get();
3304 foreach ($results as $item) {
3305 if($item)
3306 $form .= '<option selected="selected" value="'.esc_attr(wmvc_show_data($column_key, $item, false, TRUE, TRUE)).'">'.esc_html__(wmvc_show_data($column_print, $item, false, TRUE, TRUE),'wpdirectorykit').'</option>';
3307 }
3308 }
3309 } elseif(is_intval($selected)) {
3310 $db_item = $WMVC->$table->get($selected, TRUE);
3311 if($db_item)
3312 $form .= '<option selected="selected" value="'.esc_attr(wmvc_show_data($column_key, $db_item, false, TRUE, TRUE)).'">'.esc_html__(wmvc_show_data($column_print, $db_item, false, TRUE, TRUE),'wpdirectorykit').'</option>';
3313 }
3314 } else {
3315 //$form .= '<option value="" selected="selected">'.esc_html__('Not selected', 'wpdirectorykit').'</option>';
3316 }
3317 $form .= '</select>';
3318
3319 //load javascript library
3320 if($counter==0)
3321 {
3322 wp_enqueue_script('select2-select2');
3323 wp_enqueue_script('wdk-select2');
3324 wp_enqueue_style('select2-select2');
3325 }
3326 ?>
3327 <?php
3328 $counter++;
3329 return $form;
3330 }
3331 }
3332
3333 if ( ! function_exists('wdk_user_select_ajax'))
3334 {
3335 /**
3336 * Return select2 ajax
3337 *
3338 * @param string option Option key
3339 * @return string alt or title
3340 */
3341 function wdk_user_select_ajax($name = '', $selected = NULL, $empty_value='', $filter_ids = '')
3342 {
3343 $WMVC = &wdk_get_instance();
3344
3345 if(is_array($filter_ids)) $filter_ids = implode(',', $filter_ids);
3346
3347 static $counter = 0;
3348 $form = '<select data-ajax="'.admin_url('admin-ajax.php').'" name="'.$name.'" data-placeholder="'.$empty_value.'" class="form-control select_ajax_user" id="wdk_select2_user_'.$counter.'" multiple="">';
3349 if($selected) {
3350 if(is_array($selected)) {
3351 /* where in */
3352 foreach ($selected as $item) {
3353 $user_data = get_userdata($item);
3354 if($user_data)
3355 $form .= '<option selected="selected" value="'.esc_attr(wmvc_show_data('ID', $user_data, false, TRUE, TRUE)).'">'.esc_html(wmvc_show_data('display_name', $user_data, false, TRUE, TRUE)).'</option>';
3356 }
3357 } elseif(is_intval($selected)) {
3358 $user_data = get_userdata($selected);
3359 if($user_data)
3360 $form .= '<option selected="selected" value="'.esc_attr(wmvc_show_data('ID', $user_data, false, TRUE, TRUE)).'">'.esc_html(wmvc_show_data('display_name', $user_data, false, TRUE, TRUE)).'</option>';
3361 }
3362 } else {
3363 //$form .= '<option value="" selected="selected">'.esc_html__('Not selected', 'wpdirectorykit').'</option>';
3364 }
3365 $form .= '</select>';
3366
3367 //load javascript library
3368 if($counter==0)
3369 {
3370 wp_enqueue_script('select2-select2');
3371 wp_enqueue_script('wdk-select2');
3372 wp_enqueue_style('select2-select2');
3373 }
3374 ?>
3375 <?php
3376 $counter++;
3377 return $form;
3378 }
3379 }
3380
3381
3382 /*
3383 <select class="form-control" name="<?php echo 'control_operator_'.$i_fieldnum; ?>">
3384 <option value="CONTAINS">CONTAINS</option>
3385 <option value="NOT_CONTAINS">NOT_CONTAINS</option>
3386 </select>
3387 */
3388 function wdk_select_option_multiple($field_name, $options = array(), $selected = array(), $extra=NULL, $empty_text = NULL, $empty_val = '')
3389 {
3390 $output = '<select name="'.$field_name.'" '.$extra.' multiple >';
3391
3392 if(!is_null($empty_text))
3393 $output.= '<option value="'.esc_attr($empty_val).'">'.esc_html($empty_text).'</option>';
3394
3395 if(is_array($options) && count($options) > 0)
3396 foreach($options as $key=>$val)
3397 {
3398 if(is_string($selected)) {
3399 $output.= '<option value="'.$key.'" '.(($selected == $key)?'selected="selected"':'').'>'.$val.'</option>';
3400 } else if(is_array($selected)){
3401 $output.= '<option value="'.$key.'" '.((in_array($key, $selected) === TRUE)?'selected="selected"':'').'>'.$val.'</option>';
3402 }
3403 }
3404
3405 $output.= '</select>';
3406
3407 return $output;
3408 }
3409
3410
3411
3412 if ( ! function_exists('wdk_convert_date_format_js'))
3413 {
3414 /**
3415 * Convert date format for support in js
3416 * From: https://wordpress.org/support/article/formatting-date-and-time/
3417 * To: https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/01-format/
3418 *
3419 * @param string php date format Option key
3420 * @return string js date format
3421 */
3422 function wdk_convert_date_format_js($date_format)
3423 {
3424 $replaced = array(
3425 'D'=>'ddd',
3426 'j'=>'D',
3427 'd'=>'DD',
3428 'l'=>'dddd',
3429 'F'=>'MMMM',
3430 'Y'=>'YYYY',
3431 'S'=>'Do',
3432 'm'=>'MM',
3433 'n'=>'MM',
3434 'F'=>'MMMM',
3435 'M'=>'MMM',
3436 'Y'=>'YYYY',
3437 'y'=>'YY',
3438 'a'=>'a',
3439 'A'=>'A',
3440 'h'=>'hh',
3441 'G'=>'H',
3442 'H'=>'HH',
3443 'g'=>'h',
3444 'i'=>'mm',
3445 's'=>'ss',
3446 'T'=>'zz',
3447 'c'=>'',
3448 'r'=>'llll',
3449 'u'=>'x',
3450 );
3451
3452
3453 $result = '';
3454 $escaped = false;
3455 $length = strlen($date_format);
3456
3457 for ($i = 0; $i < $length; $i++) {
3458 $char = $date_format[$i];
3459
3460 if ($char === '\\') {
3461 $escaped = true;
3462 continue;
3463 }
3464
3465 if ($escaped) {
3466 $result .= "'".$char."'";
3467 $escaped = false;
3468 } else {
3469 $result .= isset($replaced[$char]) ? $replaced[$char] : $char;
3470 }
3471 }
3472
3473 return str_replace("''", '',$result);
3474 }
3475 }
3476
3477 if ( ! function_exists('wdk_convert_date_format_jquery'))
3478 {
3479 /**
3480 * Convert date format for support in js
3481 * From: https://wordpress.org/support/article/formatting-date-and-time/
3482 * To: https://api.jqueryui.com/datepicker/
3483 *
3484 * @param string php date format Option key
3485 * @return string js date format
3486 */
3487 function wdk_convert_date_format_jquery($date_format)
3488 {
3489 $replaced = array(
3490 'D'=>'D',
3491 'd'=>'dd',
3492 'j'=>'d',
3493 'l'=>'DD',
3494 'Y'=>'yy',
3495 'S'=>'d',
3496 'm'=>'mm',
3497 'n'=>'m',
3498 'M'=>'m',
3499 'F'=>'MM',
3500 'y'=>'y',
3501 'a'=>'',
3502 'A'=>'',
3503 'h'=>'',
3504 'G'=>'',
3505 'H'=>'',
3506 'g'=>'',
3507 'i'=>'',
3508 's'=>'',
3509 'T'=>'',
3510 'c'=>'ISO_8601',
3511 'r'=>'RFC_2822',
3512 'u'=>'@',
3513 ':'=>'',
3514 );
3515
3516 $result = '';
3517 $escaped = false;
3518 $length = strlen($date_format);
3519
3520 for ($i = 0; $i < $length; $i++) {
3521 $char = $date_format[$i];
3522
3523 if ($char === '\\') {
3524 $escaped = true;
3525 continue;
3526 }
3527
3528 if ($escaped) {
3529 $result .= "'".$char."'";
3530 $escaped = false;
3531 } else {
3532 $result .= isset($replaced[$char]) ? $replaced[$char] : $char;
3533 }
3534 }
3535
3536 return str_replace("''", '',$result);
3537 }
3538 }
3539
3540 if ( ! function_exists('wdk_convert_date_format_jquery'))
3541 {
3542 /**
3543 * Convert date format for support in js
3544 * From: https://wordpress.org/support/article/formatting-date-and-time/
3545 * To: https://api.jqueryui.com/datepicker/
3546 *
3547 * @param string php date format Option key
3548 * @return string js date format
3549 */
3550 function wdk_convert_date_format_jquery($date_format)
3551 {
3552 $replaced = array(
3553 'D'=>'D',
3554 'd'=>'dd',
3555 'j'=>'d',
3556 'l'=>'DD',
3557 'Y'=>'yy',
3558 'S'=>'d',
3559 'm'=>'mm',
3560 'n'=>'m',
3561 'M'=>'m',
3562 'F'=>'MM',
3563 'y'=>'y',
3564 'a'=>'',
3565 'A'=>'',
3566 'h'=>'',
3567 'G'=>'',
3568 'H'=>'',
3569 'g'=>'',
3570 'i'=>'',
3571 's'=>'',
3572 'T'=>'',
3573 'c'=>'ISO_8601',
3574 'r'=>'RFC_2822',
3575 'u'=>'@',
3576 ':'=>'',
3577 );
3578
3579
3580 $result = '';
3581 $escaped = false;
3582 $length = strlen($date_format);
3583
3584 for ($i = 0; $i < $length; $i++) {
3585 $char = $date_format[$i];
3586
3587 if ($char === '\\') {
3588 $escaped = true;
3589 continue;
3590 }
3591
3592 if ($escaped) {
3593 $result .= "'".$char."'";
3594 $escaped = false;
3595 } else {
3596 $result .= isset($replaced[$char]) ? $replaced[$char] : $char;
3597 }
3598 }
3599
3600 return str_replace("''", '',$result);
3601
3602 }
3603 }
3604
3605 if ( ! function_exists('wdk_get_gps'))
3606 {
3607
3608 /**
3609 * Get Latitude/Longitude/Altitude based on an address
3610 * @param string $address The address for converting into coordinates
3611 * @return array An array containing Latitude/Longitude/Altitude data
3612 */
3613 function wdk_get_gps($address = '')
3614 {
3615
3616 $address_key = 'cached_address_gps';
3617
3618 static $results = array();
3619
3620 if(empty($results)) {
3621 $gps_option = wdk_get_option($address_key, $results);
3622 if($gps_option)
3623 $results = $gps_option;
3624 }
3625
3626 $address = str_replace(' ','+',$address);
3627
3628 if(!isset($results[$address])) {
3629 $results[$address] = NULL;
3630 $url = 'https://nominatim.openstreetmap.org/search?format=json&q=' . $address;
3631
3632 // Add required User-Agent header
3633 $args = [
3634 'timeout' => 10,
3635 'headers' => [
3636 'User-Agent' => get_bloginfo('name') . '/1.0 (' . get_bloginfo('admin_email') . ')',
3637 ],
3638 ];
3639 $request = wp_remote_get( $url, $args);
3640 $response = '';
3641
3642 // request failed
3643 if ( is_wp_error( $request ) ) {
3644 $response = $request;
3645 }
3646 $code = (int) wp_remote_retrieve_response_code( $request );
3647 // make sure the fetch was successful
3648 if (empty($response) && $code == 200 ) {
3649 $response = wp_remote_retrieve_body( $request );
3650 // Decode the json
3651 $resp = json_decode( $response, true );
3652
3653 if(!empty($resp) && isset($resp[0]) && isset($resp[0]['lat']) && isset($resp[0]['lon'])) {
3654 $results[$address] = array('lat' => $resp[0]['lat'], 'lng' => $resp[0]['lon'], 'alt' => 0);
3655
3656 return $results[$address];
3657 }
3658 }
3659 } else {
3660 return $results[$address];
3661 }
3662 return false;
3663 }
3664 }
3665
3666 if ( ! function_exists('wdk_get_gps_google'))
3667 {
3668
3669 /**
3670 * Get Latitude/Longitude/Altitude based on an address from Google Api
3671 * @param string $address The address for converting into coordinates
3672 * @param string $api_key Custom google API Key
3673 *
3674 * @return array An array containing Latitude/Longitude/Altitude data
3675 */
3676 function wdk_get_gps_google($address = '', $api_key = NULL)
3677 {
3678 static $results = array();
3679
3680 if ( empty( $api_key ) ) {
3681 $api_key = wdk_get_option('wdk_geo_google_api_key');
3682 }
3683
3684 $address = str_replace(' ','+',$address);
3685
3686 if(!isset($results[$address])) {
3687 $results[$address] = NULL;
3688 $url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.trim($address).'&key='.$api_key;
3689 $request = wp_remote_get( $url );
3690 $response = '';
3691
3692 // request failed
3693 if ( is_wp_error( $request ) ) {
3694 $response = $request;
3695 }
3696 $code = (int) wp_remote_retrieve_response_code( $request );
3697
3698 // make sure the fetch was successful
3699 if (empty($response) && $code == 200 ) {
3700 $response = wp_remote_retrieve_body( $request );
3701 // Decode the json
3702 $resp = json_decode( $response, true );
3703 $status = $resp['status'];
3704
3705 //if request status is successful
3706 if($status == "OK"){
3707 //get address from json data
3708 $lat = $resp['results'][0]['geometry']['location']['lat'];
3709 $lng = $resp['results'][0]['geometry']['location']['lng'];
3710
3711 $results[$address] = array('lat' => $lat , 'lng' => $lng, 'alt' => 0);
3712 return $results[$address];
3713 }
3714 }
3715 } else {
3716 return $results[$address];
3717 }
3718
3719 return false;
3720 }
3721 }
3722
3723
3724 if ( ! function_exists('wdk_getDueCoords'))
3725 {
3726 // Modified from:
3727 // http://www.sitepoint.com/forums/showthread.php?656315-adding-distance-gps-coordinates-get-bounding-box
3728 /**
3729 * bearing is 0 = north, 180 = south, 90 = east, 270 = west
3730 *
3731 */
3732 function wdk_getDueCoords($latitude, $longitude, $bearing, $distance, $distance_unit = "km", $return_as_array = FALSE) {
3733
3734 if ($distance_unit == "m") {
3735 // Distance is in miles.
3736 $radius = 3963.1676;
3737 }
3738 else {
3739 // distance is in km.
3740 $radius = 6378.1;
3741 }
3742
3743 // New latitude in degrees.
3744 $new_latitude = rad2deg(asin(sin(deg2rad($latitude)) * cos($distance / $radius) + cos(deg2rad($latitude)) * sin($distance / $radius) * cos(deg2rad($bearing))));
3745
3746 // New longitude in degrees.
3747 $new_longitude = rad2deg(deg2rad($longitude) + atan2(sin(deg2rad($bearing)) * sin($distance / $radius) * cos(deg2rad($latitude)), cos($distance / $radius) - sin(deg2rad($latitude)) * sin(deg2rad($new_latitude))));
3748
3749 if ($return_as_array) {
3750 // Assign new latitude and longitude to an array to be returned to the caller.
3751 $coord = array();
3752 $coord['lat'] = $new_latitude;
3753 $coord['lng'] = $new_longitude;
3754 }
3755 else {
3756 $coord = $new_latitude . ", " . $new_longitude;
3757 }
3758
3759 return $coord;
3760
3761 }
3762 }
3763
3764 if ( ! function_exists('wdk_is_gps'))
3765 {
3766 // Validation gps
3767 /**
3768 * @param string $string_gps gps in string like xx.xxxx,xx.xxxxx
3769 * @return bool
3770 */
3771 function wdk_is_gps($string_gps = '') {
3772 if(preg_match('/^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$/', $string_gps)) {
3773 return true;
3774 }
3775
3776 return false;
3777 }
3778 }
3779
3780
3781 if ( ! function_exists('wdk_is_phone'))
3782 {
3783 // Validation phone
3784 /**
3785 * @param string $value phone in string
3786 * @return bool
3787 */
3788 function wdk_is_phone($value = '') {
3789 if(preg_match("/^[.+]{0,1}[0-9-)(]{0,25}$/", $value)) {
3790 return true;
3791 }
3792
3793 return false;
3794 }
3795 }
3796
3797 if ( ! function_exists('is_wdk_whatsapp'))
3798 {
3799 // Validation phone
3800 /**
3801 * @param string $value phone in string
3802 * @return bool
3803 */
3804 function is_wdk_whatsapp($value = '') {
3805 return true;
3806 }
3807 }
3808
3809 if ( ! function_exists('is_wdk_viber'))
3810 {
3811 // Validation phone
3812 /**
3813 * @param string $value phone in string
3814 * @return bool
3815 */
3816 function is_wdk_viber($value = '') {
3817 return true;
3818 }
3819 }
3820
3821 if ( ! function_exists('wdk_filter_phone'))
3822 {
3823 // Validation phone
3824 /**
3825 * @param string $value phone in string
3826 * @return bool
3827 */
3828 function wdk_filter_phone($value = '') {
3829 return str_replace(array(' ','-','(',')'),'',$value);
3830 }
3831 }
3832
3833
3834 if ( ! function_exists('wdk_generate_media_field'))
3835 {
3836 // Based on value return video embed, youtube, source video tag
3837 /**
3838 * @param string $value value
3839 * @param string $class help css class
3840 * @return string html or NULL
3841 */
3842 function wdk_generate_media_field($value = '', $class="wdk-image") {
3843 $output = NULL;
3844
3845 if(strpos($value, 'vimeo.com') !== FALSE)
3846 {
3847 $output = wp_oembed_get($value, array("width"=>"800", "height"=>"450"));
3848 $output = str_replace( '<iframe', '<iframe class="'.$class.'" ', $output);
3849 }
3850 elseif(strpos($value, 'watch?v=') !== FALSE)
3851 {
3852 $embed_code = substr($value, strpos($value, 'watch?v=')+8);
3853 $output = wp_oembed_get('https://www.youtube.com/watch?v='.$embed_code, array("width"=>"800", "height"=>"455"));
3854 $output = str_replace( '<iframe', '<iframe class="'.$class.'" ', $output );
3855 }
3856 elseif(strpos($value, 'youtu.be/') !== FALSE)
3857 {
3858 $embed_code = substr($value, strpos($value, 'youtu.be/')+9);
3859 $output = wp_oembed_get('https://www.youtube.com/watch?v='.$embed_code, array("width"=>"800", "height"=>"455"));
3860 $output = str_replace( '<iframe', '<iframe class="'.$class.'" ', $output );
3861 }
3862 elseif(strpos($value, 'youtube.com/embed/') !== FALSE)
3863 {
3864 $embed_code = substr($value, strpos($value, 'youtube.com/embed/')+18);
3865 $output = wp_oembed_get('https://www.youtube.com/watch?v='.$embed_code, array("width"=>"800", "height"=>"455"));
3866 $output = str_replace( '<iframe', '<iframe class="'.$class.'" ', $output );
3867 }
3868 elseif(filter_var($value, FILTER_VALIDATE_URL) !== FALSE && preg_match('/\.(mp4|flv|wmw|ogv|webm|ogg)$/i', $value))
3869 {
3870 $output = '<video src="'.$value.'" controls class="'.$class.'"></video> ';
3871 }
3872
3873 return $output;
3874 }
3875 }
3876
3877
3878 if ( ! function_exists('wdk_depend_get_hidden_fields'))
3879 {
3880 // Based on value return video embed, youtube, source video tag
3881 /**
3882 * @param int $tree_id tree_id of category
3883 * @param string $type type, default 'categories'
3884 * @return string string with hidden fields like ,1,2,3,4, or NULL
3885 */
3886 function wdk_depend_get_hidden_fields($tree_id = NULL, $type="categories") {
3887 static $output = array();
3888
3889 if(isset($output[$tree_id])) {
3890 return $output[$tree_id];
3891 }
3892 if(empty($tree_id)) {
3893 return NULL;
3894 } else {
3895 $output[$tree_id] = false;
3896
3897 global $Winter_MVC_WDK;
3898 $Winter_MVC_WDK->model('dependfields_m');
3899
3900 $depend_fields = $Winter_MVC_WDK->dependfields_m->get_by(array('field_id' => $tree_id,'main_field' => $type), TRUE);
3901
3902 if($depend_fields && !empty($depend_fields->hidden_fields_list)) {
3903 $output[$tree_id] = ','.$depend_fields->hidden_fields_list. ',';
3904 }
3905 return $output[$tree_id];
3906 }
3907
3908 return false;
3909 }
3910 }
3911
3912 if ( ! function_exists('wdk_depend_is_hidden_field'))
3913 {
3914 // Based on value return video embed, youtube, source video tag
3915 /**
3916 * @param int $field_id field_id
3917 * @param int $tree_id id for category
3918 * @param string $type type, default 'categories'
3919 * @return string string with hidden fields like ,1,2,3,4, or NULL
3920 */
3921 function wdk_depend_is_hidden_field($field_id = NULL, $tree_id = NULL, $type="categories") {
3922 $hidden_fields = wdk_depend_get_hidden_fields($tree_id, $type);
3923 if($hidden_fields && strpos($hidden_fields, ','.trim($field_id).',') !== FALSE) {
3924 return true;
3925 }
3926
3927 return false;
3928 }
3929 }
3930
3931
3932 if ( ! function_exists('is_wdk_slug_format'))
3933 {
3934 function is_wdk_slug_format($string)
3935 {
3936 if(empty($string))return FALSE;
3937
3938
3939 if (preg_match("/^[a-z0-9-_]+\$/", $string)) {
3940
3941 return TRUE;
3942 }
3943
3944 return FALSE;
3945 }
3946 }
3947
3948 if ( ! function_exists('wdk_number_format_i18n'))
3949 {
3950 function wdk_number_format_i18n($value)
3951 {
3952 if(empty($value))return NULL;
3953
3954
3955 $value = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
3956 $value = (float)str_replace(array(","," ",'&nbsp;'), "", $value);
3957
3958 // Allow decimal precision to be filtered (default is 0)
3959 $decimals = apply_filters('wdk_number_format_decimals', ((wdk_get_option('wdk_number_format_decimals')) ? wdk_get_option('wdk_number_format_decimals') : 0));
3960
3961 if(!get_option('wdk_disable_custom_muber_format')) {
3962 global $wp_locale;
3963 return number_format(
3964 $value,
3965 $decimals,
3966 $wp_locale->number_format['decimal_point'],
3967 $wp_locale->number_format['thousands_sep']
3968 );
3969 }
3970
3971 return number_format_i18n($value, $decimals);
3972 }
3973 }
3974
3975 if ( ! function_exists('wdk_currency_symbol'))
3976 {
3977 /**
3978 * Return currency symbol
3979 *
3980 * @return string currency symbol
3981 */
3982 function wdk_currency_symbol()
3983 {
3984
3985 if(function_exists('get_woocommerce_currency_symbol'))
3986 return get_woocommerce_currency_symbol();
3987
3988 if(wdk_get_option('wdk_default_currency_symbol'))
3989 return wdk_get_option('wdk_default_currency_symbol');
3990
3991 return '$';
3992 }
3993 }
3994
3995 if ( ! function_exists('wdk_generate_path_image'))
3996 {
3997 /**
3998 * Generate path of images
3999 *
4000 * @param string $id or ids of images, separeted by comma
4001 * @param bool $multi multi images, separeted by comma
4002 * @param int $limit limit characters for path
4003 * @param int $limit limit images for path
4004 *
4005 * @return string with path of image or multi images
4006 */
4007 function wdk_generate_path_image($ids = NULL, $multi = FALSE, $limit = 95, $limit_images = 10)
4008 {
4009 $path = '';
4010 if(empty($ids))
4011 return $path;
4012
4013 $image_ids = explode(',', $ids);
4014 $count_images = 0;
4015 if(is_array($image_ids)) {
4016 foreach ($image_ids as $image_id) {
4017 if(is_numeric($image_id))
4018 {
4019
4020 if($count_images>=$limit_images)
4021 break;
4022
4023 $image_path = wp_get_original_image_path($image_id);
4024 if($image_path) {
4025 /* path of image */
4026 $next_path = str_replace(WP_CONTENT_DIR . '/uploads/','', $image_path);
4027
4028 /* check length listing_images_path + next image + comma, should be less then $limit */
4029 if(strlen($path.$next_path)<$limit) {
4030
4031 if($multi) {
4032 if(!empty($path))
4033 $path .= ',';
4034 }
4035
4036 $path .= $next_path;
4037 }
4038
4039 if(!$multi)
4040 break;
4041
4042 $count_images++;
4043 }
4044 }
4045 }
4046 }
4047
4048 return $path;
4049 }
4050 }
4051
4052 if ( ! function_exists('wdk_booking_currency_symbol'))
4053 {
4054 /**
4055 * Return currency symbol
4056 *
4057 * @return string currency symbol
4058 */
4059 function wdk_booking_currency_symbol()
4060 {
4061
4062 if(function_exists('get_woocommerce_currency_symbol'))
4063 return get_woocommerce_currency_symbol();
4064
4065 if(wdk_get_option('wdk_default_currency_symbol'))
4066 return wdk_get_option('wdk_default_currency_symbol');
4067
4068 return '$';
4069 }
4070 }
4071
4072 if ( ! function_exists('wdk_generated_cached_row_userdata'))
4073 {
4074 /**
4075 * Return currency symbol
4076 *
4077 * @return string currency symbol
4078 */
4079 function wdk_generated_cached_row_userdata($row)
4080 {
4081 $user_data = array();
4082
4083 $user_data['display_name'] = wmvc_show_data('cacheduser_display_name', $row);
4084 $user_data['user_email'] = wmvc_show_data('cacheduser_email', $row);
4085 $user_data['profile_url'] = wmvc_show_data('cacheduser_profile_url', $row);
4086 $user_data['avatar_url'] = wmvc_show_data('cacheduser_avatar_url', $row);
4087
4088 /* meta */
4089 $user_data['wdk_address'] = wmvc_show_data('cacheduser_wdk_address', $row);
4090 $user_data['wdk_phone'] = wmvc_show_data('cacheduser_wdk_phone', $row);
4091 $user_data['wdk_city'] = wmvc_show_data('cacheduser_wdk_city', $row);
4092 $user_data['wdk_company_name'] = wmvc_show_data('cacheduser_wdk_company_name', $row);
4093 $user_data['wdk_facebook'] = wmvc_show_data('cacheduser_wdk_facebook', $row);
4094 $user_data['wdk_youtube'] = wmvc_show_data('cacheduser_wdk_youtube', $row);
4095 $user_data['wdk_linkedin'] = wmvc_show_data('cacheduser_wdk_linkedin', $row);
4096 $user_data['wdk_twitter'] = wmvc_show_data('cacheduser_wdk_twitter', $row);
4097 $user_data['wdk_instagram'] = wmvc_show_data('cacheduser_wdk_instagram', $row);
4098 $user_data['wdk_whatsapp'] = wmvc_show_data('cacheduser_wdk_whatsapp', $row);
4099 $user_data['wdk_viber'] = wmvc_show_data('cacheduser_wdk_viber', $row);
4100 $user_data['wdk_iban'] = wmvc_show_data('cacheduser_wdk_iban', $row);
4101 $user_data['wdk_telegram'] = wmvc_show_data('cacheduser_wdk_telegram', $row);
4102 $user_data['wdk_position_title'] = wmvc_show_data('cacheduser_wdk_position_title', $row);
4103 $user_data['agency_name'] = wmvc_show_data('cacheduser_agency_name', $row);
4104 $user_data['description'] = wmvc_show_data('cacheduser_description', $row);
4105 $user_data['user_url'] = wmvc_show_data('cacheduser_user_url', $row);
4106 $user_data['roles'] = explode(',', wmvc_show_data('cacheduser_roles', $row));
4107 $user_data['wdk_slug'] = wmvc_show_data('cacheduser_wdk_slug', $row);
4108 $user_data['user_login'] = wmvc_show_data('cacheduser_user_login', $row);
4109 $user_data['user_id'] = wmvc_show_data('cacheduser_user_id', $row);
4110
4111 if(function_exists('wdk_generate_profile_permalink') && $user_data['profile_url'] == '#') {
4112 if($user_data['user_login']) {
4113 $user_data['profile_url'] = wdk_generate_profile_permalink($user_data);
4114 } else {
4115 $user_data['profile_url'] = wdk_generate_profile_permalink(wmvc_show_data('user_id', $user_data));
4116 }
4117 }
4118
4119 return $user_data;
4120 }
4121 }
4122
4123 if ( ! function_exists('wdk_mime2extd'))
4124 {
4125 /**
4126 * Return currency symbol
4127 *
4128 * @return string currency symbol
4129 */
4130 function wdk_mime2ext($mime) {
4131 $mime_map = [
4132 'video/3gpp2' => '3g2',
4133 'video/3gp' => '3gp',
4134 'video/3gpp' => '3gp',
4135 'application/x-compressed' => '7zip',
4136 'audio/x-acc' => 'aac',
4137 'audio/ac3' => 'ac3',
4138 'application/postscript' => 'ai',
4139 'audio/x-aiff' => 'aif',
4140 'audio/aiff' => 'aif',
4141 'audio/x-au' => 'au',
4142 'video/x-msvideo' => 'avi',
4143 'video/msvideo' => 'avi',
4144 'video/avi' => 'avi',
4145 'application/x-troff-msvideo' => 'avi',
4146 'application/macbinary' => 'bin',
4147 'application/mac-binary' => 'bin',
4148 'application/x-binary' => 'bin',
4149 'application/x-macbinary' => 'bin',
4150 'image/bmp' => 'bmp',
4151 'image/x-bmp' => 'bmp',
4152 'image/x-bitmap' => 'bmp',
4153 'image/x-xbitmap' => 'bmp',
4154 'image/x-win-bitmap' => 'bmp',
4155 'image/x-windows-bmp' => 'bmp',
4156 'image/ms-bmp' => 'bmp',
4157 'image/x-ms-bmp' => 'bmp',
4158 'application/bmp' => 'bmp',
4159 'application/x-bmp' => 'bmp',
4160 'application/x-win-bitmap' => 'bmp',
4161 'application/cdr' => 'cdr',
4162 'application/coreldraw' => 'cdr',
4163 'application/x-cdr' => 'cdr',
4164 'application/x-coreldraw' => 'cdr',
4165 'image/cdr' => 'cdr',
4166 'image/x-cdr' => 'cdr',
4167 'zz-application/zz-winassoc-cdr' => 'cdr',
4168 'application/mac-compactpro' => 'cpt',
4169 'application/pkix-crl' => 'crl',
4170 'application/pkcs-crl' => 'crl',
4171 'application/x-x509-ca-cert' => 'crt',
4172 'application/pkix-cert' => 'crt',
4173 'text/css' => 'css',
4174 'text/x-comma-separated-values' => 'csv',
4175 'text/comma-separated-values' => 'csv',
4176 'application/vnd.msexcel' => 'csv',
4177 'application/x-director' => 'dcr',
4178 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
4179 'application/x-dvi' => 'dvi',
4180 'message/rfc822' => 'eml',
4181 'application/x-msdownload' => 'exe',
4182 'video/x-f4v' => 'f4v',
4183 'audio/x-flac' => 'flac',
4184 'video/x-flv' => 'flv',
4185 'image/gif' => 'gif',
4186 'application/gpg-keys' => 'gpg',
4187 'application/x-gtar' => 'gtar',
4188 'application/x-gzip' => 'gzip',
4189 'application/mac-binhex40' => 'hqx',
4190 'application/mac-binhex' => 'hqx',
4191 'application/x-binhex40' => 'hqx',
4192 'application/x-mac-binhex40' => 'hqx',
4193 'text/html' => 'html',
4194 'image/x-icon' => 'ico',
4195 'image/x-ico' => 'ico',
4196 'image/vnd.microsoft.icon' => 'ico',
4197 'text/calendar' => 'ics',
4198 'application/java-archive' => 'jar',
4199 'application/x-java-application' => 'jar',
4200 'application/x-jar' => 'jar',
4201 'image/jp2' => 'jp2',
4202 'video/mj2' => 'jp2',
4203 'image/jpx' => 'jp2',
4204 'image/jpm' => 'jp2',
4205 'image/jpeg' => 'jpeg',
4206 'image/pjpeg' => 'jpeg',
4207 'application/x-javascript' => 'js',
4208 'application/json' => 'json',
4209 'text/json' => 'json',
4210 'application/vnd.google-earth.kml+xml' => 'kml',
4211 'application/vnd.google-earth.kmz' => 'kmz',
4212 'text/x-log' => 'log',
4213 'audio/x-m4a' => 'm4a',
4214 'application/vnd.mpegurl' => 'm4u',
4215 'audio/midi' => 'mid',
4216 'application/vnd.mif' => 'mif',
4217 'video/quicktime' => 'mov',
4218 'video/x-sgi-movie' => 'movie',
4219 'audio/mpeg' => 'mp3',
4220 'audio/mpg' => 'mp3',
4221 'audio/mpeg3' => 'mp3',
4222 'audio/mp3' => 'mp3',
4223 'video/mp4' => 'mp4',
4224 'video/mpeg' => 'mpeg',
4225 'application/oda' => 'oda',
4226 'application/vnd.oasis.opendocument.text' => 'odt',
4227 'application/vnd.oasis.opendocument.spreadsheet' => 'ods',
4228 'application/vnd.oasis.opendocument.presentation' => 'odp',
4229 'audio/ogg' => 'ogg',
4230 'video/ogg' => 'ogg',
4231 'application/ogg' => 'ogg',
4232 'application/x-pkcs10' => 'p10',
4233 'application/pkcs10' => 'p10',
4234 'application/x-pkcs12' => 'p12',
4235 'application/x-pkcs7-signature' => 'p7a',
4236 'application/pkcs7-mime' => 'p7c',
4237 'application/x-pkcs7-mime' => 'p7c',
4238 'application/x-pkcs7-certreqresp' => 'p7r',
4239 'application/pkcs7-signature' => 'p7s',
4240 'application/pdf' => 'pdf',
4241 'application/octet-stream' => 'pdf',
4242 'application/x-x509-user-cert' => 'pem',
4243 'application/x-pem-file' => 'pem',
4244 'application/pgp' => 'pgp',
4245 'application/x-httpd-php' => 'php',
4246 'application/php' => 'php',
4247 'application/x-php' => 'php',
4248 'text/php' => 'php',
4249 'text/x-php' => 'php',
4250 'application/x-httpd-php-source' => 'php',
4251 'image/png' => 'png',
4252 'image/x-png' => 'png',
4253 'application/powerpoint' => 'ppt',
4254 'application/vnd.ms-powerpoint' => 'ppt',
4255 'application/vnd.ms-office' => 'ppt',
4256 'application/msword' => 'doc',
4257 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
4258 'application/x-photoshop' => 'psd',
4259 'image/vnd.adobe.photoshop' => 'psd',
4260 'audio/x-realaudio' => 'ra',
4261 'audio/x-pn-realaudio' => 'ram',
4262 'application/x-rar' => 'rar',
4263 'application/rar' => 'rar',
4264 'application/x-rar-compressed' => 'rar',
4265 'audio/x-pn-realaudio-plugin' => 'rpm',
4266 'application/x-pkcs7' => 'rsa',
4267 'text/rtf' => 'rtf',
4268 'text/richtext' => 'rtx',
4269 'video/vnd.rn-realvideo' => 'rv',
4270 'application/x-stuffit' => 'sit',
4271 'application/smil' => 'smil',
4272 'text/srt' => 'srt',
4273 'image/svg+xml' => 'svg',
4274 'application/x-shockwave-flash' => 'swf',
4275 'application/x-tar' => 'tar',
4276 'application/x-gzip-compressed' => 'tgz',
4277 'image/tiff' => 'tiff',
4278 'text/plain' => 'txt',
4279 'text/x-vcard' => 'vcf',
4280 'application/videolan' => 'vlc',
4281 'text/vtt' => 'vtt',
4282 'audio/x-wav' => 'wav',
4283 'audio/wave' => 'wav',
4284 'audio/wav' => 'wav',
4285 'application/wbxml' => 'wbxml',
4286 'video/webm' => 'webm',
4287 'audio/x-ms-wma' => 'wma',
4288 'application/wmlc' => 'wmlc',
4289 'video/x-ms-wmv' => 'wmv',
4290 'video/x-ms-asf' => 'wmv',
4291 'application/xhtml+xml' => 'xhtml',
4292 'application/excel' => 'xl',
4293 'application/msexcel' => 'xls',
4294 'application/x-msexcel' => 'xls',
4295 'application/x-ms-excel' => 'xls',
4296 'application/x-excel' => 'xls',
4297 'application/x-dos_ms_excel' => 'xls',
4298 'application/xls' => 'xls',
4299 'application/x-xls' => 'xls',
4300 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
4301 'application/vnd.ms-excel' => 'xlsx',
4302 'application/xml' => 'xml',
4303 'text/xml' => 'xml',
4304 'text/xsl' => 'xsl',
4305 'application/xspf+xml' => 'xspf',
4306 'application/x-compress' => 'z',
4307 'application/x-zip' => 'zip',
4308 'application/zip' => 'zip',
4309 'application/x-zip-compressed' => 'zip',
4310 'application/s-compressed' => 'zip',
4311 'multipart/x-zip' => 'zip',
4312 'text/x-scriptzsh' => 'zsh',
4313 ];
4314
4315 return isset($mime_map[$mime]) === true ? $mime_map[$mime] : false;
4316 }
4317 }
4318
4319 if ( ! function_exists('wdk_is_dash_enabled'))
4320 {
4321 /**
4322 * IS Dash pages exists
4323 *
4324 * @return bool true if exists dash
4325 */
4326 function wdk_is_dash_enabled() {
4327 if(function_exists('run_wdk_membership') && wdk_get_option('wdk_membership_dash_page') && get_post_status(wdk_get_option('wdk_membership_dash_page')) =='publish'){
4328 return true;
4329 }
4330
4331 return false;
4332 }
4333 }
4334
4335 if(!function_exists('wdk_page_by_title')) {
4336 function wdk_page_by_title ( $page_title, $output = OBJECT, $post_type = 'page' ) {
4337 global $wpdb;
4338
4339 if ( is_array( $post_type ) ) {
4340 $post_type = esc_sql( $post_type );
4341 $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
4342 $sql = $wpdb->prepare(
4343 "
4344 SELECT ID
4345 FROM $wpdb->posts
4346 WHERE post_title = %s
4347 AND post_type IN ($post_type_in_string)
4348 ",
4349 $page_title
4350 );
4351 } else {
4352 $sql = $wpdb->prepare(
4353 "
4354 SELECT ID
4355 FROM $wpdb->posts
4356 WHERE post_title = %s
4357 AND post_type = %s
4358 ",
4359 $page_title,
4360 $post_type
4361 );
4362 }
4363
4364 $page = $wpdb->get_var( $sql );
4365
4366 if ( $page ) {
4367 return get_post( $page, $output );
4368 }
4369
4370 return null;
4371 }
4372 }
4373
4374
4375 if ( ! function_exists('is_wdk_gps_single'))
4376 {
4377 function is_wdk_gps_single($param)
4378 {
4379
4380 if (is_numeric($param) && $param > -180 && $param < 180) {
4381 return true;
4382 }
4383
4384 return false;
4385 }
4386 }
4387
4388 if ( ! function_exists('wdk_get_tgmpa_link'))
4389 {
4390 function wdk_get_tgmpa_link()
4391 {
4392 if(file_exists(get_template_directory().'/includes/tgm_pa/class-tgm-plugin-activation.php') || file_exists(get_template_directory().'/tgm_pa/class-tgm-plugin-activation.php')) {
4393 return get_admin_url() . "themes.php?page=tgmpa-install-plugins";
4394 } else {
4395 return get_admin_url() . "plugins.php?page=tgmpa-install-plugins";
4396 }
4397
4398 return false;
4399 }
4400 }
4401
4402 if ( ! function_exists('wdk_sprintf'))
4403 {
4404 function wdk_sprintf($string = '')
4405 {
4406 $arg_list = func_get_args();
4407
4408 if(count($arg_list)<2) {
4409 return $string;
4410 }
4411
4412 if(stripos($string, '%1$s') === FALSE) {
4413 return $string;
4414 }
4415
4416 return call_user_func_array("sprintf", $arg_list);
4417 }
4418 }
4419
4420 if ( ! function_exists('wdk_db_table'))
4421 {
4422 function wdk_db_table($data, $columns = array()) {
4423 $output = '<table>';
4424 foreach($data as $key => $var) {
4425 if($key === 0)
4426 {
4427 $output .= '<tr>';
4428 foreach($var as $k => $v) {
4429 if(count($columns) > 0 && !in_array($k, $columns))continue;
4430
4431 $output .= '<td><strong>' . $k . '</strong></td>';
4432 }
4433 $output .= '</tr>';
4434 }
4435
4436 $output .= '<tr>';
4437 foreach($var as $k => $v) {
4438 if(count($columns) > 0 && !in_array($k, $columns))continue;
4439
4440 $output .= '<td>' . $v . '</td>';
4441 }
4442 $output .= '</tr>';
4443 }
4444 $output .= '</table>';
4445 echo $output;
4446 }
4447 }
4448
4449 if ( ! function_exists('wdk_move_gps'))
4450 {
4451 function wdk_move_gps($value) {
4452 return $value+0.001 * rand(1, 9);
4453 }
4454 }
4455
4456 if ( ! function_exists('wdk_get_near_location'))
4457 {
4458 function wdk_get_near_location($latitude, $longitude, $radius = 10000) {
4459 // Convert radius from meters to degrees
4460 $radiusInDegrees = $radius / 111000;
4461
4462 $u = mt_rand() / mt_getrandmax();
4463 $v = mt_rand() / mt_getrandmax();
4464 $w = $radiusInDegrees * sqrt($u);
4465 $t = 2 * M_PI * $v;
4466 $x = $w * cos($t);
4467 $y = $w * sin($t);
4468
4469 // Adjust the x-coordinate for the shrinking of the east-west distances
4470 $newX = $x / cos(deg2rad($latitude));
4471
4472 $newLongitude = $longitude + $newX;
4473 $newLatitude = $latitude + $y;
4474
4475 return array('lat' => $newLatitude, 'lng' => $newLongitude);
4476 }
4477 }
4478
4479 if ( ! function_exists('wdk_is_listing_preview_page'))
4480 {
4481 function wdk_is_listing_preview_page() {
4482 global $wdk_listing_id;
4483
4484 if(!empty($wdk_listing_id))
4485 return TRUE;
4486
4487 return FALSE;
4488 }
4489 }
4490
4491 if ( ! function_exists('wdk_is_listing_field_exists'))
4492 {
4493 function wdk_is_listing_field_exists($field_name = '', $udpate_cache = FALSE) {
4494 static $available_fields_listings = array();
4495 $custom_fields = array();
4496
4497 $WMVC = &wdk_get_instance();
4498 $WMVC->model('listingfield_m');
4499
4500 if(empty($available_fields_listings) || $udpate_cache) {
4501 $available_fields_listings = $WMVC->listingfield_m->get_available_fields();
4502 }
4503
4504 if(isset($available_fields_listings[$field_name]) || isset($custom_fields[$field_name])) {
4505 return TRUE;
4506 }
4507
4508 return FALSE;
4509 }
4510 }
4511
4512 if ( ! function_exists('wdk_cached_field_get'))
4513 {
4514 function wdk_cached_field_get($udpate_cache = FALSE) {
4515 static $fields = NULL;
4516
4517 $WMVC = &wdk_get_instance();
4518 $WMVC->model('field_m');
4519
4520 if(is_null($fields) || $udpate_cache) {
4521 $fields = $WMVC->field_m->get();
4522 }
4523
4524 return $fields;
4525 }
4526 }
4527
4528 if (! function_exists('wdk_generate_slug'))
4529 {
4530 function wdk_generate_slug($str, $separator = 'dash', $lowercase = TRUE)
4531 {
4532 if ($separator == 'dash')
4533 {
4534 $search = '_';
4535 $replace = '-';
4536 }
4537 else
4538 {
4539 $search = '-';
4540 $replace = '_';
4541 }
4542
4543 $dot='';
4544 if($separator == 'dot'){
4545 $str = str_replace(' ', '.', $str);
4546 $dot='.';
4547 }
4548
4549 $trans = array(
4550 $search => $replace,
4551 "\s+" => $replace,
4552 "[^a-z0-9".$replace.$dot."]" => '',
4553 $replace."+" => $replace,
4554 $replace."$" => '',
4555 "^".$replace => ''
4556 );
4557
4558 // For Croatia
4559 $str = str_replace(array('č','ć','ž','š','đ', 'Č','Ć','Ž','Š','Đ'),
4560 array('c','c','z','s','d', 'c','c','z','s','d'), $str);
4561
4562 // For Turkish
4563 $str = str_replace(array('ş','Ş','ı','İ','ğ','Ğ','Ü','ü','Ö','ö','ç','Ç'),
4564 array('s','s','i','i','g','g','u','u','o','o','c','c'), $str);
4565
4566 // Russian alphabet
4567 $str = str_replace(array('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я'),
4568 array('a','b','v','g','d','e','e','zh','z','i','y','k','l','m','n','o','p','r','s','t','u','f','kh','c','ch','sh','sh','','y','','e','yu','ya'), $str);
4569 $str = str_replace(array('а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','�
4570 ','ц','ч','ш','щ','ъ','ы','ь','э','ю','я'),
4571 array('a','b','v','g','d','e','e','zh','z','i','y','k','l','m','n','o','p','r','s','t','u','f','kh','c','ch','sh','sh','','y','','e','yu','ya'), $str);
4572
4573 // Ukrainian alphabet
4574 $str = str_replace(array('Ґ','Є','І','Ї'),
4575 array('G','E','I','I'), $str);
4576 $str = str_replace(array('ґ','є','і','ї'),
4577 array('g','e','i','i'), $str);
4578 // Symbols
4579 $str = str_replace(array("  ","’","–",'«','»','№','„','”'),
4580 array("","","-",'','','no','',''), $str);
4581
4582 // Alphabets Czech Croatian Turkish and other
4583 $str = str_replace(array('Á','Ä','Ď','É','Ě','Ë','Í','Ň','Ń','Ó','Ŕ','Ř','Ť','Ú','Ů','Ý','Ź','Č','Ć','Ž','Š','Đ','Ş','İ','Ğ','Ü','Ö','Ç'),
4584 array('a','a','d','e','e','e','i','n','n','o','r','r','t','u','u','y','z','c','c','z','s','d','s','i','g','u','o','c'), $str);
4585 $str = str_replace(array('á','ä','ď','é','ě','ë','í','ň','ń','ó','ŕ','ř','ť','ú','ů','ý','ź','č','ć','ž','š','đ','ş','ı','ğ','ü','ö','ç'),
4586 array('a','a','d','e','e','e','i','n','n','o','r','r','t','u','u','y','z','c','c','z','s','d','s','i','g','u','o','c'), $str);
4587
4588 // For french
4589 $str = str_replace(array('â','é','è','û','ê', 'à','Â','ç','ï','î','ä','î'),
4590 array('a','e','e','u','e', 'a','c','c','i','î','a','î'), $str);
4591
4592 $str = strip_tags(strtolower($str));
4593
4594
4595 foreach ($trans as $key => $val)
4596 {
4597 $str = preg_replace("#".$key."#", $val, $str);
4598 }
4599
4600 return trim(stripslashes($str));
4601 }
4602 }
4603
4604
4605 if (! function_exists('wdk_is_gps'))
4606 {
4607 function wdk_is_gps($gps = '')
4608 {
4609
4610 if(stripos($gps,',') === FALSE) {
4611 return FALSE;
4612 }
4613
4614 $gps_coor = explode(',', $gps);
4615
4616 if(count($gps_coor) != 2)
4617 {
4618 return FALSE;
4619 }
4620
4621 if(!is_numeric($gps_coor[0]) || !is_numeric($gps_coor[1]))
4622 {
4623 return FALSE;
4624 }
4625
4626 if($gps_coor[0] < -90 || $gps_coor[0] > 90 || $gps_coor[1] < -180 || $gps_coor[1] > 180)
4627 {
4628 return FALSE;
4629 }
4630
4631 return TRUE;
4632 }
4633 }
4634
4635 if ( ! function_exists('is_wdk_is_useremail_exists'))
4636 {
4637 function is_wdk_is_useremail_exists($param)
4638 {
4639
4640 if(null == username_exists( $param ) && !email_exists($param)) {
4641 return true;
4642 }
4643
4644 return false;
4645 }
4646 }
4647
4648
4649 /*
4650 Validation is natural integer
4651 */
4652 if ( ! function_exists('is_wdk_is_natural'))
4653 {
4654 function is_wdk_is_natural($param)
4655 {
4656
4657 if (is_intval($param) && stripos($param, '.') === FALSE && stripos($param, ',') === FALSE) {
4658 return true;
4659 }
4660
4661 return false;
4662 }
4663 }
4664
4665
4666 /**
4667 * Check is listing preview page exits
4668 *
4669 * @return bool
4670 */
4671 if ( ! function_exists('wdk_is_listing_page_enabled'))
4672 {
4673 function wdk_is_listing_page_enabled ()
4674 {
4675
4676 if(get_option('wdk_listing_page') && get_post_status(get_option('wdk_listing_page')) =='publish') {
4677 return true;
4678 }
4679
4680 return false;
4681 }
4682 }
4683
4684
4685 /**
4686 * Check is listing preview page exits
4687 *
4688 * @return bool
4689 */
4690 if ( ! function_exists('replace_smart_data'))
4691 {
4692 function replace_smart_data($output = '', $replace_data = array()) {
4693 // Match all occurrences of the pattern
4694 if (preg_match_all('/\{([^}]+)\}/', $output, $matches)) {
4695 foreach ($matches[1] as $key => $value) {
4696 foreach ($replace_data as $replace_key => $replace_value) {
4697 $output = str_replace('{'.$replace_key.'}', $replace_value, $output);
4698 }
4699 }
4700 }
4701 return $output;
4702 }
4703 }
4704
4705 if ( ! function_exists('wdk_generate_missing_image_sizes'))
4706 {
4707 /**
4708 * Wdk_generate_missing_image_sizes and update meta
4709 * @param int $attachment_id of iamge
4710 * @param string $size_name size of image based on wp intermediate_size
4711 *
4712 * @return bool
4713 */
4714 function wdk_generate_missing_image_sizes($attachment_id, $size_name = '') {
4715 if(empty($size_name) || $size_name == 'full' || !get_option( "{$size_name}_size_w" )) {
4716 return true;
4717 }
4718
4719 // Check if the attachment is an image
4720 if (!wp_attachment_is_image($attachment_id)) {
4721 return false;
4722 }
4723
4724 $file = get_attached_file( $attachment_id );
4725 require_once(ABSPATH . "wp-admin" . '/includes/image.php');
4726 $metadata = wp_generate_attachment_metadata($attachment_id, $file);
4727 if ( ! isset( $metadata['sizes'][ $size_name ] ) ) {
4728 // Generate the missing image size
4729 $resized = image_make_intermediate_size( $file, get_option( "{$size_name}_size_w" ), get_option( "{$size_name}_size_h" ), get_option( "{$size_name}_crop" ) );
4730
4731 // If the resizing was successful, add it to the metadata
4732 if ( $resized ) {
4733 $metadata['sizes'][ $size_name ] = $resized;
4734 wp_update_attachment_metadata( $attachment_id, $metadata );
4735 }
4736 }
4737 return true;
4738 }
4739 }
4740
4741 if (!function_exists('wdk_get_languages')) {
4742
4743 function wdk_get_languages($lang_code_id = null)
4744 {
4745 $lang_pattern = ['title' => '', 'lang_code' => '', 'id' => '', 'icon' => '', 'url' => ''];
4746 $languages = [];
4747
4748 // [qTranslate X]
4749 if (function_exists('qtranxf_getSortedLanguages')) {
4750 global $q_config;
4751
4752 if (empty($q_config)) {
4753 // Initialize qTranslate X language settings if needed
4754 // qtranxf_init_language();
4755 }
4756
4757 $all_langs = qtranxf_getSortedLanguages();
4758 if (count($all_langs) > 0) {
4759 foreach ($all_langs as $key => $lang_code) {
4760 $languages[$key + 1] = array_merge(
4761 $lang_pattern,
4762 [
4763 'title' => $q_config['language_name'][$lang_code],
4764 'lang_code' => $lang_code,
4765 'id' => $key + 1,
4766 'icon' => '',
4767 'url' => wdk_get_language_url($lang_code),
4768 ]
4769 );
4770 }
4771 }
4772 }
4773 // [/qTranslate X]
4774
4775 // [WPML]
4776 if (function_exists('icl_get_languages')) {
4777 $wpml_langs = icl_get_languages('orderby=KEY&order=DIR&link_empty_to=str');
4778 $k = 1;
4779 foreach ($wpml_langs as $key => $lang_data) {
4780 $languages[$k] = array_merge(
4781 $lang_pattern,
4782 [
4783 'title' => (!empty($lang_data['translated_name'])) ? $lang_data['translated_name'] : $lang_data['native_name'],
4784 'lang_code' => $lang_data['language_code'],
4785 'id' => $k,
4786 'icon' => (!empty($lang_data['country_flag_url'])) ? $lang_data['country_flag_url'] : WPDIRECTORYKIT_URL.'public/img/flags/'.$lang_data['language_code'].'.png',
4787 'url' => wdk_get_language_url($lang_data['language_code']),
4788 ]
4789 );
4790 $k++;
4791 }
4792 } elseif (has_filter('wpml_active_languages')) {
4793 $wpml_langs = apply_filters('wpml_active_languages', null) ?: get_query_var('lang', 'all');
4794 if (is_array($wpml_langs)) {
4795 foreach ($wpml_langs as $lang_data) {
4796 if (!isset($lang_data['code']) && isset($lang_data['language_code'])) {
4797 $lang_data['code'] = $lang_data['language_code'];
4798 }
4799 if (empty($lang_data['translated_name']) && !empty($lang_data['native_name'])) {
4800 $lang_data['translated_name'] = $lang_data['native_name'];
4801 }
4802 $languages[$lang_data['id']] = array_merge(
4803 $lang_pattern,
4804 [
4805 'title' => (!empty($lang_data['translated_name'])) ? $lang_data['translated_name'] : $lang_data['native_name'],
4806 'lang_code' => $lang_data['code'],
4807 'id' => $lang_data['id'],
4808 'icon' => (!empty($lang_data['country_flag_url'])) ? $lang_data['country_flag_url'] : WPDIRECTORYKIT_URL.'public/img/flags/'.$lang_data['language_code'].'.png',
4809 'url' => wdk_get_language_url($lang_data['code']),
4810 ]
4811 );
4812 }
4813 }
4814 }
4815 // [/WPML]
4816
4817 // [TranslatePress]
4818 if (function_exists('trp_custom_language_switcher')) {
4819 $k = 1;
4820 foreach (trp_custom_language_switcher() as $lang_data) {
4821 $languages[$k++] = array_merge(
4822 $lang_pattern,
4823 [
4824 'title' => $lang_data['language_name'],
4825 'lang_code' => $lang_data['language_code'],
4826 'id' => $k,
4827 'icon' => $lang_data['flag_link'],
4828 'url' => $lang_data['current_page_url'],
4829 ]
4830 );
4831 }
4832 }
4833 // [/TranslatePress]
4834
4835 if (!empty($lang_code_id)) {
4836 foreach ($languages as $lang) {
4837 if (($lang['id'] == $lang_code_id) || ($lang['lang_code'] == $lang_code_id)) {
4838 return $lang['id'] == $lang_code_id ? $lang['lang_code'] : $lang['id'];
4839 }
4840 }
4841 return false;
4842 }
4843
4844 return $languages;
4845 }
4846 }
4847
4848 if (!function_exists('wdk_default_language')) {
4849 function wdk_default_language()
4850 {
4851 // [qTranslate X]
4852 if (function_exists('qtranxf_getLanguageDefault')) {
4853 return qtranxf_getLanguageDefault();
4854 }
4855 // [/qTranslate X]
4856
4857 // [WPML]
4858 if (function_exists('icl_get_languages')) {
4859 $wpml_langs = icl_get_languages('orderby=KEY&order=DIR&link_empty_to=str');
4860 foreach ($wpml_langs as $lang_data) {
4861 if ($lang_data['major'] == 1) {
4862 return $lang_data['code'];
4863 }
4864 }
4865 } elseif (has_filter('wpml_default_language')) {
4866 return apply_filters('wpml_default_language', null);
4867 }
4868 // [/WPML]
4869
4870 return 'en';
4871 }
4872 }
4873
4874 if (!function_exists('wdk_current_language')) {
4875 function wdk_current_language()
4876 {
4877 if (function_exists('trp_get_languages')) {
4878 global $TRP_LANGUAGE;
4879 $trp = TRP_Translate_Press::get_trp_instance();
4880 $settings = $trp->get_component('settings')->get_settings();
4881 $translation_languages = $trp->get_component('languages')->get_language_names($settings['publish-languages']);
4882 if (isset($translation_languages[$TRP_LANGUAGE])) {
4883 return $translation_languages[$TRP_LANGUAGE];
4884 }
4885 }
4886
4887 // [qTranslate X]
4888 if (function_exists('qtranxf_getLanguage')) {
4889 return qtranxf_getLanguage();
4890 }
4891 // [/qTranslate X]
4892
4893 // [WPML]
4894 if (function_exists('icl_get_languages')) {
4895 $wpml_langs = icl_get_languages('orderby=KEY&order=DIR&link_empty_to=str');
4896 foreach ($wpml_langs as $lang_data) {
4897 if ($lang_data['active'] == 1) {
4898 return (!empty($lang_data['native_name'])) ? $lang_data['native_name'] : $lang_data['language_code'];
4899 }
4900 }
4901 } elseif (has_filter('wpml_current_language')) {
4902 return apply_filters('wpml_current_language', null);
4903 }
4904 // [/WPML]
4905
4906 return 'en';
4907 }
4908 }
4909
4910 if (!function_exists('wdk_current_language_id')) {
4911 function wdk_current_language_id()
4912 {
4913 $lang_id = wdk_get_languages(wdk_current_language());
4914 return is_numeric($lang_id) ? $lang_id : wdk_default_language_id();
4915 }
4916 }
4917
4918 if (!function_exists('wdk_default_language_id')) {
4919 function wdk_default_language_id()
4920 {
4921 $lang_id = wdk_get_languages(wdk_default_language());
4922 return is_numeric($lang_id) ? $lang_id : '1';
4923 }
4924 }
4925
4926 if (!function_exists('wdk_get_language_name')) {
4927 function wdk_get_language_name($id_or_code)
4928 {
4929 $langs = wdk_get_languages();
4930 foreach ($langs as $lang) {
4931 if ($lang['lang_code'] == $id_or_code || $lang['id'] == $id_or_code) {
4932 return $lang['title'];
4933 }
4934 }
4935 return '';
4936 }
4937 }
4938
4939 if (!function_exists('wdk_get_language_url')) {
4940 function wdk_get_language_url($lang_code)
4941 {
4942 // [qTranslate X]
4943 if (function_exists('qtranxf_convertURL')) {
4944 return qtranxf_convertURL('', $lang_code, false, true);
4945 }
4946 // [/qTranslate X]
4947
4948 // [WPML]
4949 if (function_exists('icl_get_languages')) {
4950 $wpml_langs = icl_get_languages('orderby=KEY&order=DIR&link_empty_to=str');
4951 foreach ($wpml_langs as $lang_data) {
4952 if ($lang_data['language_code'] == $lang_code) {
4953 return $lang_data['url'];
4954 }
4955 }
4956 } elseif (has_filter('wpml_active_languages')) {
4957 $wpml_langs = apply_filters('wpml_active_languages', null);
4958 foreach ($wpml_langs as $lang_data) {
4959 if (!isset($lang_data['language_code']) && isset($lang_data['language_code'])) {
4960 $lang_data['language_code'] = $lang_data['language_code'];
4961 }
4962 if (empty($lang_data['translated_name']) && !empty($lang_data['native_name'])) {
4963 $lang_data['translated_name'] = $lang_data['native_name'];
4964 }
4965 $url = wdk_wpml_ls_language_url($lang_data['url'], $lang_data);
4966 if ($lang_data['language_code'] == $lang_code) {
4967 return $url;
4968 }
4969 }
4970 }
4971 // [/WPML]
4972
4973 return '';
4974 }
4975 }
4976
4977 function wdk_set_user_default_language($user_id = null)
4978 {
4979 if (is_null($user_id)) {
4980 $user_id = get_current_user_id();
4981 }
4982
4983 $get_language = get_user_meta($user_id, 'user_language', true);
4984
4985 if (!$get_language && (function_exists('icl_get_languages') || has_filter('wpml_active_languages'))) {
4986 do_action('wpml_switch_language', $get_language);
4987 }
4988 }
4989
4990 function wdk_set_language($lang_code = null)
4991 {
4992 if (!is_null($lang_code) && (function_exists('icl_get_languages') || has_filter('wpml_active_languages'))) {
4993 do_action('wpml_switch_language', $lang_code);
4994 }
4995 }
4996
4997 function wdk_wpml_ls_language_url($url, $data)
4998 {
4999 global $sitepress;
5000
5001 if (is_object($sitepress)) {
5002 $sitepress_settings = $sitepress->get_settings();
5003 }
5004
5005 return $url;
5006 }
5007
5008 add_filter('wpml_ls_language_url', 'wdk_wpml_ls_language_url', 10, 3);
5009
5010 if (!function_exists('wdk_calculate_nights')) {
5011 /**
5012 * Calculate the number of nights between two dates
5013 *
5014 * This function takes two date strings as input and calculates the number of nights
5015 * (i.e., the difference in days) between them. It returns the total number of nights
5016 * between the provided start and end dates. The date format must be valid for PHP's
5017 * DateTime class.
5018 *
5019 * @param string $start_date The start date in 'Y-m-d' format.
5020 * @param string $end_date The end date in 'Y-m-d' format.
5021 * @return int The number of nights (days between the two dates).
5022 */
5023 function wdk_calculate_nights($start_date, $end_date) {
5024
5025 /* normalize date */
5026 $start_date = wdk_normalize_date_db($start_date, 'Y-m-d H:i:s', 'Y-m-d');
5027 $end_date = wdk_normalize_date_db($end_date, 'Y-m-d H:i:s', 'Y-m-d');
5028
5029 // Create DateTime objects for start and end dates
5030 $start = new DateTime($start_date);
5031 $end = new DateTime($end_date);
5032
5033 // Calculate the difference between the two dates
5034 $difference = $start->diff($end);
5035
5036 // Return the number of nights (difference in days)
5037 return $difference->days;
5038 }
5039 }
5040
5041 if ( ! function_exists('wdk_select_db_field_ajax'))
5042 {
5043 /**
5044 * Return select2 ajax
5045 *
5046 * @param string option Option key
5047 * @return string alt or title
5048 */
5049 function wdk_select_db_field_ajax($name = '', $selected = NULL, $empty_value='', $filter_id = '')
5050 {
5051 $WMVC = &wdk_get_instance();
5052
5053 static $counter = 0;
5054 $form = '<select data-ajax="'.admin_url('admin-ajax.php').'" name="'.$name.'" data-id="'.$filter_id.'" data-placeholder="'.$empty_value.'" class="form-control wdk_select2_field_suggestion" id="wdk_select2_field_'.$filter_id.'_'.$counter.'" multiple="">';
5055 if($selected) {
5056 if(is_array($selected)) {
5057 /* where in */
5058 foreach ($selected as $item) {
5059 $form .= '<option selected="selected" value="'.esc_attr($item).'">'.esc_html($item).'</option>';
5060 }
5061 } elseif(is_string($selected)) {
5062 $form .= '<option selected="selected" value="'.esc_attr($selected).'">'.esc_html($selected).'</option>';
5063 }
5064 } else {
5065 //$form .= '<option value="" selected="selected">'.esc_html__('Not selected', 'wpdirectorykit').'</option>';
5066 }
5067 $form .= '</select>';
5068
5069 //load javascript library
5070 if($counter==0)
5071 {
5072 wp_enqueue_script('select2-select2');
5073 wp_enqueue_script('wdk-select2');
5074 wp_enqueue_style('select2-select2');
5075 }
5076 ?>
5077 <?php
5078 $counter++;
5079 return $form;
5080
5081 }
5082 }
5083
5084 if ( ! function_exists('wdk_next_month_payment_day'))
5085 {
5086 /**
5087 * Gets the next payment date one month later, considering the number of days in the next month.
5088 *
5089 * @param string $currentDate The current payment date in 'Y-m-d H:i:s' format.
5090 * @return string|false The next payment date in 'Y-m-d H:i:s' format or false on error.
5091 */
5092 function wdk_next_month_payment_day($currentDate, $time = false, $wanted_day = NULL) {
5093 $nextDate = null;
5094 $timestamp = strtotime($currentDate);
5095 $daysInNextMonth = date('t', strtotime('+1 month', strtotime(date('Y-m', $timestamp))));
5096 $currentDay = (int)date('d', $timestamp);
5097
5098 $timeFormat = $time ? "H:i:s" : "00:00:00";
5099
5100
5101 // Determine the wanted day
5102 if ($wanted_day !== NULL) {
5103 $wanted_day = (int)date('d', strtotime($wanted_day));
5104 } else {
5105 $wanted_day = (int)date('d', $timestamp);
5106 }
5107
5108 $nextMonth = strtotime('first day of next month', $timestamp);
5109 $daysInNextMonth = date('t', $nextMonth);
5110
5111 // Adjust for the wanted day
5112 if ($wanted_day > $daysInNextMonth ||
5113 (
5114 get_option('wdk_membership_next_month_calculation_with_last_day')
5115
5116 && (
5117 $currentDay >= 30 || $currentDay == date('t', $timestamp)
5118 )
5119 )
5120 ) {
5121 // If the wanted day exceeds the max days of the next month, use the last day of the month
5122 $nextDate = date("Y-m-{$daysInNextMonth} {$timeFormat}", $nextMonth);
5123 } else {
5124 // Otherwise, set the exact wanted day
5125 $nextDate = date("Y-m-{$wanted_day} {$timeFormat}", $nextMonth);
5126 }
5127
5128 return ($nextDate) ? $nextDate : false;
5129 }
5130 }
5131
5132 if ( ! function_exists('wdk_next_year_payment_day'))
5133 {
5134 /**
5135 * Gets the next payment date one year later, considering the number of days in the next month.
5136 *
5137 * @param string $currentDate The current payment date in 'Y-m-d H:i:s' format.
5138 * @return string|false The next payment date in 'Y-m-d H:i:s' format or false on error.
5139 */
5140
5141 function wdk_next_year_payment_day($currentDate, $time = false) {
5142 $nextDate = null;
5143 $timestamp = strtotime($currentDate);
5144 $nextYearTimestamp = strtotime('+1 year', strtotime(date('Y-m', $timestamp)));
5145 $daysInNextMonth = date('t', $nextYearTimestamp);
5146 $currentDay = date('j', $timestamp);
5147 $timeFormat = "00:00:00";
5148 if($time) {
5149 $timeFormat = "H:i:s";
5150 }
5151 if ($currentDay > $daysInNextMonth) {
5152 $nextDate = date('Y-m-d '.$timeFormat, strtotime('last day of this month', $nextYearTimestamp));
5153 } else {
5154 $nextDate = date('Y-m-d '.$timeFormat, strtotime('+1 year', $timestamp));
5155 }
5156
5157 return ($nextDate) ? $nextDate : false;
5158 }
5159 }
5160
5161 if ( ! function_exists('wdk_generate_auto_login_link'))
5162 {
5163 function wdk_generate_auto_login_link( $user_id = null ) {
5164 $token = substr(md5($user_id.NONCE_KEY.'wpdirectorykit'),0,10);
5165
5166 $login_url = site_url( "/?auto-login=1&user_id={$user_id}&token={$token}" );
5167 return $login_url;
5168 }
5169 }
5170
5171 if ( ! function_exists('wdk_get_user_subscription_id'))
5172 {
5173 function wdk_get_user_subscription_id($user_id = null) {
5174 global $Winter_MVC_wdk_membership;
5175 if(!isset($Winter_MVC_wdk_membership)) {
5176 return false;
5177 }
5178 $Winter_MVC_wdk_membership->model('subscription_user_m');
5179 $user_subscription = $Winter_MVC_wdk_membership->subscription_user_m->get_by(array('user_id'=>$user_id), TRUE);
5180 return wmvc_show_data('subscription_id', $user_subscription, '', TRUE, TRUE);
5181 }
5182 }
5183
5184 if ( ! function_exists('is_wdk_related_validation'))
5185 /**
5186 * IS WDK related validation
5187 *
5188 * @return bool true if exists dash
5189 */
5190 {
5191 function is_wdk_related_validation($param)
5192 {
5193
5194 if(empty($param)) {
5195 return TRUE;
5196 }
5197
5198 $listing_id = (!empty($_GET['id'])) ? intval(sanitize_text_field($_GET['id'])) : null;
5199
5200
5201 global $Winter_MVC_WDK;
5202 $Winter_MVC_WDK->model('listing_m');
5203
5204 $Winter_MVC_WDK->db->select('post_id');
5205 $Winter_MVC_WDK->db->where(array(
5206 '(post_id IN ('.esc_sql(sanitize_text_field($param)).'))' => NULL,
5207 '((`listing_related_ids` IS NOT NULL AND `listing_related_ids` !="") OR (`listing_parent_post_id` IS NOT NULL AND `listing_parent_post_id` !=0))' => NULL,
5208 ));
5209
5210 if($listing_id) {
5211 $Winter_MVC_WDK->db->where(array(
5212 '`listing_parent_post_id` !='.esc_sql($listing_id).'' => NULL,
5213 ));
5214 }
5215
5216 $Winter_MVC_WDK->db->from($Winter_MVC_WDK->listing_m->_table_name);
5217 $Winter_MVC_WDK->db->limit(5);
5218
5219 $Winter_MVC_WDK->db->get();
5220 if ($Winter_MVC_WDK->db->num_rows() > 0) {
5221 $db_results = $Winter_MVC_WDK->db->results();
5222 } else {
5223 $db_results = null;
5224 }
5225
5226 if (!empty($db_results)) {
5227 return false;
5228 }
5229
5230 return TRUE;
5231 }
5232 }
5233
5234 /**
5235 * Renders an Elementor template by its title or post ID.
5236 *
5237 * Attempts to find and render an Elementor layout/template using the post title or post ID.
5238 * If the post is found and public, its rendered Elementor content is returned, otherwise post content fallback or error.
5239 *
5240 * @since 1.0.0
5241 * @param string|int $title The title (or ID if $id=true) of the Elementor template to render.
5242 * @param bool $id Optional. If true, $title is treated as a post ID. If false (default), searches by title.
5243 * @return string|false Rendered template HTML on success, public/content fallback, or error message/false on failure.
5244 */
5245 function wdk_render_elementor_template( $title, $id = false ) {
5246 // Initialize variables.
5247 $layout_id = null;
5248 $template_content = '';
5249
5250 // Determine the layout/post ID.
5251 if ( ! $id ) {
5252 // Search by post title. Returns WP_Post/object or null.
5253 $found_post = wdk_page_by_title( $title, OBJECT, ['elementor_library','page'] );
5254 $layout_id = $found_post ? $found_post->ID : null;
5255
5256 // Support WPML translation if present.
5257 // The filter may change $layout_id to a translated post's ID if needed.
5258 $layout_id = apply_filters( 'wpml_object_id', $layout_id, 'elementor_library', true );
5259 } else {
5260 // ID provided directly.
5261 $layout_id = intval($title);
5262 }
5263
5264 // Early return if no valid layout found.
5265 if ( empty( $layout_id ) ) {
5266 return false;
5267 }
5268
5269 // Get post object (Elementor template or WP Page).
5270 $post_data = get_post( $layout_id );
5271
5272
5273 // Validate post: should exist, be published, and not password protected.
5274 if ( ! $post_data || $post_data->post_status !== 'publish' || post_password_required( $post_data ) ) {
5275 return esc_html__( 'Layout is not public', 'wpdirectorykit' );
5276 }
5277
5278 // Render content depending on post type.
5279 if (
5280 ( isset($post_data->post_type) && $post_data->post_type === 'elementor_library' ) ||
5281 ( isset($post_data->post_type) && $post_data->post_type === 'page' )
5282 ) {
5283 // Try to render using Elementor's frontend builder.
5284 if ( class_exists('\Elementor\Plugin') && method_exists('\Elementor\Plugin', 'instance') ) {
5285 $elementor_instance = \Elementor\Plugin::instance();
5286 $content = $elementor_instance->frontend->get_builder_content_for_display( $layout_id );
5287 $template_content = ! empty( $content ) ? $content : $post_data->post_content;
5288 } else {
5289 // Elementor not present; fallback to post content.
5290 $template_content = $post_data->post_content;
5291 }
5292 } else {
5293 // Non-Elementor post types, fallback to post content.
5294 $template_content = $post_data->post_content;
5295 }
5296
5297 /**
5298 * Filter: Allows modification of the rendered Elementor template content before returning.
5299 *
5300 * @param string $template_content The rendered template content.
5301 * @param int $layout_id The ID of the layout/template.
5302 * @param WP_Post $post_data The WP_Post object of the layout/template.
5303 */
5304 return apply_filters( 'wdk_render_elementor_template_output', $template_content, $layout_id, $post_data );
5305 }
5306
5307 if(!function_exists('wdk_esc_sql')) {
5308 function wdk_esc_sql($value = '', $strict = false) {
5309 $patterns = [
5310 '/\bselect\b/i',
5311 '/\binsert\b/i',
5312 '/\bupdate\b/i',
5313 '/\bdelete\b/i',
5314 '/\bunion\b/i',
5315 '/\bextractvalue\b/i',
5316 '/\bversion\s*\(\)/i',
5317 '/\bdatabase\s*\(\)/i',
5318 '/\bconcat\s*\(/i',
5319 '/\bdrop\b/i',
5320 '/\bsleep\s*\(/i',
5321 '/\bbenchmark\s*\(/i',
5322 '/--/',
5323 '/#/i',
5324 '/\/\*/',
5325
5326 // EXTRA BLOCK YOU REQUESTED
5327 '/\\\\/', // remove backslash \
5328 '/\|/', // remove |
5329 '/%/', // remove %
5330 ];
5331
5332 // If strict mode is enabled, block additional patterns
5333 if ($strict === true) {
5334 $strict_patterns = [
5335 '/\bif\b\s*\(/i',
5336 '/\bord\b/i',
5337 '/\bsubstr\s*\(/i',
5338 '/\bschema\s*\(\)/i',
5339 '/@@version/i',
5340 ];
5341 $patterns = array_merge($patterns, $strict_patterns);
5342 }
5343
5344 return esc_sql(trim(preg_replace($patterns, '', sanitize_text_field($value))));
5345 }
5346 }
5347
5348 if(!function_exists('wdk_esc_sql_order_by')) {
5349 function wdk_esc_sql_order_by($value = '', array $allowed_fields = [])
5350 {
5351 if (empty($value) || empty($allowed_fields)) {
5352 return '';
5353 }
5354 $result = [];
5355 foreach (explode(',', $value) as $part) {
5356 $part = trim(sanitize_text_field($part));
5357
5358 $direction = 'ASC';
5359 if (preg_match('/\s+(ASC|DESC)$/i', $part, $match)) {
5360 $direction = strtoupper($match[1]);
5361 $part = trim(substr($part, 0, -strlen($match[0])));
5362 }
5363
5364 $part = sanitize_key($part);
5365
5366 if (in_array($part, $allowed_fields, true)) {
5367 $result[] = $part . ' ' . $direction;
5368 }
5369 }
5370
5371 return implode(', ', $result);
5372 }
5373 }
5374
5375 if(!function_exists('wdk_listing_seo_title')) {
5376 function wdk_listing_seo_title () {
5377 static $cached_seo_title = null;
5378 if ($cached_seo_title !== null) {
5379 return $cached_seo_title;
5380 }
5381
5382 $seo_title ='';
5383 global $wp_query;
5384 $wdk_listing_id = $wp_query->post->ID;
5385 if(wdk_get_option('wdk_seo_listing_title')) {
5386 global $Winter_MVC_WDK;
5387 $Winter_MVC_WDK->model('field_m');
5388 $Winter_MVC_WDK->load_helper('listing');
5389
5390 $seo_template = wdk_get_option('wdk_seo_listing_title');
5391
5392 $matches = [];
5393 preg_match_all('/{(?:field_)?([^}]+)}/', $seo_template, $matches);
5394 $fields_in_template = isset($matches[1]) ? $matches[1] : [];
5395
5396 $fields_values = [];
5397
5398 foreach ($fields_in_template as $field_id) {
5399 $key_id = '{field_' . $field_id . '}';
5400 if($field_id == 'category') {
5401 $field_id = 'category_title';
5402 }
5403 if($field_id == 'location') {
5404 $field_id = 'location_title';
5405 }
5406 // Try to get value for field_id for this listing
5407 $fields_values[$key_id] = wdk_field_value($field_id, $wdk_listing_id);
5408 }
5409 // Replace the fields in template with real values
5410 $seo_title = strtr($seo_template, $fields_values);
5411 }
5412
5413 $cached_seo_title = $seo_title;
5414 return $seo_title;
5415 }
5416 }
5417
5418
5419 if ( ! function_exists('wdk_filter_viber_phone'))
5420 {
5421 // Validation phone for viber
5422 /**
5423 * @param string $value phone in string
5424 * @return strings +xxx
5425 */
5426 function wdk_filter_viber_phone($value = '') {
5427 $value = str_replace(array(' ','-','(',')'),'',$value);
5428 return (strpos($value, '+') !== 0) ? '+' . $value : $value;
5429 }
5430 }
5431
5432 ?>
5433