PluginProbe
WP Directory Kit / 1.4.8
WP Directory Kit v1.4.8
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 1.4.0 1.4.1 All 35 releases
wpdirectorykit / application / helpers / Basic.php

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

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