Code

< 40 %
40-60 %
> 60 %
1
<?php
2
/**
3
 * Hook and filter actions used by the plugin
4
 *
5
 * @since 1.0.0
6
 * @package GeoDirectory
7
 * @global array $geodir_addon_list List of active GeoDirectory extensions.
8
 * @global string $plugin_file_name Plugin main file name. 'geodirectory/geodirectory.php'.
9
 */
10
11
/**
12
 * Return the GeoDirectory ajax specific url.
13
 *
14
 * This is used to run GeoDirectory specific functions via ajax.
15
 *
16
 * @since 1.0.0
17
 * @package GeoDirectory
18
 * @return string The GeoDirectory ajax URL.
19
 */
20
function geodir_get_ajax_url()
21
{
22 2
    return admin_url('admin-ajax.php?action=geodir_ajax_action');
23
}
24
25
/////////////////////
26
/* ON INIT ACTIONS */
27
/////////////////////
28
29
add_action('init', 'geodir_on_init', 1);
30
31
add_action('init', 'geodir_add_post_filters');
32
33
//add_action('init', 'geodir_init_defaults');
34
35
add_action('init', 'geodir_allow_post_type_frontend');
36
37
add_action('init', 'geodir_register_taxonomies', 1);
38
39
add_action('init', 'geodir_register_post_types', 2);
40
41
add_filter('geodir_post_type_args', 'geodir_post_type_args_modify', 0, 2);
42
43
//add_action( 'init', 'geodir_flush_rewrite_rules', 99 );
44
45
add_action('init', 'geodir_custom_post_status');
46
47
add_action('widgets_init', 'geodir_register_sidebar'); // Takes care of widgets
48
49
global $geodir_addon_list;
50
/**
51
 * Build an array of installed addons.
52
 *
53
 * This filter builds an array of installed addons which can be used to check what exactly is installed.
54
 *
55
 * @since 1.0.0
56
 * @package GeoDirectory
57
 * @param array $geodir_addon_list The array of installed plugins $geodir_addon_list['geodir_location_manager'].
58
 */
59
apply_filters('geodir_build_addon_list', $geodir_addon_list);
60
61
add_action('wp_ajax_geodir_ajax_action', "geodir_ajax_handler");
62
63
add_action('wp_ajax_nopriv_geodir_ajax_action', 'geodir_ajax_handler');
64
65
/* Pluploader */
66
add_action('wp_ajax_plupload_action', "geodir_plupload_action");
67
68
add_action('wp_ajax_nopriv_plupload_action', 'geodir_plupload_action'); // call for not logged in ajax
69
70
////////////////////////
71
/* Widget Initialization */
72
////////////////////////
73
74
add_action('widgets_init', 'register_geodir_widgets');
75
76
////////////////////////
77
/* REWRITE RULES */
78
////////////////////////
79
80
add_filter('rewrite_rules_array', 'geodir_listing_rewrite_rules');
81
82
////////////////////////
83
/* QUERY VARS */
84
////////////////////////
85
86
add_filter('query_vars', 'geodir_add_location_var');
87
add_filter('query_vars', 'geodir_add_geodir_page_var');
88
add_action('wp', 'geodir_add_page_id_in_query_var'); // problem fix in wordpress 3.8
89
if (get_option('permalink_structure') != '')
90
    add_filter('parse_request', 'geodir_set_location_var_in_session_in_core');
91
92
add_filter('parse_query', 'geodir_modified_query');
93
94
95
////////////////////////
96
/* ON WP LOAD ACTIONS */
97
////////////////////////
98
99
//add_action( 'wp_loaded','geodir_flush_rewrite_rules' );
100
add_action('wp_loaded', 'geodir_on_wp_loaded', 10);
101
102
add_action('wp', 'geodir_on_wp', 10);
103
104
105
/////////////////////////////
106
/* ON WP HEAD ACTIONS */
107
/////////////////////////////
108
109
add_action('wp_head', 'geodir_header_scripts');
110
111
// add_action('admin_head', 'geodir_header_scripts'); // Removed since 1.5.0
112
113
add_action('wp_head', 'geodir_init_map_jason'); // Related to MAP
114
115
add_action('wp_head', 'geodir_init_map_canvas_array'); // Related to MAP
116
117
add_action('wp_head', 'geodir_restrict_widget'); // Related to widgets
118
119
//////////////////////////////
120
/* ENQUEUE SCRIPTS AND STYLES */
121
//////////////////////////////
122
123
add_action('wp_enqueue_scripts', 'geodir_templates_scripts');
124
125
add_action('wp_enqueue_scripts', 'geodir_templates_styles', 8);
126
127
////////////////////////
128
/* ON MAIN NAVIGATION */
129
////////////////////////
130
add_filter('wp_nav_menu_items', 'geodir_menu_items', 100, 2);
131
132
add_filter('wp_page_menu', 'geodir_pagemenu_items', 100, 2);
133
134
135
/////////////////////////
136
/* ON TEMPLATE INCLUDE */
137
/////////////////////////
138
139
add_filter('template_include', 'geodir_template_loader',9);
140
141
/////////////////////////
142
/* CATEGORY / TAXONOMY / CUSTOM POST ACTIONS */
143
/////////////////////////
144
145
//add_action('edited_term','geodir_update_markers_oncatedit',10,3);
146
147
add_filter('term_link', 'geodir_get_term_link', 10, 3);
148
149
add_filter('post_type_archive_link', 'geodir_get_posttype_link', 10, 2);
150
151
add_filter('post_type_link', 'geodir_listing_permalink_structure', 10, 4);
152
153
////////////////////////
154
/* POST AND LOOP ACTIONS */
155
////////////////////////
156
if (!is_admin()) {
157
    add_action('pre_get_posts', 'geodir_exclude_page', 100); /// Will help to exclude virtual page from everywhere
158
    add_filter('wp_list_pages_excludes', 'exclude_from_wp_list_pages', 100);
159
    /** Exclude Virtual Pages From Pages List **/
160
    add_action('pre_get_posts', 'set_listing_request', 0);
161
    add_action('pre_get_posts', 'geodir_listing_loop_filter', 1);
162
    add_filter('excerpt_more', 'geodir_excerpt_more', 1000);
163
    add_filter('excerpt_length', 'geodir_excerpt_length', 1000);
164
    add_action('the_post', 'create_marker_jason_of_posts'); // Add marker in json array, Map related filter
165
}
166
167
168
add_action('set_object_terms', 'geodir_set_post_terms', 10, 4);
169
170
add_action('transition_post_status', 'geodir_update_poststatus', 10, 3);
171
172
add_action('before_delete_post', 'geodir_delete_listing_info', 10, 1);
173
174
175
////////////////////////
176
/* WP REVIEW COUNT ACTIONS */
177
////////////////////////
178
179
add_action('geodir_update_postrating', 'geodir_term_review_count_force_update_single_post', 100,1);
180
//add_action('geodir_update_postrating', 'geodir_term_review_count_force_update', 100);
181
add_action('transition_post_status', 'geodir_term_review_count_force_update', 100,3);
182
//add_action('created_term', 'geodir_term_review_count_force_update', 100);
183
add_action('edited_term', 'geodir_term_review_count_force_update', 100);
184
//add_action('delete_term', 'geodir_term_review_count_force_update', 100); /*causes memory timeout on delete bulk tags*/
185
186
////////////////////////
187
/* WP CAT META UPDATE ACTIONS */
188
////////////////////////
189
add_action('gd_tax_meta_updated', 'geodir_get_term_icon_rebuild', 5000);
190
////////////////////////
191
/* WP FOOTER ACTIONS */
192
////////////////////////
193
194
add_action('wp_footer', 'geodir_footer_scripts'); /* Footer Scripts loader */
195
196
add_action('wp_footer', 'send_marker_jason_to_js'); // Show map for listings with markers
197
198
199
add_action('admin_footer', 'geodir_localize_all_js_msg');
200
201
add_action('wp_footer', 'geodir_localize_all_js_msg');
202
203
add_action('admin_head-media-upload-popup', 'geodir_localize_all_js_msg');
204
add_action('customize_controls_print_footer_scripts', 'geodir_localize_all_js_msg');
205
206
add_action('wp_head', 'geodir_add_meta_keywords');
207
add_action('wp_head', 'geodir_google_analytics_tracking_code');
208
209
/* Sharelocation scripts */
210
//global $geodir_addon_list;
211
//if(!empty($geodir_addon_list) && array_key_exists('geodir_sharelocation_manager', $geodir_addon_list) && $geodir_addon_list['geodir_sharelocation_manager'] == 'yes') { 
212
add_action('wp_footer', 'geodir_add_sharelocation_scripts');
213
//}
214
215
216
/**
217
 * Save and update GeoDirectory navigation settings per theme.
218
 *
219
 * @since 1.0.0
220
 * @package GeoDirectory
221
 * @param string $newname The theme name.
222
 * @ignore
223
 */
224
function geodir_unset_prev_theme_nav_location($newname)
225
{
226
    $geodir_theme_location = get_option('geodir_theme_location_nav_' . $newname);
227
    if ($geodir_theme_location) {
228
        update_option('geodir_theme_location_nav', $geodir_theme_location);
229
    } else {
230
        update_option('geodir_theme_location_nav', '');
231
    }
232
}
233
234
/// add action for theme switch to blank previous theme navigation location setting
235
add_action("switch_theme", "geodir_unset_prev_theme_nav_location", 10, 2);
236
237
/**
238
 * Contains functions/hooks for setting up the CPT and taxonomies for the plugin.
239
 *
240
 * @since 1.0.0
241
 */
242
require_once('geodirectory-functions/custom_taxonomy_hooks_actions.php');
243
244
/**
245
 * Includes the file that adds filters/functions to change the database queries.
246
 *
247
 * @since 1.0.0
248
 * @package GeoDirectory
249
 */
250
function geodir_add_post_filters()
251
{
252
    /**
253
     * Contains all function for filtering listing.
254
     *
255
     * @since 1.0.0
256
     * @package GeoDirectory
257
     */
258
    include_once('geodirectory-functions/listing_filters.php');
259
    
260
    // Theme My Login compatibility fix
261
    if ( isset( $_REQUEST['geodir_search'] ) && class_exists( 'Theme_My_Login' ) ) {
262
        remove_action( 'pre_get_posts', array( Theme_My_Login::get_object(), 'pre_get_posts' ) );
263
    }
264
    
265
    if ( isset( $_REQUEST['geodir_search'] ) ) {
266
        add_filter( 'geodir_filter_widget_listings_fields', 'geodir_search_widget_location_filter_fields', 100, 3 );
267
        add_filter( 'geodir_filter_widget_listings_orderby', 'geodir_search_widget_location_filter_orderby', 100, 3 );
268
    }
269
}
270
271
272
if (!function_exists('geodir_init_defaults')) {
273
    /**
274
     * Calls the function to register the GeoDirectory default CPT and taxonomies.
275
     *
276
     * @since 1.0.0
277
     * @package GeoDirectory
278
     */
279
    function geodir_init_defaults()
280
    {
281
        if (function_exists('geodir_register_defaults')) {
282
283
            geodir_register_defaults();
284
285
        }
286
287
    }
288
}
289
290
291
/* Sidebar */
292
add_action('geodir_sidebar', 'geodir_get_sidebar', 10);
293
294
295
/* Pagination in loop-store */
296
add_action('geodir_pagination', 'geodir_pagination', 10);
297
298
299
/** Add Custom Menu Items **/
300
301
302
/** Replaces "Post" in the update messages for custom post types on the "Edit" post screen. **/
303
add_filter('post_updated_messages', 'geodir_custom_update_messages');
304
305
306
// CALLED ON 'sidebars_widgets' FILTER
307
308
if (!function_exists('geodir_restrict_widget')) {
309
    /**
310
     * Sets global values to be able to tell if the current page is a GeoDirectory listing page or a GeoDirectory details page.
311
     *
312
     * @global bool $is_listing Sets the global value to true if on a GD category page. False if not.
313
     * @global bool $is_single_place Sets the global value to true if on a GD details (post) page. False if not.
314
     * @since 1.0.0
315
     * @package GeoDirectory
316
     */
317
    function geodir_restrict_widget()
318
    {
319
        global $is_listing, $is_single_place;
320
321
        // set is listing	
322
        (geodir_is_page('listing')) ? $is_listing = true : $is_listing = false;
323
324
        // set is single place
325
        (geodir_is_page('place')) ? $is_single_place = true : $is_single_place = false;
326
327
328
    }
329
}
330
331
332
/////// GEO DIRECOTORY CUSTOM HOOKS ///
333
334
add_action('geodir_before_tab_content', 'geodir_before_tab_content');// this function is in custom_functions.php and it is used to wrap detail page tab content 
335
add_action('geodir_after_tab_content', 'geodir_after_tab_content');// this function is in custom_functions.php and it is used to wrap detail page tab content
336
337
// Detail page sidebar content 
338
add_action('geodir_detail_page_sidebar', 'geodir_detail_page_sidebar_content_sorting', 1);
339
/**
340
 * Builds an array of elements for the details (post) page sidebar.
341
 *
342
 * Builds an array of functions to be called in the details page (post) sidebar, this array can be changed via hook or filter.
343
 *
344
 * @since 1.0.0
345
 * @package GeoDirectory
346
 */
347
function geodir_detail_page_sidebar_content_sorting()
348
{
349
    $arr_detail_page_sidebar_content =
350
        /**
351
         * An array of functions to be called to be displayed on the details (post) page sidebar.
352
         *
353
         * This filter can be used to remove sections of the details page sidebar,
354
         * add new sections or rearrange the order of the sections.
355
         *
356
         * @param array array('geodir_social_sharing_buttons','geodir_share_this_button','geodir_detail_page_google_analytics','geodir_edit_post_link','geodir_detail_page_review_rating','geodir_detail_page_more_info') The array of functions that will be called.
357
         * @since 1.0.0
358
         */
359
        apply_filters('geodir_detail_page_sidebar_content',
360
            array('geodir_social_sharing_buttons',
361
                'geodir_detail_page_google_analytics',
362
                'geodir_edit_post_link',
363
                'geodir_detail_page_review_rating',
364
                'geodir_detail_page_more_info'
365
            ) // end of array 
366
        ); // end of apply filter
367
    if (!empty($arr_detail_page_sidebar_content)) {
368
        foreach ($arr_detail_page_sidebar_content as $content_function) {
369
            if (function_exists($content_function)) {
370
                add_action('geodir_detail_page_sidebar', $content_function);
371
            }
372
        }
373
    }
374
}
375
376
add_action('geodir_after_edit_post_link', 'geodir_add_to_favourite_link', 1);
377
378
/**
379
 * Outputs the add to favourite line for the current post if not add listing preview page.
380
 *
381
 * @global object $post The current post object.
382
 * @global bool $preview True if the current page is add listing preview page. False if not.
383
 * since 1.0.0
384
 * @package GeoDirectory
385
 */
386
function geodir_add_to_favourite_link()
387
{
388
    global $post, $preview;
389
    if (!$preview && geodir_is_page('detail')) {
390
        ?>
391
        <p class="edit_link">
392
            <?php geodir_favourite_html($post->post_author, $post->ID); ?>
393
        </p>
394
    <?php
395
    }
396
}
397
398
/**
399
 * Outputs social buttons.
400
 *
401
 * Outputs social sharing buttons twitter,facebook and google plus into a containing div if not on the add listing preview page.
402
 *
403
 * @global bool $preview True if the current page is add listing preview page. False if not.
404
 * @since 1.0.0
405
 * @package GeoDirectory
406
 */
407
function geodir_social_sharing_buttons()
408
{
409
    global $preview;
410
    ob_start(); // Start  buffering;
411
    /**
412
     * This action is called before the social buttons twitter,facebook and google plus are output in a containing div.
413
     *
414
     * @since 1.0.0
415
     */
416
    do_action('geodir_before_social_sharing_buttons');
417
    if (!$preview) {
418
        ?>
419
        <div class="likethis">
420
            <?php geodir_twitter_tweet_button(); ?>
421
            <?php geodir_fb_like_button(); ?>
422
            <?php geodir_google_plus_button(); ?>
423
        </div>
424
    <?php
425
    }// end of if, if its a preview or not
426
427
    /**
428
     * This action is called after the social buttons twitter,facebook and google plus are output in a containing div.
429
     *
430
     * @since 1.0.0
431
     */
432
    do_action('geodir_after_social_sharing_buttons');
433
    $content_html = ob_get_clean();
434
    if (trim($content_html) != '')
435
        $content_html = '<div class="geodir-company_info geodir-details-sidebar-social-sharing">' . $content_html . '</div>';
436
    if ((int)get_option('geodir_disable_tfg_buttons_section') != 1) {
437
        /**
438
         * Filter the geodir_social_sharing_buttons() function content.
439
         *
440
         * @param string $content_html The output html of the geodir_social_sharing_buttons() function.
441
         */
442
        echo $content_html = apply_filters('geodir_social_sharing_buttons_html', $content_html);
443
    }
444
445
446
}
447
448
449
/**
450
 * Outputs the edit post link.
451
 *
452
 * Outputs the edit post link if the current logged in user owns the post.
453
 *
454
 * @global bool $preview True if the current page is add listing preview page. False if not.
455
 * @global WP_Post|null $post The current post, if available.
456
 * @since 1.0.0
457
 * @package GeoDirectory
458
 */
459
function geodir_edit_post_link()
460
{
461
    global $post, $preview;
462
    ob_start(); // Start buffering;
463
    /**
464
     * This is called before the edit post link html in the function geodir_edit_post_link()
465
     *
466
     * @since 1.0.0
467
     */
468
    do_action('geodir_before_edit_post_link');
469
    if (!$preview) {
470
        $is_current_user_owner = geodir_listing_belong_to_current_user();
471
        
472
        if ($is_current_user_owner) {
473
            $post_id = $post->ID;
474
            
475
            if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
476
                $post_id = (int)$_REQUEST['pid'];
477
            }
478
479
            $postlink = get_permalink(geodir_add_listing_page_id());
480
            $editlink = geodir_getlink($postlink, array('pid' => $post_id), false);
481
            echo ' <p class="edit_link"><i class="fas fa-pencil-alt"></i> <a href="' . esc_url($editlink) . '">' . __('Edit this Post', 'geodirectory') . '</a></p>';
482
        }
483
    }// end of if, if its a preview or not
484
    /**
485
     * This is called after the edit post link html in the function geodir_edit_post_link()
486
     *
487
     * @since 1.0.0
488
     */
489
    do_action('geodir_after_edit_post_link');
490
    $content_html = ob_get_clean();
491
    if (trim($content_html) != '')
492
        $content_html = '<div class="geodir-company_info geodir-details-sidebar-user-links">' . $content_html . '</div>';
493
    if ((int)get_option('geodir_disable_user_links_section') != 1) {
494
        /**
495
         * Filter the geodir_edit_post_link() function content.
496
         *
497
         * @param string $content_html The output html of the geodir_edit_post_link() function.
498
         */
499
        echo $content_html = apply_filters('geodir_edit_post_link_html', $content_html);
500
    }
501
}
502
503
/**
504
 * Outputs the google analytics section on details page.
505
 *
506
 * Outputs the google analytics html if the current logged in user owns the post.
507
 *
508
 * @global WP_Post|null $post The current post, if available.
509
 * @since 1.0.0
510
 * @package GeoDirectory
511
 */
512
function geodir_detail_page_google_analytics()
513
{
514
    if ( ! get_option( 'geodir_ga_stats' ) ) {
515
		return;
516
	}
517
	global $post,$preview;
518
    if($preview){return '';}
519
    $package_info = array();
520
    $package_info = geodir_post_package_info($package_info, $post);
521
522
    $id = trim(get_option('geodir_ga_account_id'));
523
524
    if (!$id) {
525
        return; //if no Google Analytics ID then bail.
526
    }
527
528
    ob_start(); // Start buffering;
529
    /**
530
     * This is called before the edit post link html in the function geodir_detail_page_google_analytics()
531
     *
532
     * @since 1.0.0
533
     */
534
    do_action('geodir_before_google_analytics');
535
    
536
    $refresh_time = get_option('geodir_ga_refresh_time', 5);
537
    /**
538
     * Filter the time interval to check & refresh new users results.
539
     *
540
     * @since 1.5.9
541
     *
542
     * @param int $refresh_time Time interval to check & refresh new users results.
543
     */
544
    $refresh_time = apply_filters('geodir_google_analytics_refresh_time', $refresh_time);
545
    $refresh_time = absint($refresh_time * 1000);
546
    
547
    $hide_refresh = get_option('geodir_ga_auto_refresh');
548
    
549
    $auto_refresh = $hide_refresh && $refresh_time && $refresh_time > 0 ? 1 : 0;
550
    if (is_user_logged_in() &&  (isset($package_info->google_analytics) && $package_info->google_analytics == '1') && (get_current_user_id()==$post->post_author || current_user_can( 'manage_options' )) ) {
551
        $page_url = urlencode($_SERVER['REQUEST_URI']);
552
        ?>
553
        <script type="text/javascript">
554
            var gd_gaTimeOut;
555
            var gd_gaTime = parseInt('<?php echo $refresh_time;?>');
556
            var gd_gaHideRefresh = <?php echo (int)$hide_refresh;?>;
557
            var gd_gaAutoRefresh = <?php echo $auto_refresh;?>;
558
            ga_data1 = false;
559
            ga_data2 = false;
560
            ga_data3 = false;
561
            ga_data4 = false;
562
            ga_data5 = false;
563
            ga_data6 = false;
564
            ga_au = 0;
565
            jQuery(document).ready(function() {              
566
                // Set some global Chart.js defaults.
567
                Chart.defaults.global.animationSteps = 60;
568
                Chart.defaults.global.animationEasing = 'easeInOutQuart';
569
                Chart.defaults.global.responsive = true;
570
                Chart.defaults.global.maintainAspectRatio = false;
571
                
572
                jQuery('.gdga-show-analytics').click(function(e){
573
                    jQuery(this).hide();
574
                    jQuery('.gdga-analytics-box').show();
575
                    gdga_weekVSweek();
576
                    gdga_realtime(true);
577
                });
578
579
                if (gd_gaAutoRefresh !== 1) {
580
                    jQuery('.fa#gdga-loader-icon').click(function(e){
581
                        gdga_refresh();
582
                        clearTimeout(gd_gaTimeOut);
583
                        gdga_realtime();
584
                    });
585
                }
586
            });
587
588
            function gdga_weekVSweek() {
589
                jQuery.ajax({url: "<?php echo admin_url('admin-ajax.php?action=gdga&ga_page='.$page_url.'&ga_type=thisweek'); ?>", success: function(result){
590
                    ga_data1 = jQuery.parseJSON(result);
591
                    if(ga_data1.error){jQuery('#ga_stats').html(result);return;}
592
                    gd_renderWeekOverWeekChart();
593
                }});
594
595
                jQuery.ajax({url: "<?php echo admin_url('admin-ajax.php?action=gdga&ga_page='.$page_url.'&ga_type=lastweek'); ?>", success: function(result){
596
                    ga_data2 = jQuery.parseJSON(result);
597
                    gd_renderWeekOverWeekChart();
598
                }});
599
            }
600
601
            function gdga_yearVSyear() {
602
                jQuery.ajax({url: "<?php echo admin_url('admin-ajax.php?action=gdga&ga_page='.$page_url.'&ga_type=thisyear'); ?>", success: function(result){
603
                    ga_data3 = jQuery.parseJSON(result);
604
                    if(ga_data3.error){jQuery('#ga_stats').html(result);return;}
605
606
                    gd_renderYearOverYearChart()
607
                }});
608
609
                jQuery.ajax({url: "<?php echo admin_url('admin-ajax.php?action=gdga&ga_page='.$page_url.'&ga_type=lastyear'); ?>", success: function(result){
610
                    ga_data4 = jQuery.parseJSON(result);
611
                    gd_renderYearOverYearChart()
612
                }});
613
            }
614
615
            function gdga_country() {
616
                jQuery.ajax({url: "<?php echo admin_url('admin-ajax.php?action=gdga&ga_page='.$page_url.'&ga_type=country'); ?>", success: function(result){
617
                    ga_data5 = jQuery.parseJSON(result);
618
                    if(ga_data5.error){jQuery('#ga_stats').html(result);return;}
619
                    gd_renderTopCountriesChart();
620
                }});
621
            }
622
623
            function gdga_realtime(dom_ready) {
624
                jQuery.ajax({url: "<?php echo admin_url('admin-ajax.php?action=gdga&ga_page='.$page_url.'&ga_type=realtime'); ?>", success: function(result) {
625
                    ga_data6 = jQuery.parseJSON(result);
626
                    if (ga_data6.error) {
627
                        jQuery('#ga_stats').html(result);
628
                        return;
629
                    }
630
                    gd_renderRealTime(dom_ready);
631
                }});
632
            }
633
634
            function gd_renderRealTime(dom_ready) {
635
                if (typeof dom_ready === 'undefined') {
636
                    gdga_refresh(true);
637
                }
638
                ga_au_old = ga_au;
639
640
                ga_au = ga_data6.totalsForAllResults["rt:activeUsers"];
641
                if (ga_au>ga_au_old) {
642
                    jQuery('.gd-ActiveUsers').addClass( "is-increasing");
643
                }
644
645
                if (ga_au<ga_au_old) {
646
                    jQuery('.gd-ActiveUsers').addClass( "is-decreasing");
647
                }
648
                
649
                jQuery('.gd-ActiveUsers-value').html(ga_au);
650
651
                if (gd_gaTime > 0 && gd_gaAutoRefresh === 1) {
652
                    // check for new users every 5 seconds
653
                    gd_gaTimeOut = setTimeout(function() {
654
                        jQuery('.gd-ActiveUsers').removeClass("is-increasing is-decreasing");
655
                        gdga_realtime();
656
                    }, gd_gaTime);
657
                }
658
            }
659
660
            /**
661
             * Draw the a chart.js doughnut chart with data from the specified view that
662
             * compares sessions from mobile, desktop, and tablet over the past two
663
             * weeks.
664
             */
665
            function gd_renderTopCountriesChart() {
666
                if (ga_data5) {
667
                    response = ga_data5;
668
                    ga_data5 = false;
669
                } else {
670
                    return;
671
                }
672
673
                jQuery('#gdga-chart-container').show();
674
                jQuery('#gdga-legend-container').show();
675
                gdga_refresh(true);
676
                jQuery('#gdga-select-analytic').show();
677
                
678
                var data = [];
679
                var colors = ['#4D5360','#949FB1','#D4CCC5','#E2EAE9','#F7464A'];
680
681
                if (response.rows) {
682
                    response.rows.forEach(function (row, i) {
683
                        data.push({
684
                            label: row[0],
685
                            value: +row[1],
686
                            color: colors[i]
687
                        });
688
                    });
689
690
                    new Chart(makeCanvas('gdga-chart-container')).Doughnut(data);
691
                    generateLegend('gdga-legend-container', data);
692
                } else {
693
                    gdga_noResults();
694
                }
695
            }
696
697
            function gdga_noResults() {
698
                jQuery('#gdga-chart-container').html('<?php _e('No results available','geodirectory');?>');
699
                jQuery('#gdga-legend-container').html('');
700
            }
701
702
            /**
703
             * Draw the a chart.js bar chart with data from the specified view that
704
             * overlays session data for the current year over session data for the
705
             * previous year, grouped by month.
706
             */
707
            function gd_renderYearOverYearChart() {
708
                if (ga_data3 && ga_data4) {
709
                    thisYear = ga_data3;
710
                    lastYear = ga_data4;
711
                    ga_data3 = false;
712
                    ga_data4 = false;
713
                } else {
714
                    return;
715
                }
716
717
                jQuery('#gdga-chart-container').show();
718
                jQuery('#gdga-legend-container').show();
719
                gdga_refresh(true);
720
                jQuery('#gdga-select-analytic').show();
721
722
                // Adjust `now` to experiment with different days, for testing only...
723
                var now = moment(); // .subtract(3, 'day');
724
725
                Promise.all([thisYear, lastYear]).then(function(results) {
726
                    var data1 = results[0].rows.map(function(row) { return +row[2]; });
727
                    var data2 = results[1].rows.map(function(row) { return +row[2]; });
728
                    //var labelsN = results[0].rows.map(function(row) { return +row[1]; });
729
730
                    var labels = ['<?php _e('Jan', 'geodirectory');?>',
731
                        '<?php _e('Feb', 'geodirectory');?>',
732
                        '<?php _e('Mar', 'geodirectory');?>',
733
                        '<?php _e('Apr', 'geodirectory');?>',
734
                        '<?php _e('May', 'geodirectory');?>',
735
                        '<?php _e('Jun', 'geodirectory');?>',
736
                        '<?php _e('Jul', 'geodirectory');?>',
737
                        '<?php _e('Aug', 'geodirectory');?>',
738
                        '<?php _e('Sep', 'geodirectory');?>',
739
                        '<?php _e('Oct', 'geodirectory');?>',
740
                        '<?php _e('Nov', 'geodirectory');?>',
741
                        '<?php _e('Dec', 'geodirectory');?>'];
742
743
                    // Ensure the data arrays are at least as long as the labels array.
744
                    // Chart.js bar charts don't (yet) accept sparse datasets.
745
                    for (var i = 0, len = labels.length; i < len; i++) {
746
                        if (data1[i] === undefined) data1[i] = null;
747
                        if (data2[i] === undefined) data2[i] = null;
748
                    }
749
750
                    var data = {
751
                        labels : labels,
752
                        datasets : [
753
                            {
754
                                label: '<?php _e('Last Year', 'geodirectory');?>',
755
                                fillColor : "rgba(220,220,220,0.5)",
756
                                strokeColor : "rgba(220,220,220,1)",
757
                                data : data2
758
                            },
759
                            {
760
                                label: '<?php _e('This Year', 'geodirectory');?>',
761
                                fillColor : "rgba(151,187,205,0.5)",
762
                                strokeColor : "rgba(151,187,205,1)",
763
                                data : data1
764
                            }
765
                        ]
766
                    };
767
768
                    new Chart(makeCanvas('gdga-chart-container')).Bar(data);
769
                    generateLegend('gdga-legend-container', data.datasets);
770
                }).catch(function(err) {
771
                    console.error(err.stack);
772
                })
773
            }
774
775
            /**
776
             * Draw the a chart.js line chart with data from the specified view that
777
             * overlays session data for the current week over session data for the
778
             * previous week.
779
             */
780
            function gd_renderWeekOverWeekChart() {
781
                if(ga_data1 && ga_data2){
782
                    thisWeek = ga_data1;
783
                    lastWeek = ga_data2;
784
                    ga_data1 = false;
785
                    ga_data2 = false;
786
                }else{
787
                    return;
788
                }
789
790
                jQuery('#gdga-chart-container').show();
791
                jQuery('#gdga-legend-container').show();
792
                gdga_refresh(true);
793
                jQuery('#gdga-select-analytic').show();
794
795
                // Adjust `now` to experiment with different days, for testing only...
796
                var now = moment();
797
798
                Promise.all([thisWeek, lastWeek]).then(function(results) {
799
                    var data1 = results[0].rows.map(function(row) { return +row[2]; });
800
                    var data2 = results[1].rows.map(function(row) { return +row[2]; });
801
                    var labels = results[1].rows.map(function(row) { return +row[0]; });
802
803
                    <?php
804
                    // Here we list the shorthand days of the week so it can be used in translation.
805
                    __("Mon",'geodirectory');
806
                    __("Tue",'geodirectory');
807
                    __("Wed",'geodirectory');
808
                    __("Thu",'geodirectory');
809
                    __("Fri",'geodirectory');
810
                    __("Sat",'geodirectory');
811
                    __("Sun",'geodirectory');
812
                    ?>
813
814
                    labels = [
815
                        "<?php _e(date('D', strtotime("+1 day")),'geodirectory'); ?>",
816
                        "<?php _e(date('D', strtotime("+2 day")),'geodirectory'); ?>",
817
                        "<?php _e(date('D', strtotime("+3 day")),'geodirectory'); ?>",
818
                        "<?php _e(date('D', strtotime("+4 day")),'geodirectory'); ?>",
819
                        "<?php _e(date('D', strtotime("+5 day")),'geodirectory'); ?>",
820
                        "<?php _e(date('D', strtotime("+6 day")),'geodirectory'); ?>",
821
                        "<?php _e(date('D', strtotime("+7 day")),'geodirectory'); ?>"
822
                    ];
823
824
                    var data = {
825
                        labels : labels,
826
                        datasets : [
827
                            {
828
                                label: '<?php _e('Last Week', 'geodirectory');?>',
829
                                fillColor : "rgba(220,220,220,0.5)",
830
                                strokeColor : "rgba(220,220,220,1)",
831
                                pointColor : "rgba(220,220,220,1)",
832
                                pointStrokeColor : "#fff",
833
                                data : data2
834
                            },
835
                            {
836
                                label: '<?php _e('This Week', 'geodirectory');?>',
837
                                fillColor : "rgba(151,187,205,0.5)",
838
                                strokeColor : "rgba(151,187,205,1)",
839
                                pointColor : "rgba(151,187,205,1)",
840
                                pointStrokeColor : "#fff",
841
                                data : data1
842
                            }
843
                        ]
844
                    };
845
846
                    new Chart(makeCanvas('gdga-chart-container')).Line(data);
847
                    generateLegend('gdga-legend-container', data.datasets);
848
                });
849
            }
850
851
            /**
852
             * Create a new canvas inside the specified element. Set it to be the width
853
             * and height of its container.
854
             * @param {string} id The id attribute of the element to host the canvas.
855
             * @return {RenderingContext} The 2D canvas context.
856
             */
857
            function makeCanvas(id) {
858
                var container = document.getElementById(id);
859
                var canvas = document.createElement('canvas');
860
                var ctx = canvas.getContext('2d');
861
862
                container.innerHTML = '';
863
                canvas.width = container.offsetWidth;
864
                canvas.height = container.offsetHeight;
865
                container.appendChild(canvas);
866
867
                return ctx;
868
            }
869
870
            /**
871
             * Create a visual legend inside the specified element based off of a
872
             * Chart.js dataset.
873
             * @param {string} id The id attribute of the element to host the legend.
874
             * @param {Array.<Object>} items A list of labels and colors for the legend.
875
             */
876
            function generateLegend(id, items) {
877
                var legend = document.getElementById(id);
878
                legend.innerHTML = items.map(function(item) {
879
                    var color = item.color || item.fillColor;
880
                    var label = item.label;
881
                    return '<li><i style="background:' + color + '"></i>' + label + '</li>';
882
                }).join('');
883
            }
884
885
            function gdga_select_option() {
886
                jQuery('#gdga-select-analytic').hide();
887
                gdga_refresh();
888
889
                gaType = jQuery('#gdga-select-analytic').val();
890
891
                if (gaType=='weeks') {
892
                    gdga_weekVSweek();
893
                } else if (gaType=='years') {
894
                    gdga_yearVSyear();
895
                } else if(gaType=='country') {
896
                    gdga_country();
897
                }
898
            }
899
            
900
            function gdga_refresh(stop) {
901
                if (typeof stop !== 'undefined' && stop) {
902
                    if (gd_gaAutoRefresh === 1 || gd_gaHideRefresh == 1) {
903
                        jQuery('#gdga-loader-icon').hide();
904
                    } else {
905
                        jQuery('#gdga-loader-icon').removeClass('fa-spin');
906
                    }
907
                } else {
908
                    if (gd_gaAutoRefresh === 1 || gd_gaHideRefresh == 1) {
909
                        jQuery('#gdga-loader-icon').show();
910
                    } else {
911
                        if (!jQuery('#gdga-loader-icon').hasClass('fa-spin')) {
912
                            jQuery('#gdga-loader-icon').addClass('fa-spin');
913
                        }
914
                    }
915
                }
916
            }
917
        </script>
918
        <style>
919
            .geodir-details-sidebar-google-analytics {
920
                min-height: 60px;
921
            }
922
            #ga_stats #gd-active-users-container {
923
                float: right;
924
                margin: 0 0 10px;
925
            }
926
927
            #gdga-select-analytic {
928
                clear: both;
929
            }
930
931
            #ga_stats #ga-analytics-title{
932
                float: left;
933
                font-weight: bold;
934
            }
935
936
            #ga_stats #gd-active-users-container{
937
                float: right;
938
            }
939
            .Chartjs {
940
                font-size: .85em
941
            }
942
943
            .Chartjs-figure {
944
                height: 200px;
945
                width: 100%;
946
                display: none;
947
            }
948
949
            .Chartjs-legend {
950
                list-style: none;
951
                margin: 0;
952
                padding: 1em 0 0;
953
                text-align: center;
954
                width: 100%;
955
                display: none;
956
            }
957
958
            .Chartjs-legend>li {
959
                display: inline-block;
960
                padding: .25em .5em
961
            }
962
963
            .Chartjs-legend>li>svg {
964
                display: inline-block;
965
                height: 1em;
966
                margin-right: .5em;
967
                vertical-align: -.1em;
968
                width: 1em
969
            }
970
971
            @media (min-width: 570px) {
972
                .Chartjs-figure {
973
                    margin-right:1.5em
974
                }
975
            }
976
977
            .gd-ActiveUsers {
978
                background: #f3f2f0;
979
                border: 1px solid #d4d2d0;
980
                border-radius: 4px;
981
                font-weight: 300;
982
                padding: .5em 1.5em;
983
                white-space: nowrap
984
            }
985
986
            .gd-ActiveUsers-value {
987
                display: inline-block;
988
                font-weight: 600;
989
                margin-right: -.25em
990
            }
991
992
            .gd-ActiveUsers.is-increasing {
993
                -webkit-animation: increase 3s;
994
                animation: increase 3s
995
            }
996
997
            .gd-ActiveUsers.is-decreasing {
998
                -webkit-animation: decrease 3s;
999
                animation: decrease 3s
1000
            }
1001
1002
            @-webkit-keyframes increase {
1003
                10% {
1004
                    background-color: #eaffea;
1005
                    border-color: hsla(120,100%,25%,.5);
1006
                    color: hsla(120,100%,25%,1)
1007
                }
1008
            }
1009
1010
            @keyframes increase {
1011
                10% {
1012
                    background-color: #eaffea;
1013
                    border-color: hsla(120,100%,25%,.5);
1014
                    color: hsla(120,100%,25%,1)
1015
                }
1016
            }
1017
1018
            @-webkit-keyframes decrease {
1019
                10% {
1020
                    background-color: #ffeaea;
1021
                    border-color: hsla(0,100%,50%,.5);
1022
                    color: red
1023
                }
1024
            }
1025
1026
            @keyframes decrease {
1027
                10% {
1028
                    background-color: #ffeaea;
1029
                    border-color: hsla(0,100%,50%,.5);
1030
                    color: red
1031
                }
1032
            }
1033
            .fa#gdga-loader-icon {
1034
                margin: 0 10px 0 -10px;
1035
                color: #333333;
1036
                cursor: pointer;
1037
                -webkit-animation-duration:1.5s;
1038
                animation-duration:1.5s;
1039
            }
1040
        </style>
1041
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
1042
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
1043
        <button type="button" class="gdga-show-analytics"><?php _e('Show Google Analytics', 'geodirectory');?></button>
1044
        <span id="ga_stats" class="gdga-analytics-box" style="display:none">
1045
            <div id="ga-analytics-title"><?php _e("Analytics", 'geodirectory');?></div>
1046
            <div id="gd-active-users-container">
1047
                <div class="gd-ActiveUsers"><i id="gdga-loader-icon" class="fas fa-refresh fa-spin" title="<?php esc_attr_e("Refresh", 'geodirectory');?>"></i><?php _e("Active Users:", 'geodirectory');?>
1048
                    <b class="gd-ActiveUsers-value">0</b>
1049
                </div>
1050
            </div>
1051
            <select id="gdga-select-analytic" onchange="gdga_select_option();" style="display: none;">
1052
                <option value="weeks"><?php _e("Last Week vs This Week", 'geodirectory');?></option>
1053
                <option value="years"><?php _e("This Year vs Last Year", 'geodirectory');?></option>
1054
                <option value="country"><?php _e("Top Countries", 'geodirectory');?></option>
1055
            </select>
1056
            <div class="Chartjs-figure" id="gdga-chart-container"></div>
1057
            <ol class="Chartjs-legend" id="gdga-legend-container"></ol>
1058
        </span>
1059
1060
    <?php
1061
    }
1062
    /**
1063
     * This is called after the edit post link html in the function geodir_detail_page_google_analytics()
1064
     *
1065
     * @since 1.0.0
1066
     */
1067
    do_action('geodir_after_google_analytics');
1068
    $content_html = ob_get_clean();
1069
    if (trim($content_html) != '')
1070
        $content_html = '<div class="geodir-company_info geodir-details-sidebar-google-analytics">' . $content_html . '</div>';
1071
    if ((int)get_option('geodir_disable_google_analytics_section') != 1) {
1072
        /**
1073
         * Filter the geodir_edit_post_link() function content.
1074
         *
1075
         * @param string $content_html The output html of the geodir_edit_post_link() function.
1076
         */
1077
        echo $content_html = apply_filters('geodir_google_analytic_html', $content_html);
1078
    }
1079
}
1080
1081
/**
1082
 * Output the current post overall review and a small image compatible with google hreviews.
1083
 *
1084
 * @global WP_Post|null $post The current post, if available.
1085
 * @global bool $preview True if the current page is add listing preview page. False if not.
1086
 * @global object $post_images Image objects of current post if available.
1087
 * @since 1.0.0
1088
 * @since 1.6.16 Changes for disable review stars for certain post type.
1089
 * @deprecated 1.6.3 Use geodir_action_details_micordata()
1090
 * @see geodir_action_details_micordata()
1091
 * @package GeoDirectory
1092
 */
1093
function geodir_detail_page_review_rating()
1094
{
1095
    global $post, $preview, $post_images;
1096
    
1097
    if (!empty($post->ID) && geodir_cpt_has_rating_disabled((int)$post->ID)) {
1098
        return;
1099
    }
1100
    ob_start(); // Start  buffering;
1101
    /**
1102
     * This is called before the rating html in the function geodir_detail_page_review_rating().
1103
     *
1104
     * This is called outside the check for an actual rating and the check for preview page.
1105
     *
1106
     * @since 1.0.0
1107
     */
1108
    do_action('geodir_before_detail_page_review_rating');
1109
1110
    $comment_count = geodir_get_review_count_total($post->ID);
1111
    $post_avgratings = geodir_get_post_rating($post->ID);
1112
1113
    if ($post_avgratings != 0 && !$preview) {
1114
        /**
1115
         * This is called before the rating html in the function geodir_detail_page_review_rating().
1116
         *
1117
         * This is called inside the check for an actual rating and the check for preview page.
1118
         *
1119
         * @since 1.0.0
1120
         * @param float $post_avgratings Average rating for the current post.
1121
         * @param int $post->ID Current post ID.
1122
         */
1123
        do_action('geodir_before_review_rating_stars_on_detail', $post_avgratings, $post->ID);
1124
1125
        $html = '<p style=" float:left;">';
1126
        $html .= geodir_get_rating_stars($post_avgratings, $post->ID);
1127
        $html .= '<div class="average-review" itemscope itemtype="http://data-vocabulary.org/Review-aggregate">';
1128
        $post_avgratings = (is_float($post_avgratings) || (strpos($post_avgratings, ".", 1) == 1 && strlen($post_avgratings) > 3)) ? number_format($post_avgratings, 1, '.', '') : $post_avgratings;
1129
       
1130
	   $reviews_text = $comment_count > 1 ? __("reviews", 'geodirectory') : __("review", 'geodirectory');
1131
	   
1132
	   $html .= '<span itemprop="rating" itemscope itemtype="http://data-vocabulary.org/Rating"><span class="rating" itemprop="average" content="' . $post_avgratings . '">' . $post_avgratings . '</span> / <span itemprop="best" content="5">5</span> ' . __("based on", 'geodirectory') . ' </span><span class="count" itemprop="count" content="' . $comment_count . '">' . $comment_count . ' ' . $reviews_text . '</span><br />';
1133
1134
        $html .= '<span class="item">';
1135
        $html .= '<span class="fn" itemprop="itemreviewed">' . $post->post_title . '</span>';
1136
1137
        if ($post_images) {
1138
            foreach ($post_images as $img) {
1139
                $post_img = $img->src;
1140
                break;
1141
            }
1142
        }
1143
1144
        if (isset($post_img) && $post_img) {
1145
            $html .= '<br /><img src="' . $post_img . '" class="photo" alt="' . esc_attr($post->post_title) . '" itemprop="photo" content="' . $post_img . '" class="photo" />';
1146
        }
1147
1148
        $html .= '</span>';
1149
1150
        echo $html .= '</div>';
1151
        /**
1152
         * This is called after the rating html in the function geodir_detail_page_review_rating().
1153
         *
1154
         * This is called inside the check for an actual rating and the check for preview page.
1155
         *
1156
         * @since 1.0.0
1157
         * @param float $post_avgratings Average rating for the current post.
1158
         * @param int $post->ID Current post ID.
1159
         */
1160
        do_action('geodir_after_review_rating_stars_on_detail', $post_avgratings, $post->ID);
1161
    }
1162
    /**
1163
     * This is called before the rating html in the function geodir_detail_page_review_rating().
1164
     *
1165
     * This is called outside the check for an actual rating and the check for preview page.
1166
     *
1167
     * @since 1.0.0
1168
     */
1169
    do_action('geodir_after_detail_page_review_rating');
1170
    $content_html = ob_get_clean();
1171
    if (trim($content_html) != '') {
1172
        $content_html = '<div class="geodir-company_info geodir-details-sidebar-rating">' . $content_html . '</div>';
1173
    }
1174
    if ((int)get_option('geodir_disable_rating_info_section') != 1) {
1175
        /**
1176
         * Filter the geodir_detail_page_review_rating() function content.
1177
         *
1178
         * @since 1.0.0
1179
         * @param string $content_html The output html of the geodir_detail_page_review_rating() function.
1180
         */
1181
        echo $content_html = apply_filters('geodir_detail_page_review_rating_html', $content_html);
1182
    }
1183
}
1184
1185
/**
1186
 * This outputs the info section of the details page.
1187
 *
1188
 * This outputs the info section of the details page which includes all the post custom fields.
1189
 * @since 1.0.0
1190
 * @package GeoDirectory
1191
 */
1192
function geodir_detail_page_more_info()
1193
{
1194
    ob_start(); // Start  buffering;
1195
    /**
1196
     * This is called before the info section html.
1197
     *
1198
     * @since 1.0.0
1199
     */
1200
    do_action('geodir_before_detail_page_more_info');
1201
    if ($geodir_post_detail_fields = geodir_show_listing_info('detail')) {
1202
        echo $geodir_post_detail_fields;
1203
    }
1204
    /**
1205
     * This is called after the info section html.
1206
     *
1207
     * @since 1.0.0
1208
     */
1209
    do_action('geodir_after_detail_page_more_info');
1210
1211
    $content_html = ob_get_clean();
1212
    if (trim($content_html) != '')
1213
        $content_html = '<div class="geodir-company_info geodir-details-sidebar-listing-info">' . $content_html . '</div>';
1214
    if ((int)get_option('geodir_disable_listing_info_section') != 1) {
1215
        /**
1216
         * Filter the output html for function geodir_detail_page_more_info().
1217
         *
1218
         * @since 1.0.0
1219
         * @param string $content_html The output html of the geodir_detail_page_more_info() function.
1220
         */
1221
        echo $content_html = apply_filters('geodir_detail_page_more_info_html', $content_html);
1222
    }
1223
}
1224
1225
1226
/**
1227
 * Outputs translated JS text strings.
1228
 *
1229
 * This function outputs text strings used in JS files as a json array of strings so they can be translated and still be used in JS files.
1230
 *
1231
 * @since 1.0.0
1232
 * @package GeoDirectory
1233
 */
1234
function geodir_localize_all_js_msg()
1235
{// check_ajax_referer function is used to make sure no files are uploaded remotely but it will fail if used between https and non https so we do the check below of the urls
1236
    if (str_replace("https", "http", admin_url('admin-ajax.php')) && !empty($_SERVER['HTTPS'])) {
1237
        $ajax_url = admin_url('admin-ajax.php');
1238
    } elseif (!str_replace("https", "http", admin_url('admin-ajax.php')) && empty($_SERVER['HTTPS'])) {
1239
        $ajax_url = admin_url('admin-ajax.php');
1240
    } elseif (str_replace("https", "http", admin_url('admin-ajax.php')) && empty($_SERVER['HTTPS'])) {
1241
        $ajax_url = str_replace("https", "http", admin_url('admin-ajax.php'));
1242
    } elseif (!str_replace("https", "http", admin_url('admin-ajax.php')) && !empty($_SERVER['HTTPS'])) {
1243
        $ajax_url = str_replace("http", "https", admin_url('admin-ajax.php'));
1244
    }
1245
	
1246
	/**
1247
	 * Filter the allowed image type extensions for post images.
1248
	 *
1249
	 * @since 1.4.7.1
1250
	 * @param string $allowed_img_types The image type extensions array.
1251
	 */
1252
	$allowed_img_types = apply_filters('geodir_allowed_post_image_exts', array('jpg', 'jpeg', 'jpe', 'gif', 'png'));
1253
	
1254
    $default_marker_icon = get_option('geodir_default_marker_icon');
1255
    $default_marker_size = geodir_get_marker_size($default_marker_icon, array('w' => 20, 'h' => 34));
1256
    $default_marker_width = $default_marker_size['w'];
1257
    $default_marker_height = $default_marker_size['h'];
1258
    
1259
    $arr_alert_msg = array(
1260
        'geodir_plugin_url' => geodir_plugin_url(),
1261
        'geodir_admin_ajax_url' => $ajax_url,
1262
        'custom_field_not_blank_var' => __('HTML Variable Name must not be blank', 'geodirectory'),
1263
        'custom_field_not_special_char' => __('Please do not use special character and spaces in HTML Variable Name.', 'geodirectory'),
1264
        'custom_field_unique_name' => __('HTML Variable Name should be a unique name.', 'geodirectory'),
1265
        'custom_field_delete' => __('Are you wish to delete this field?', 'geodirectory'),
1266
        //start not show alert msg
1267
        'tax_meta_class_succ_del_msg' => __('File has been successfully deleted.', 'geodirectory'),
1268
        'tax_meta_class_not_permission_to_del_msg' => __('You do NOT have permission to delete this file.', 'geodirectory'),
1269
        'tax_meta_class_order_save_msg' => __('Order saved!', 'geodirectory'),
1270
        'tax_meta_class_not_permission_record_img_msg' => __('You do not have permission to reorder images.', 'geodirectory'),
1271
        'address_not_found_on_map_msg' => __('Address not found for:', 'geodirectory'),
1272
        // end not show alert msg
1273
        'my_place_listing_del' => __('Are you sure you wish to delete this listing?', 'geodirectory'),
1274
        'my_main_listing_del' => __('Deleting the main listing of a franchise will turn all franchises in regular listings. Are you sure wish to delete this main listing?', 'geodirectory'),
1275
        //start not show alert msg
1276
        'rating_error_msg' => __('Error : please retry', 'geodirectory'),
1277
        'listing_url_prefix_msg' => __('Please enter listing url prefix', 'geodirectory'),
1278
        'invalid_listing_prefix_msg' => __('Invalid character in listing url prefix', 'geodirectory'),
1279
        'location_url_prefix_msg' => __('Please enter location url prefix', 'geodirectory'),
1280
        'invalid_location_prefix_msg' => __('Invalid character in location url prefix', 'geodirectory'),
1281
        'location_and_cat_url_separator_msg' => __('Please enter location and category url separator', 'geodirectory'),
1282
        'invalid_char_and_cat_url_separator_msg' => __('Invalid character in location and category url separator', 'geodirectory'),
1283
        'listing_det_url_separator_msg' => __('Please enter listing detail url separator', 'geodirectory'),
1284
        'invalid_char_listing_det_url_separator_msg' => __('Invalid character in listing detail url separator', 'geodirectory'),
1285
        'loading_listing_error_favorite' => __('Error loading listing.', 'geodirectory'),
1286
        'geodir_field_id_required' => __('This field is required.', 'geodirectory'),
1287
        'geodir_valid_email_address_msg' => __('Please enter valid email address.', 'geodirectory'),
1288
        'geodir_default_marker_icon' => $default_marker_icon,
1289
        'geodir_default_marker_w' => $default_marker_width,
1290
        'geodir_default_marker_h' => $default_marker_height,
1291
        'geodir_latitude_error_msg' => GEODIR_LATITUDE_ERROR_MSG,
1292
        'geodir_longgitude_error_msg' => GEODIR_LOGNGITUDE_ERROR_MSG,
1293
        'geodir_default_rating_star_icon' => get_option('geodir_default_rating_star_icon'),
1294
        'gd_cmt_btn_post_reply' => __('Post Reply', 'geodirectory'),
1295
        'gd_cmt_btn_reply_text' => __('Reply text', 'geodirectory'),
1296
        'gd_cmt_btn_post_review' => __('Post Review', 'geodirectory'),
1297
        'gd_cmt_btn_review_text' => __('Review text', 'geodirectory'),
1298
        'gd_cmt_err_no_rating' => __("Please select star rating, you can't leave a review without stars.", 'geodirectory'),
1299
        'err_empty_review' => __('Please type a review.', 'geodirectory'),
1300
        'err_empty_reply' => __('Please type a reply.', 'geodirectory'),
1301
        /* on/off dragging for phone devices */
1302
        'geodir_onoff_dragging' => get_option('geodir_map_onoff_dragging') ? true : false,
1303
        'geodir_is_mobile' => wp_is_mobile() ? true : false,
1304
        'geodir_on_dragging_text' => __('Enable Dragging', 'geodirectory'),
1305
        'geodir_off_dragging_text' => __('Disable Dragging', 'geodirectory'),
1306
        'geodir_err_max_file_size' => __('File size error : You tried to upload a file over %s', 'geodirectory'),
1307
        'geodir_err_file_upload_limit' => __('You have reached your upload limit of %s files.', 'geodirectory'),
1308
        'geodir_err_pkg_upload_limit' => __('You may only upload %s files with this package, please try again.', 'geodirectory'),
1309
        'geodir_action_remove' => __('Remove', 'geodirectory'),
1310
		'geodir_txt_all_files' => __('Allowed files', 'geodirectory'),
1311
		'geodir_err_file_type' => __('File type error. Allowed file types: %s', 'geodirectory'),
1312
		'gd_allowed_img_types' => !empty($allowed_img_types) ? implode(',', $allowed_img_types) : '',
1313
		'geodir_txt_form_wait' => __('Wait...', 'geodirectory'),
1314
		'geodir_txt_form_searching' => __('Searching...', 'geodirectory'),
1315
		'fa_rating' => (int)get_option('geodir_reviewrating_enable_font_awesome') == 1 ? 1 : '',
1316
		'reviewrating' => defined('GEODIRREVIEWRATING_VERSION') ? 1 : '',
1317
        'multirating' => defined('GEODIRREVIEWRATING_VERSION') && get_option('geodir_reviewrating_enable_rating') ? true : false,
1318
        'geodir_map_name' => geodir_map_name(),
1319
        'osmStart' => __('Start', 'geodirectory'),
1320
        'osmVia' => __('Via {viaNumber}', 'geodirectory'),
1321
        'osmEnd' => __('Enter Your Location', 'geodirectory'),
1322
        'ga_delete_check' => __('Do you wish to Deauthorize and break Analytics?', 'geodirectory'),
1323
        'geoMyLocation' => __('My Location', 'geodirectory'),
1324
        'geoErrUNKNOWN_ERROR' => addslashes(__('Unable to find your location', 'geodirectory')),
1325
        'geoErrPERMISSION_DENINED' => addslashes(__('Permission denied in finding your location', 'geodirectory')),
1326
        'geoErrPOSITION_UNAVAILABLE' => addslashes(__('Your location is currently unknown', 'geodirectory')),
1327
        'geoErrBREAK' => addslashes(__('Attempt to find location took too long', 'geodirectory')),
1328
        'geoErrDEFAULT' => addslashes(__('Location detection not supported in browser', 'geodirectory')),
1329
		'mapLanguage' => geodir_get_map_default_language(),
1330
		'lightBox_txtImage' => addslashes(__('Image', 'geodirectory')),
1331
		'lightBox_txtOf' => addslashes(__('of', 'geodirectory')),
1332
    );
1333
1334
    /**
1335
     * Filters the translated JS strings from function geodir_localize_all_js_msg().
1336
     *
1337
     * With this filter you can add, remove or change translated JS strings.
1338
     * You should add your own translations to this if you are building an addon rather than adding another script block.
1339
     *
1340
     * @since 1.0.0
1341
     */
1342
    $arr_alert_msg = apply_filters('geodir_all_js_msg', $arr_alert_msg);
1343
1344
    foreach ($arr_alert_msg as $key => $value) {
1345
        if (!is_scalar($value))
1346
            continue;
1347
        $arr_alert_msg[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
1348
    }
1349
1350
    $script = "var geodir_all_js_msg = " . json_encode($arr_alert_msg) . ';';
1351
    echo '<script>';
1352
    echo $script;
1353
    echo '</script>';
1354
}
1355
1356
add_action('admin_bar_menu', 'geodir_admin_bar_site_menu', 31);
1357
/**
1358
 * Add GeoDirectory link to the WordPress admin bar.
1359
 *
1360
 * This function adds a link to the GeoDirectory backend to the WP admin bar via a hook.
1361
 *    add_action('admin_bar_menu', 'geodir_admin_bar_site_menu', 31);
1362
 *
1363
 * @since 1.0.0
1364
 * @package GeoDirectory
1365
 * @param object $wp_admin_bar The admin bar object.
1366
 */
1367
function geodir_admin_bar_site_menu($wp_admin_bar)
1368
{
1369
    if (get_option("geodir_installed")) {
1370
        if (current_user_can('manage_options')) {
1371
            $wp_admin_bar->add_menu(array('parent' => 'appearance', 'id' => 'geodirectory', 'title' => __('GeoDirectory', 'geodirectory'), 'href' => admin_url('?page=geodirectory')));
1372
        }
1373
    }
1374
}
1375
1376
add_action('geodir_before_listing', 'geodir_display_sort_options'); /*function in custom_functions.php*/
1377
1378
add_filter('geodir_posts_order_by_sort', 'geodir_posts_order_by_custom_sort', 0, 3);
1379
1380
add_filter('geodir_advance_custom_fields_heading', 'geodir_advance_customfields_heading', 0, 2);
1381
1382
1383
add_action('switch_theme', 'geodir_store_sidebars');
1384
1385
/**
1386
 * Stores the GeoDirectory widget locations in the theme widget areas.
1387
 *
1388
 * This function loops through the GeoDirectory widgets and saves their locations in the widget areas to an option
1389
 * so they can be restored later. This is called via hook.
1390
 *    add_action('switch_theme', 'geodir_store_sidebars');
1391
 *
1392
 * @since 1.0.0
1393
 * @package GeoDirectory
1394
 * @global array $geodir_sidebars List of geodirectory sidebars.
1395
 * @global array $sidebars_widgets List of geodirectory sidebar widgets.
1396
 */
1397
function geodir_store_sidebars()
1398
{
1399
    global $geodir_sidebars;
1400
    global $sidebars_widgets;
1401
1402
    if (!is_array($sidebars_widgets))
1403
        $sidebars_widgets = wp_get_sidebars_widgets();
1404
    $geodir_old_sidebars = array();
1405
1406
    if (is_array($geodir_sidebars)) {
1407
        foreach ($geodir_sidebars as $val) {
1408
            if (is_array($sidebars_widgets)) {
1409
                if (array_key_exists($val, $sidebars_widgets))
1410
                    $geodir_old_sidebars[$val] = $sidebars_widgets[$val];
1411
                else
1412
                    $geodir_old_sidebars[$val] = array();
1413
            }
1414
        }
1415
    }
1416
    update_option('geodir_sidebars', $geodir_old_sidebars);
1417
    geodir_option_version_backup('geodir_sidebars');
1418
1419
}
1420
1421
add_action('after_switch_theme', 'geodir_restore_sidebars');
1422
/**
1423
 * Restore sidebars.
1424
 *
1425
 * @since 1.0.0
1426
 * @package GeoDirectory
1427
 * @global array $sidebars_widgets List of geodirectory sidebar widgets.
1428
 */
1429
function geodir_restore_sidebars()
1430
{
1431
    global $sidebars_widgets;
1432
1433
    if (!is_array($sidebars_widgets))
1434
        $sidebars_widgets = wp_get_sidebars_widgets();
1435
1436
    if (is_array($sidebars_widgets)) {
1437
        $geodir_old_sidebars = get_option('geodir_sidebars');
1438
        if (is_array($geodir_old_sidebars)) {
1439
            foreach ($geodir_old_sidebars as $key => $val) {
1440
                if(0 === strpos($key, 'geodir_'))// if gd widget
1441
                {
1442
                    $sidebars_widgets[$key] = $geodir_old_sidebars[$key];
1443
                }
1444
1445
1446
            }
1447
        }
1448
1449
    }
1450
1451
    update_option('sidebars_widgets', $sidebars_widgets);
1452
    update_option('geodir_sidebars', '');
1453
}
1454
1455
add_action('geodir_after_listing_post_gridview', 'geodir_after_listing_post_gridview');
1456
/**
1457
 * Set gridview columns value.
1458
 *
1459
 * @since 1.0.0
1460
 * @package GeoDirectory
1461
 * @global string $gridview_columns The girdview style of the listings.
1462
 */
1463
function geodir_after_listing_post_gridview()
1464
{
1465
    global $gridview_columns;
1466
1467
    $gridview_columns = '';
1468
1469
}
1470
1471
/*
1472
add_filter('script_loader_src' , 'geodir_script_loader_src');
1473
1474
function geodir_script_loader_src($url)
1475
{
1476
	if (strstr($url, "maps") !== false) {
1477
       echo  $url = str_replace("&amp;", "&", $url); // or $url = $original_url
1478
    }
1479
	return $url ;
1480
}*/
1481
1482
add_filter('clean_url', 'so_handle_038', 99, 3);
1483
/**
1484
 * Clean url.
1485
 *
1486
 * @since 1.0.0
1487
 * @package GeoDirectory
1488
 * @param string $url Url.
1489 1
 * @param string $original_url Original url.
1490
 * @param string $_context Context.
1491
 * @return string Modified url.
1492
 */
1493 1
function so_handle_038($url, $original_url, $_context)
1494
{
1495
    if (strstr($url, "maps.google.com/maps/api/js") !== false) {
1496
        $url = str_replace("&#038;", "&amp;", $url); // or $url = $original_url
1497
    }
1498
1499
    return $url;
1500
}
1501
1502
1503
add_action('geodir_after_main_form_fields', 'geodir_after_main_form_fields', 1);
1504
/**
1505
 * Add html after main form fields.
1506
 *
1507
 * @since 1.0.0
1508
 * @package GeoDirectory
1509
 * @global object $post The current post object.
1510
 * @global object $gd_session GeoDirectory Session object.
1511
 */
1512
function geodir_after_main_form_fields() {
1513
	global $gd_session;
1514
	
1515
    if (get_option('geodir_accept_term_condition')) {
1516
        global $post;
1517
        $term_condition = '';
1518
        if (isset($_REQUEST['backandedit'])) {
1519
            $post = (object)$gd_session->get('listing');
1520
            $term_condition = isset($post->geodir_accept_term_condition) ? $post->geodir_accept_term_condition : '';
1521
        }
1522
1523
        ?>
1524
        <div id="geodir_accept_term_condition_row" class="required_field geodir_form_row clearfix">
1525
            <label>&nbsp;</label>
1526
1527
            <div class="geodir_taxonomy_field" style="float:left; width:70%;">
1528
				<span style="display:block"> 
1529
				<input class="main_list_selecter" type="checkbox" <?php if ($term_condition == '1') {
1530
                    echo 'checked="checked"';
1531
                } ?> field_type="checkbox" name="geodir_accept_term_condition" id="geodir_accept_term_condition"
1532
                       class="geodir_textfield" value="1"
1533
                       style="display:inline-block"/><a href="<?php $terms_page = get_option('geodir_term_condition_page'); if($terms_page){ echo get_permalink($terms_page);}?>" target="_blank"><?php _e('Please accept our terms and conditions', 'geodirectory'); ?></a>
1534
				</span>
1535
            </div>
1536
            <span class="geodir_message_error"><?php if (isset($required_msg)) {
1537
                    _e($required_msg, 'geodirectory');
1538
                } ?></span>
1539
        </div>
1540
    <?php
1541
1542
    }
1543
}
1544
1545
1546
/* ------------------------------START CODE FOR HIDE/DISPLAY TABS */
1547
1548
add_filter('geodir_detail_page_tab_is_display', 'geodir_detail_page_tab_is_display', 0, 2);
1549
1550
/**
1551
 * Check whether custom field should be displayed or not, on the details page tab.
1552
 *
1553
 * @since 1.0.0
1554
 * @package GeoDirectory
1555
 * @global object $post The current post object.
1556
 * @global object $post_images Image objects of current post if available.
1557
 * @global string $video The video embed content.
1558
 * @global string $special_offers Special offers content.
1559
 * @global string $related_listing Related listing html.
1560
 * @global string $geodir_post_detail_fields Detail field html.
1561
 * @param bool $is_display Old display value.
1562
 * @param string $tab Tab type.
1563
 * @return bool New display value. If display returns true.
1564
 */
1565
function geodir_detail_page_tab_is_display($is_display, $tab)
1566
{
1567
    global $post, $post_images, $video, $special_offers, $related_listing, $geodir_post_detail_fields;
1568
1569
    if ($tab == 'post_profile') {
1570
        /** This action is documented in geodirectory_template_actions.php */
1571
        $desc_limit = apply_filters('geodir_description_field_desc_limit', '');
1572
        
1573
        if (!($desc_limit === '' || (int)$desc_limit > 0)) {
1574
            $is_display = false;
1575
        }
1576
    }
1577
    
1578
    if ($tab == 'post_info')
1579
        $is_display = (!empty($geodir_post_detail_fields)) ? true : false;
1580
    
1581
    if ($tab == 'post_images')
1582
        $is_display = (!empty($post_images)) ? true : false;
1583
1584
    if ($tab == 'post_video')
1585
        $is_display = (!empty($video)) ? true : false;
1586
1587
    if ($tab == 'special_offers')
1588
        $is_display = (!empty($special_offers)) ? true : false;
1589
1590
    if ($tab == 'reviews')
1591
        $is_display = (geodir_is_page('detail')) ? true : false;
1592
1593
    if ($tab == 'related_listing') {
1594
       $message = __('No listings found which match your selection.', 'geodirectory');
1595
       
1596
       /** This action is documented in geodirectory-functions/template_functions.php */
1597
       $message = apply_filters('geodir_message_listing_not_found', $message, 'listing-listview', false);
1598
       
1599
       $is_display = ((strpos($related_listing, $message) !== false || $related_listing == '' || !geodir_is_page('detail'))) ? false : true;
1600
    }
1601
1602
    return $is_display;
1603
}
1604
1605
1606
add_action('wp', 'geodir_changes_in_custom_fields_table');
1607
add_action('wp_admin', 'geodir_changes_in_custom_fields_table');
1608
1609
/**
1610
 * Geodirectory updated custom field table(add field and change show in sidebar value in db).
1611
 *
1612
 * @since 1.0.0
1613
 * @package GeoDirectory
1614
 * @global object $wpdb WordPress Database object.
1615
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1616
 */
1617
function geodir_changes_in_custom_fields_table() {
1618
    global $wpdb, $plugin_prefix;
1619
	
1620
	// Remove unused virtual page
1621
	$listings_page_id = (int)get_option('geodir_listing_page');
1622
	if ($listings_page_id) {
1623
		$wpdb->query($wpdb->prepare("DELETE FROM " . $wpdb->posts . " WHERE ID=%d AND post_name = %s AND post_type=%s", array($listings_page_id, 'listings', 'page')));
1624
        delete_option('geodir_listing_page');
1625
	}
1626
1627
    if (!get_option('geodir_changes_in_custom_fields_table')) {
1628
        $wpdb->query(
1629
            $wpdb->prepare(
1630
                "UPDATE " . GEODIR_CUSTOM_FIELDS_TABLE . " SET is_default=%s, is_admin=%s WHERE is_default=%s",
1631
                array('1', '1', 'admin')
1632
            )
1633
        );
1634
1635
1636
        /* --- terms meta value set --- */
1637
1638
        update_option('geodir_default_marker_icon', geodir_plugin_url() . '/geodirectory-functions/map-functions/icons/pin.png');
1639
1640
        $options_data = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "options WHERE option_name LIKE %s", array('%tax_meta_%')));
1641
1642
        if (!empty($options_data)) {
1643
1644
            foreach ($options_data as $optobj) {
1645
1646
                $option_val = str_replace('tax_meta_', '', $optobj->option_name);
1647
1648
                $taxonomies_data = $wpdb->get_results($wpdb->prepare("SELECT taxonomy FROM " . $wpdb->prefix . "term_taxonomy WHERE taxonomy LIKE %s AND term_id=%d", array('%category%', $option_val)));
1649
1650
                if (!empty($taxonomies_data)) {
1651
1652
                    foreach ($taxonomies_data as $taxobj) {
1653
1654
                        $taxObject = get_taxonomy($taxobj->taxonomy);
1655
                        $post_type = $taxObject->object_type[0];
1656
1657
                        $opt_value = 'tax_meta_' . $post_type . '_' . $option_val;
1658
1659
                        $duplicate_data = $wpdb->get_var($wpdb->prepare("SELECT option_id FROM " . $wpdb->prefix . "options WHERE option_name=%s", array('tax_meta_' . $option_val)));
1660
1661
                        if ($duplicate_data) {
1662
1663
                            $wpdb->query($wpdb->prepare("UPDATE " . $wpdb->prefix . "options SET	option_name=%s WHERE option_id=%d", array($opt_value, $optobj->option_id)));
1664
1665
                        } else {
1666
1667
                            $wpdb->query($wpdb->prepare("INSERT INTO " . $wpdb->prefix . "options (option_name,option_value,autoload) VALUES (%s, %s, %s)", array($opt_value, $optobj->option_value, $optobj->autoload)));
1668
1669
                        }
1670
1671
                    }
1672
1673
                }
1674
1675
            }
1676
        }
1677
1678
        update_option('geodir_changes_in_custom_fields_table', '1');
1679
1680
    }
1681
1682
}
1683
1684
1685
add_filter('geodir_location_slug_check', 'geodir_location_slug_check');
1686
/**
1687
 * Check location slug.
1688
 *
1689
 * @since 1.0.0
1690
 * @package GeoDirectory
1691
 * @global object $wpdb WordPress Database object.
1692
 * @global string $table_prefix WordPress Database Table prefix.
1693
 * @param string $slug Term slug.
1694
 * @return string Modified term slug.
1695
 */
1696
function geodir_location_slug_check($slug)
1697
{
1698
1699
    global $wpdb, $table_prefix;
1700
1701
    $slug_exists = $wpdb->get_var($wpdb->prepare("SELECT slug FROM " . $table_prefix . "terms WHERE slug=%s", array($slug)));
1702
1703
    if ($slug_exists) {
1704
1705
        $suffix = 1;
1706
        do {
1707
            $alt_location_name = _truncate_post_slug($slug, 200 - (strlen($suffix) + 1)) . "-$suffix";
1708
            $location_slug_check = $wpdb->get_var($wpdb->prepare("SELECT slug FROM " . $table_prefix . "terms WHERE slug=%s", array($alt_location_name)));
1709
            $suffix++;
1710
        } while ($location_slug_check && $suffix < 100);
1711
1712
        $slug = $alt_location_name;
1713
1714
    }
1715
1716
    return $slug;
1717
1718
}
1719
1720
1721
add_action('edited_term', 'geodir_update_term_slug', '1', 3);
1722
add_action('create_term', 'geodir_update_term_slug', '1', 3);
1723
add_action( 'delete_term', 'geodir_on_delete_term', 1, 5 );
1724
1725
/**
1726
 * Update term slug.
1727
 *
1728
 * @since 1.0.0
1729
 * @since 1.5.3 Modified to update tag in detail table when tag updated.
1730
 * @package GeoDirectory
1731
 * @global object $wpdb WordPress Database object.
1732
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1733
 * @global string $table_prefix WordPress Database Table prefix.
1734
 * @param int|string $term_id The term ID.
1735 3
 * @param int $tt_id term Taxonomy ID.
1736
 * @param string $taxonomy Taxonomy slug.
1737 3
 */
1738
function geodir_update_term_slug($term_id, $tt_id, $taxonomy)
1739 3
{
1740
1741
    global $wpdb, $plugin_prefix, $table_prefix;
1742
1743
    $tern_data = get_term_by('id', $term_id, $taxonomy);
1744
1745
    $slug = $tern_data->slug;
1746
1747
    /**
1748
     * Filter if a term slug exists.
1749
     *
1750 3
     * @since 1.0.0
1751
     * @package GeoDirectory
1752 3
     * @param bool $bool Default: false.
1753
     * @param string $slug The term slug.
1754
     * @param int $term_id The term ID.
1755
     */
1756
    $slug_exists = apply_filters('geodir_term_slug_is_exists', false, $slug, $term_id);
1757
1758
    if ($slug_exists) {
1759
1760
        $suffix = 1;
1761
        do {
1762
            $new_slug = _truncate_post_slug($slug, 200 - (strlen($suffix) + 1)) . "-$suffix";
1763
1764
            /** This action is documented in geodirectory_hooks_actions.php */
1765
            $term_slug_check = apply_filters('geodir_term_slug_is_exists', false, $new_slug, $term_id);
1766
1767
            $suffix++;
1768
        } while ($term_slug_check && $suffix < 100);
1769
1770
        $slug = $new_slug;
1771
1772
        //wp_update_term( $term_id, $taxonomy, array('slug' => $slug) );
1773 3
1774 3
        $wpdb->query($wpdb->prepare("UPDATE " . $table_prefix . "terms SET slug=%s WHERE term_id=%d", array($slug, $term_id)));
1775
1776 3
    }
1777 3
	
1778 3
	// Update tag in detail table.
1779
	$taxonomy_obj = get_taxonomy($taxonomy);
1780 3
	$post_type = !empty($taxonomy_obj) ? $taxonomy_obj->object_type[0] : NULL;
1781
	
1782
	$post_types = geodir_get_posttypes();
1783
	if ($post_type && in_array($post_type, $post_types) && $post_type . '_tags' == $taxonomy) {		
1784
		$posts_obj = $wpdb->get_results($wpdb->prepare("SELECT object_id FROM " . $wpdb->term_relationships . " WHERE term_taxonomy_id = %d", array($tt_id)));
1785
		
1786
		if (!empty($posts_obj)) {
1787
			foreach ($posts_obj as $post_obj) {
1788
				$post_id = $post_obj->object_id;
1789
				
1790
				$raw_tags = wp_get_object_terms($post_id, $post_type . '_tags', array('fields' => 'names'));
1791 3
				$post_tags = !empty($raw_tags) ? implode(',', $raw_tags) : '';
1792 3
				
1793
				$listing_table = $plugin_prefix . $post_type . '_detail';
1794
				$wpdb->query($wpdb->prepare("UPDATE " . $listing_table . " SET post_tags=%s WHERE post_id =%d", array($post_tags, $post_id)));
1795
			}
1796
		}
1797
	}
1798
}
1799
1800
1801
add_filter('geodir_term_slug_is_exists', 'geodir_term_slug_is_exists', 0, 3); //in core plugin
1802
/**
1803
 * Check whether a term slug exists or not.
1804
 *
1805
 * @since 1.0.0
1806
 * @package GeoDirectory
1807
 * @global object $wpdb WordPress Database object.
1808
 * @global string $table_prefix WordPress Database Table prefix.
1809
 * @param bool $slug_exists Default: false.
1810
 * @param string $slug Term slug.
1811 3
 * @param int $term_id The term ID.
1812
 * @return bool true when exists. false when not exists.
1813 3
 */
1814
function geodir_term_slug_is_exists($slug_exists, $slug, $term_id)
1815 3
{
1816 3
1817 3
    global $wpdb, $table_prefix;
1818
1819 3
    $default_location = geodir_get_default_location();
1820 3
1821
    $country_slug = $default_location->country_slug;
1822 3
    $region_slug = $default_location->region_slug;
1823 3
    $city_slug = $default_location->city_slug;
1824
1825 3
    if ($country_slug == $slug || $region_slug == $slug || $city_slug == $slug)
1826
        return $slug_exists = true;
1827
1828
    if ($wpdb->get_var($wpdb->prepare("SELECT slug FROM " . $table_prefix . "terms WHERE slug=%s AND term_id != %d", array($slug, $term_id))))
1829
        return $slug_exists = true;
1830
1831
    return $slug_exists;
1832
}
1833
1834
1835
1836
add_filter('pre_get_document_title', 'geodir_custom_page_title', 100);
1837
add_filter('wp_title', 'geodir_custom_page_title', 100, 2);
1838
/**
1839
 * Set custom page title.
1840
 *
1841
 * @since 1.0.0
1842
 * @since 1.6.18 Option added to disable overwrite by Yoast SEO titles & metas on GD pages.
1843
 * @package GeoDirectory
1844
 * @global object $wp WordPress object.
1845
 * @param string $title Old title.
1846
 * @param string $sep Title separator.
1847
 * @return string Modified title.
1848
 */
1849
function geodir_custom_page_title($title = '', $sep = '')
1850
{
1851
    global $wp;
1852
    if ((class_exists('WPSEO_Frontend') || class_exists('All_in_One_SEO_Pack')) && !geodir_disable_yoast_seo_metas()) {
1853
        return $title;
1854
    }
1855
1856
    if ($sep == '') {
1857
        /**
1858
         * Filter the page title separator.
1859
         *
1860
         * @since 1.0.0
1861
         * @package GeoDirectory
1862
         * @param string $sep The separator, default: `|`.
1863
         */
1864
        $sep = apply_filters('geodir_page_title_separator', '|');
1865
    }
1866
1867
1868
    $gd_page = '';
1869
    if(geodir_is_page('home')){
1870
        $gd_page = 'home';
1871
        $title = (get_option('geodir_meta_title_homepage')) ? get_option('geodir_meta_title_homepage') : $title;
1872
    }
1873
    elseif(geodir_is_page('detail')){
1874
        $gd_page = 'detail';
1875
        $title = (get_option('geodir_meta_title_detail')) ? get_option('geodir_meta_title_detail') : $title;
1876
    }
1877
    elseif(geodir_is_page('pt')){
1878
        $gd_page = 'pt';
1879
        $title = (get_option('geodir_meta_title_pt')) ? get_option('geodir_meta_title_pt') : $title;
1880
    }
1881
    elseif(geodir_is_page('listing')){
1882
        $gd_page = 'listing';
1883
        $title = (get_option('geodir_meta_title_listing')) ? get_option('geodir_meta_title_listing') : $title;
1884
    }
1885
    elseif(geodir_is_page('location')){
1886
        $gd_page = 'location';
1887
        $title = (get_option('geodir_meta_title_location')) ? get_option('geodir_meta_title_location') : $title;
1888
    }
1889
    elseif(geodir_is_page('search')){
1890
        $gd_page = 'search';
1891
        $title = (get_option('geodir_meta_title_search')) ? get_option('geodir_meta_title_search') : $title;
1892
    }
1893
    elseif(geodir_is_page('add-listing')){
1894
        $gd_page = 'add-listing';
1895
        $title = (get_option('geodir_meta_title_add-listing')) ? get_option('geodir_meta_title_add-listing') : $title;
1896
    }
1897
    elseif(geodir_is_page('author')){
1898
        $gd_page = 'author';
1899
        $title = (get_option('geodir_meta_title_author')) ? get_option('geodir_meta_title_author') : $title;
1900
    }
1901
    elseif(geodir_is_page('login')){
1902
        $gd_page = 'login';
1903
        $title = (get_option('geodir_meta_title_login')) ? get_option('geodir_meta_title_login') : $title;
1904
    }
1905
    elseif(geodir_is_page('listing-success')){
1906
        $gd_page = 'listing-success';
1907
        $title = (get_option('geodir_meta_title_listing-success')) ? get_option('geodir_meta_title_listing-success') : $title;
1908
    }
1909
1910
1911
    /**
1912
     * Filter page meta title to replace variables.
1913
     *
1914
     * @since 1.5.4
1915
     * @param string $title The page title including variables.
1916
     * @param string $gd_page The GeoDirectory page type if any.
1917
     * @param string $sep The title separator symbol.
1918
     */
1919
    return apply_filters('geodir_seo_meta_title', __($title, 'geodirectory'), $gd_page, $sep);
1920
1921
}
1922
1923
1924
//add_action('init', 'geodir_set_post_attachment'); // we need to make a tool somewhere to run this function maybe via ajax or something in batch form, it is crashing servers with lots of listings
1925
1926
/**
1927
 * set attachments for all geodir posts.
1928
 *
1929
 * @since 1.0.0
1930
 * @package GeoDirectory
1931
 */
1932
function geodir_set_post_attachment()
1933
{
1934
1935
    if (!get_option('geodir_set_post_attachments')) {
1936
1937
        require_once(ABSPATH . 'wp-admin/includes/image.php');
1938
        require_once(ABSPATH . 'wp-admin/includes/file.php');
1939
1940
        $all_postypes = geodir_get_posttypes();
1941
1942
        foreach($all_postypes as $post_type){
1943
            $args = array(
1944
                'posts_per_page' => -1,
1945
                'post_type' => $post_type,
1946
                'post_status' => 'publish');
1947
1948
            $posts_array = get_posts($args);
1949
1950
            if (!empty($posts_array)) {
1951
1952
                foreach ($posts_array as $post) {
1953
1954
                    geodir_set_wp_featured_image($post->ID);
1955
1956
                }
1957
1958
            }
1959
        }
1960
1961
1962
        update_option('geodir_set_post_attachments', '1');
1963
1964
    }
1965
1966
}
1967
1968
1969
/*   --------- geodir remove url seperator ------- */
1970
1971
add_action('init', 'geodir_remove_url_seperator');
1972
/**
1973
 * Remove url separator.
1974
 *
1975
 * @since 1.0.0
1976
 * @package GeoDirectory
1977
 */
1978
function geodir_remove_url_seperator()
1979
{
1980
1981
    if (!get_option('geodir_remove_url_seperator')) {
1982
1983
        if (get_option('geodir_listingurl_separator'))
1984
            delete_option('geodir_listingurl_separator');
1985
1986
        if (get_option('geodir_detailurl_separator'))
1987
            delete_option('geodir_detailurl_separator');
1988
1989
        flush_rewrite_rules(false);
1990
1991
        update_option('geodir_remove_url_seperator', '1');
1992
1993
    }
1994
1995
}
1996
1997
add_filter('geodir_permalink_settings', 'geodir_remove_url_seperator_form_permalink_settings', 0, 1);
1998
1999
/**
2000
 * Remove url separator from permalink settings.
2001
 *
2002
 * @since 1.0.0
2003
 * @package GeoDirectory
2004
 * @param array $permalink_arr The permalink settings array ( Geodirectory -> Permalinks ).
2005
 * @return array Modified permalink array.
2006
 */
2007
function geodir_remove_url_seperator_form_permalink_settings($permalink_arr)
2008
{
2009
    foreach ($permalink_arr as $key => $value) {
2010
2011
        if ($value['id'] == 'geodir_listingurl_separator' || $value['id'] == 'geodir_detailurl_separator')
2012
            unset($permalink_arr[$key]);
2013
2014
    }
2015
2016
    return $permalink_arr;
2017
2018
}
2019
2020
if (!is_admin()) {
2021
    add_filter('posts_results', 'geodir_set_status_draft_to_publish_for_own_post');
2022
}
2023
/**
2024
 * Set status from draft to publish.
2025
 *
2026
 * @since 1.0.0
2027
 * @package GeoDirectory
2028 1
 * @global object $wp WordPress object.
2029
 * @param object $post Post object.
2030 1
 * @return object Modified post object.
2031
 */
2032
function geodir_set_status_draft_to_publish_for_own_post($post)
2033
{
2034
    $user_id = get_current_user_id();
2035
2036
    if(!$user_id){return $post;}
2037
2038
    $gd_post_types = geodir_get_posttypes();
2039
2040
    if (!empty($post) && $post[0]->post_author == $user_id && in_array($post[0]->post_type, $gd_post_types) && !isset($_REQUEST['fl_builder'])) {
2041
        $post[0]->post_status = 'publish';
2042
    }
2043
    return $post;
2044
}
2045
2046
2047
add_filter('geodir_detail_page_tab_list_extend', 'geodir_detail_page_tab_headings_change');
2048
/**
2049
 * Detail Page Tab Headings Change.
2050
 *
2051
 * @since 1.0.0
2052
 * @package GeoDirectory
2053
 * @global object $wpdb WordPress Database object.
2054
 * @param array $tabs_arr {
2055
 *    Attributes of the Tabs array.
2056
 *
2057
 *    @type array $post_profile {
2058
 *        Attributes of post_profile.
2059
 *
2060
 *        @type string $heading_text    Tab Heading. Default "Profile".
2061
 *        @type bool   $is_active_tab   Is this tab active? Default true.
2062
 *        @type bool   $is_display      Display this tab? Default true.
2063
 *        @type string $tab_content     Tab content. Default "".
2064
 *
2065
 *    }
2066
 *    @type array $post_info {
2067
 *        Attributes of post_info.
2068
 *
2069
 *        @type string $heading_text    Tab Heading. Default "More Info".
2070
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2071
 *        @type bool   $is_display      Display this tab? Default false.
2072
 *        @type string $tab_content     Tab content. Default "".
2073
 *
2074
 *    }
2075
 *    @type array $post_images {
2076
 *        Attributes of post_images.
2077
 *
2078
 *        @type string $heading_text    Tab Heading. Default "Photo".
2079
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2080
 *        @type bool   $is_display      Display this tab? Default true.
2081
 *        @type string $tab_content     Tab content. Default "".
2082
 *
2083
 *    }
2084
 *    @type array $post_video {
2085
 *        Attributes of post_video.
2086
 *
2087
 *        @type string $heading_text    Tab Heading. Default "Video".
2088
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2089
 *        @type bool   $is_display      Display this tab? Default false.
2090
 *        @type string $tab_content     Tab content. Default "".
2091
 *
2092
 *    }
2093
 *    @type array $special_offers {
2094
 *        Attributes of special_offers.
2095
 *
2096
 *        @type string $heading_text    Tab Heading. Default "Special Offers".
2097
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2098
 *        @type bool   $is_display      Display this tab? Default false.
2099
 *        @type string $tab_content     Tab content. Default "".
2100
 *
2101
 *    }
2102
 *    @type array $post_map {
2103
 *        Attributes of post_map.
2104
 *
2105
 *        @type string $heading_text    Tab Heading. Default "Map".
2106
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2107
 *        @type bool   $is_display      Display this tab? Default true.
2108
 *        @type string $tab_content     Tab content. Default "".
2109
 *
2110
 *    }
2111
 *    @type array $reviews {
2112
 *        Attributes of reviews.
2113
 *
2114
 *        @type string $heading_text    Tab Heading. Default "Reviews".
2115
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2116
 *        @type bool   $is_display      Display this tab? Default true.
2117
 *        @type string $tab_content     Tab content. Default "review display".
2118
 *
2119
 *    }
2120
 *    @type array $related_listing {
2121
 *        Attributes of related_listing.
2122
 *
2123
 *        @type string $heading_text    Tab Heading. Default "Related Listing".
2124
 *        @type bool   $is_active_tab   Is this tab active? Default false.
2125
 *        @type bool   $is_display      Display this tab? Default true.
2126
 *        @type string $tab_content     Tab content. Default "".
2127
 *
2128
 *    }
2129
 *
2130
 * }
2131
 * @return array Modified tabs array.
2132
 */
2133
function geodir_detail_page_tab_headings_change($tabs_arr)
2134
{
2135
    global $wpdb;
2136
2137
    $post_type = geodir_get_current_posttype();
2138
2139
    $all_postypes = geodir_get_posttypes();
2140
2141
    if (!empty($tabs_arr) && $post_type != '' && in_array($post_type, $all_postypes)) {
2142
2143
        if (array_key_exists('post_video', $tabs_arr)) {
2144
2145
            $field_title = $wpdb->get_var($wpdb->prepare("select site_title from " . GEODIR_CUSTOM_FIELDS_TABLE . " where htmlvar_name = %s and post_type = %s ", array('geodir_video', $post_type)));
2146
2147
            if (isset($tabs_arr['post_video']['heading_text']) && $field_title != '')
2148
                $tabs_arr['post_video']['heading_text'] = $field_title;
2149
        }
2150
2151
        if (array_key_exists('special_offers', $tabs_arr)) {
2152
2153
            $field_title = $wpdb->get_var($wpdb->prepare("select site_title from " . GEODIR_CUSTOM_FIELDS_TABLE . " where htmlvar_name = %s and post_type = %s ", array('geodir_special_offers', $post_type)));
2154
2155
            if (isset($tabs_arr['special_offers']['heading_text']) && $field_title != '')
2156
                $tabs_arr['special_offers']['heading_text'] = $field_title;
2157
        }
2158
2159
    }
2160
2161
    return $tabs_arr;
2162
2163
}
2164
2165
add_action('init', 'geodir_remove_template_redirect_actions', 100);
2166
/**
2167
 * Remove template redirect options.
2168
 *
2169
 * @since 1.0.0
2170
 * @package GeoDirectory
2171
 */
2172
function geodir_remove_template_redirect_actions()
2173
{
2174
    if (geodir_is_page('login')){
2175
        remove_all_actions('template_redirect');
2176
        remove_action('init', 'avia_modify_front', 10);
2177
    }
2178
}
2179
2180
2181
2182
/* ---------- temp function to delete media post */
2183
2184
add_action('delete_attachment', 'geodirectory_before_featured_image_delete');
2185
2186
/**
2187
 * temp function to delete media post.
2188
 *
2189
 * @since 1.0.0
2190
 * @package GeoDirectory
2191
 * @global object $wpdb WordPress Database object.
2192
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2193
 * @param int $attachment_id Attachment ID.
2194
 * @return bool|void Returns false on failure.
2195
 */
2196
function geodirectory_before_featured_image_delete($attachment_id)
2197
{
2198
2199
    global $wpdb, $plugin_prefix;
2200
2201
    $post_id = get_post_field('post_parent', $attachment_id);
2202
2203
    $attachment_url = wp_get_attachment_url($attachment_id);
2204
2205
    if ($post_id > 0 && (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete')) {
2206
2207
        $post_type = get_post_type($post_id);
2208
2209
        $all_postypes = geodir_get_posttypes();
2210
2211
        if (!in_array($post_type, $all_postypes) || !is_admin())
2212
            return false;
2213
2214
        $uploads = wp_upload_dir();
2215
2216
        $split_img_path = explode($uploads['baseurl'], $attachment_url);
2217
2218
        $split_img_file_path = isset($split_img_path[1]) ? $split_img_path[1] : '';
2219
2220
        $wpdb->query(
2221
            $wpdb->prepare("DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id = %d AND file=%s ",
2222
                array($post_id, $split_img_file_path)
2223
            )
2224
        );
2225
2226
        $attachment_data = $wpdb->get_row(
2227
            $wpdb->prepare("SELECT ID, MIN(`menu_order`) FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id=%d",
2228
                array($post_id)
2229
            )
2230
        );
2231
2232
        if (!empty($attachment_data)) {
2233
            $wpdb->query("UPDATE " . GEODIR_ATTACHMENT_TABLE . " SET menu_order=1 WHERE ID=" . $attachment_data->ID);
2234
        }
2235
2236
2237
        $table_name = $plugin_prefix . $post_type . '_detail';
2238
2239
        $wpdb->query("UPDATE " . $table_name . " SET featured_image='' WHERE post_id =" . $post_id);
2240
2241
        geodir_set_wp_featured_image($post_id);
2242
2243
    }
2244
2245
}
2246
2247
2248
//add_action('wp', 'geodir_temp_set_post_attachment'); //WTF 
2249
2250
/**
2251
 * temp function to set post attachment.
2252
 *
2253
 * @since 1.0.0
2254
 * @package GeoDirectory
2255
 * @global object $wpdb WordPress Database object.
2256
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2257
 */
2258
function geodir_temp_set_post_attachment()
2259
{
2260
2261
    global $wpdb, $plugin_prefix;
2262
2263
    $all_postypes = geodir_get_posttypes();
2264
2265
    foreach ($all_postypes as $posttype) {
2266
2267
        $tablename = $plugin_prefix . $posttype . '_detail';
2268
2269
        $get_post_data = $wpdb->get_results("SELECT post_id FROM " . $tablename);
2270
2271
        if (!empty($get_post_data)) {
2272
2273
            foreach ($get_post_data as $data) {
2274
2275
                $post_id = $data->post_id;
2276
2277
                $attachment_data = $wpdb->get_results("SELECT * FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id =" . $post_id . " AND file!=''");
2278
2279
                if (!empty($attachment_data)) {
2280
2281
                    foreach ($attachment_data as $attach) {
2282
2283
                        $file_info = pathinfo($attach->file);
2284
2285
                        $sub_dir = '';
2286
                        if ($file_info['dirname'] != '.' && $file_info['dirname'] != '..')
2287
                            $sub_dir = stripslashes_deep($file_info['dirname']);
2288
2289
                        $uploads = wp_upload_dir(trim($sub_dir, '/')); // Array of key => value pairs
2290
                        $uploads_path = $uploads['basedir'];
2291
2292
                        $file_name = $file_info['basename'];
2293
2294
                        $img_arr['path'] = $uploads_path . $sub_dir . '/' . $file_name;
2295
2296
                        if (!file_exists($img_arr['path'])) {
2297
2298
                            $wpdb->query("DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE ID=" . $attach->ID);
2299
2300
                        }
2301
2302
                    }
2303
2304
                    $attachment_data = $wpdb->get_row("SELECT ID, MIN(`menu_order`) FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id=" . $post_id . " GROUP BY post_id");
2305
2306
                    if (!empty($attachment_data)) {
2307
2308
                        if ($attachment_data->ID)
2309
                            $wpdb->query("UPDATE " . GEODIR_ATTACHMENT_TABLE . " SET menu_order=1 WHERE ID=" . $attachment_data->ID);
2310
2311
                    } else {
2312
2313
                        if (has_post_thumbnail($post_id)) {
2314
2315
                            $post_thumbnail_id = get_post_thumbnail_id($post_id);
2316
2317
                            wp_delete_attachment($post_thumbnail_id);
2318
2319
                        }
2320
2321
                    }
2322
2323
                    $wpdb->query("UPDATE " . $tablename . " SET featured_image='' WHERE post_id =" . $post_id);
2324
2325
                    geodir_set_wp_featured_image($post_id);
2326
2327
                }
2328
2329
            }
2330
2331
        }
2332
2333
    }
2334
2335
}
2336
2337
2338
/* -------- GEODIR FUNCTION TO UPDATE geodir_default_rating_star_icon ------ */
2339
2340
add_action('init', 'geodir_default_rating_star_icon');
2341
2342
/**
2343
 * Update default rating star icon.
2344
 *
2345
 * @since 1.0.0
2346
 * @package GeoDirectory
2347
 */
2348
function geodir_default_rating_star_icon()
2349
{
2350
2351
    if (!get_option('geodir_default_rating_star_icon')) {
2352
        update_option('geodir_default_rating_star_icon', geodir_plugin_url() . '/geodirectory-assets/images/stars.png');
2353
    }
2354
2355
}
2356
2357
2358
/* ------- GET CURRENT USER POST LISTING -------*/
2359
/**
2360
 * Get user's post listing count.
2361
 *
2362
 * @since 1.0.0
2363
 * @package GeoDirectory
2364
 * @global object $wpdb WordPress Database object.
2365
 * @global object $current_user Current user object.
2366
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2367
 * @return array User listing count for each post type.
2368
 */
2369
function geodir_user_post_listing_count($user_id = 0)
2370
{
2371
    global $wpdb, $plugin_prefix, $current_user;
2372
    if(!$user_id){
2373
        $user_id = $current_user->ID;
2374
    }
2375
2376
    $all_posts = get_option('geodir_listing_link_user_dashboard');
2377
2378
    $user_listing = array();
2379
    if ($user_id && is_array($all_posts) && !empty($all_posts)) {
2380
        foreach ($all_posts as $ptype) {
2381
            $total_posts = $wpdb->get_var("SELECT count( ID ) FROM " . $wpdb->prefix . "posts WHERE post_author=" . $user_id . " AND post_type='" . $ptype . "' AND ( post_status = 'publish' OR post_status = 'draft' OR post_status = 'private' OR post_status = 'pending' )");
2382
2383
            if ($total_posts > 0) {
2384
                $user_listing[$ptype] = $total_posts;
2385
            }
2386
        }
2387
    }
2388
2389
    return $user_listing;
2390
}
2391
2392
2393
2394
2395
add_filter('geodir_detail_page_tab_list_extend', 'geodir_detail_page_custom_field_tab');
2396
/**
2397
 * Details page tab custom fields.
2398
 *
2399
 * @since 1.0.0
2400
 * @since 1.5.7 Custom fields option values added to db translation.
2401
 *              Changes to display url fields title.
2402
 * @package GeoDirectory
2403
 * @global object $post The current post object.
2404
 * @param array $tabs_arr Tabs array {@see geodir_detail_page_tab_headings_change()}.
2405
 * @return array Modified tabs array.
2406
 */
2407
function geodir_detail_page_custom_field_tab($tabs_arr)
2408
{
2409
    global $post;
2410
2411
    $post_type = geodir_get_current_posttype();
2412
    $all_postypes = geodir_get_posttypes();
2413
2414
    if (!empty($tabs_arr) && $post_type != '' && in_array($post_type, $all_postypes) && (geodir_is_page('detail') || geodir_is_page('preview'))) {
2415
        $package_info = array();
2416
        $package_info = geodir_post_package_info($package_info, $post);
2417
        $post_package_id = !empty($package_info->pid) ? $package_info->pid : '';
2418
        $fields_location = 'owntab';
2419
2420
        $custom_fields = geodir_post_custom_fields($post_package_id, 'all', $post_type, $fields_location);
2421
        //remove video and special offers if it is already set to show
2422
        if(isset($tabs_arr['post_video']['is_display']) && $tabs_arr['post_video']['is_display']){
2423
            $unset_video = true;
2424
        }
2425
2426
        if(isset($tabs_arr['special_offers']['is_display']) && $tabs_arr['special_offers']['is_display']){
2427
            $unset_special_offers = true;
2428
        }
2429
        if(isset($unset_video) || isset($unset_special_offers) && !empty($custom_fields)){
2430
            foreach($custom_fields as $key => $custom_field){
2431
                if($custom_field['name']=='geodir_video' && isset($unset_video)){
2432
                    unset($custom_fields[$key]);
2433
                }
2434
                if($custom_field['name']=='geodir_special_offers' && isset($unset_special_offers)){
2435
                    unset($custom_fields[$key]);
2436
                }
2437
            }
2438
        }
2439
2440
2441
        if (!empty($custom_fields)) {
2442
            $parse_custom_fields = array();
2443
            foreach ($custom_fields as $field) {
2444
                $field = stripslashes_deep($field); // strip slashes
2445
                $type = $field;
2446
                $field_name = $field['htmlvar_name'];
2447
                if (empty($geodir_post_info) && geodir_is_page('preview') && $field_name != '' && !isset($post->{$field_name}) && isset($_REQUEST[$field_name])) {
2448
                    $post->{$field_name} = $_REQUEST[$field_name];
2449
                }
2450
2451
                if (isset($field['show_in']) && strpos($field['show_in'], '[owntab]') !== false  && ((isset($post->{$field_name}) && $post->{$field_name} != '') || $field['type'] == 'fieldset' || $field['type'] == 'address') && in_array($field['type'], array('text', 'datepicker', 'textarea', 'time', 'phone', 'email', 'select', 'multiselect', 'url', 'html', 'fieldset', 'radio', 'checkbox', 'file','address','taxonomy'))) {
2452
                    if ($type['type'] == 'datepicker' && ($post->{$type['htmlvar_name']} == '' || $post->{$type['htmlvar_name']} == '0000-00-00')) {
2453
                        continue;
2454
                    }
2455
2456
                    $parse_custom_fields[] = $field;
2457
                }
2458
            }
2459
            $custom_fields = $parse_custom_fields;
2460
        }
2461
        //print_r($custom_fields);
2462
        if (!empty($custom_fields)) {
2463
2464
            global $field_set_start;
2465
2466
            $post = stripslashes_deep($post); // strip slashes
2467
            
2468
            $field_set_start = 0;
2469
            $fieldset_count = 0;
2470
            $fieldset = '';
2471
            $total_fields = count($custom_fields);
2472
            $count_field = 0;
2473
            $fieldset_arr = array();
2474
            $i = 0;
2475
            $geodir_post_info = isset($post->ID) && !empty($post->ID) ? geodir_get_post_info($post->ID) : NULL;
2476
2477
            foreach ($custom_fields as $field) {
2478
                $count_field++;
2479
                $field_name = $field['htmlvar_name'];
2480
                if (empty($geodir_post_info) && geodir_is_page('preview') && $field_name != '' && !isset($post->{$field_name}) && isset($_REQUEST[$field_name])) {
2481
                    $post->{$field_name} = $_REQUEST[$field_name];
2482
                }
2483
2484
                if (isset($field['show_in']) && strpos($field['show_in'], '[owntab]') !== false && ((isset($post->{$field_name}) && $post->{$field_name} != '') || $field['type'] == 'fieldset' || $field['type'] == 'address') && in_array($field['type'], array('text', 'datepicker', 'textarea', 'time', 'phone', 'email', 'select', 'multiselect', 'url', 'html', 'fieldset', 'radio', 'checkbox', 'file','address','taxonomy'))) {
2485
                    $label = $field['site_title'] != '' ? $field['site_title'] : $field['admin_title'];
2486
                    $site_title = trim($field['site_title']);
2487
                    $type = $field;
2488
                    $variables_array = array();
2489
2490
                    if ($type['type'] == 'datepicker' && ($post->{$type['htmlvar_name']} == '' || $post->{$type['htmlvar_name']} == '0000-00-00')) {
2491
                        continue;
2492
                    }
2493
2494
                    if ($type['type'] != 'fieldset') {
2495
                        $i++;
2496
                        $variables_array['post_id'] = $post->ID;
2497
                        $variables_array['label'] = __($type['site_title'], 'geodirectory');
2498
                        $variables_array['value'] = isset($post->{$type['htmlvar_name']}) ? $post->{$type['htmlvar_name']} : '';
2499
2500
                    }else{
2501
                        $i = 0;
2502
                        $fieldset_count++;
2503
                        $field_set_start = 1;
2504
                        $fieldset_arr[$fieldset_count]['htmlvar_name'] = 'gd_tab_' . $fieldset_count;
2505
                        $fieldset_arr[$fieldset_count]['label'] = $label;
2506
                    }
2507
2508
2509
                    if(isset($type['extra_fields'])){$extra_fields= $type['extra_fields'];}
2510
                    $type = stripslashes_deep($type); // strip slashes
2511
                    if(isset($type['extra_fields'])){$type['extra_fields'] = $extra_fields;}
2512
                    $html = '';
2513
                    $html_var = isset($type['htmlvar_name']) ? $type['htmlvar_name'] : '';
2514
                    if($html_var=='post'){$html_var='post_address';}
2515
                    $field_icon = geodir_field_icon_proccess($type);
2516
                    $filed_type = $type['type'];
2517
2518
                    /**
2519
                     * Filter the output for custom fields.
2520
                     *
2521
                     * Here we can remove or add new functions depending on the field type.
2522
                     *
2523
                     * @param string $html The html to be filtered (blank).
2524
                     * @param string $fields_location The location the field is to be show.
2525
                     * @param array $type The array of field values.
2526
                     */
2527
                    $html = apply_filters("geodir_custom_field_output_{$filed_type}",$html,$fields_location,$type);
2528
2529
2530
                    /**
2531
                     * Filter custom field output in tab.
2532
                     *
2533
                     * @since 1.5.6
2534
                     *
2535
                     * @param string $html_var The HTML variable name for the field.
2536
                     * @param string $html Custom field unfiltered HTML.
2537
                     * @param array $variables_array Custom field variables array.
2538
                     */
2539
                    $html = apply_filters("geodir_tab_show_{$html_var}", $html, $variables_array);
2540
2541
                    $fieldset_html = '';
2542
                    if ($field_set_start == 1) {
2543
                        $add_html = false;
2544
                        if ($type['type'] == 'fieldset' && $fieldset_count > 1) {
2545
                            if ($fieldset != '') {
2546
                                $add_html = true;
2547
                                $label = $fieldset_arr[$fieldset_count - 1]['label'];
2548
                                $htmlvar_name = $fieldset_arr[$fieldset_count - 1]['htmlvar_name'];
2549
                            }
2550
                            $fieldset_html = $fieldset;
2551
                            $fieldset = '';
2552
                        } else {
2553
                            $fieldset .= $html;
2554
                            if ($total_fields == $count_field && $fieldset != '') {
2555
                                $add_html = true;
2556
                                $label = $fieldset_arr[$fieldset_count]['label'];
2557
                                $htmlvar_name = $fieldset_arr[$fieldset_count]['htmlvar_name'];
2558
                                $fieldset_html = $fieldset;
2559
                            }
2560
                        }
2561
2562
                        if ($add_html) {
2563
                            $tabs_arr[$htmlvar_name] = array(
2564
                                'heading_text' => __($label, 'geodirectory'),
2565
                                'is_active_tab' => false,
2566
                                /**
2567
                                 * Filter if a custom field should be displayed on the details page tab.
2568
                                 *
2569
                                 * @since 1.0.0
2570
                                 * @param string $htmlvar_name The field HTML var name.
2571
                                 */
2572
                                'is_display' => apply_filters('geodir_detail_page_tab_is_display', true, $htmlvar_name),
2573
                                'tab_content' => '<div class="geodir-company_info field-group xxx">' . $fieldset_html . '</div>'
2574
                            );
2575
                        }
2576
                    } else {
2577
                        if ($html != '') {
2578
                            $tabs_arr[$html_var] = array(
2579
                                'heading_text' => __($label, 'geodirectory'),
2580
                                'is_active_tab' => false,
2581
                                /** This action is documented in geodirectory_hooks_actions.php */
2582
                                'is_display' => apply_filters('geodir_detail_page_tab_is_display', true, $field['htmlvar_name']),
2583
                                'tab_content' => $html
2584
                            );
2585
                        }
2586
                    }
2587
                }
2588
            }
2589
        }
2590
    }
2591
    return $tabs_arr;
2592
}
2593
2594
/* display add listing page for wpml */
2595
add_filter('option_geodir_add_listing_page', 'get_page_id_geodir_add_listing_page', 10, 2);
2596
2597
/*
2598
 * hook action for post updated
2599
 */
2600
add_action('post_updated', 'geodir_function_post_updated', 16, 3);
2601
2602
2603
add_action('geodir_after_edit_post_link_on_listing', 'geodir_add_post_status_author_page', 11);
2604
2605
/**
2606
 * Adds post status on author page when the author is current user.
2607
 *
2608
 * @since 1.0.0
2609
 * @package GeoDirectory
2610
 * @global object $wpdb WordPress Database object.
2611
 * @global object $post The current post object.
2612
 */
2613
function geodir_add_post_status_author_page()
2614
{
2615
    global $wpdb, $post;
2616
2617
    $html = '';
2618
    if (get_current_user_id()) {
2619
2620
        $is_author_page = apply_filters('geodir_post_status_is_author_page', geodir_is_page('author'));
2621
        if ($is_author_page && !empty($post) && isset($post->post_author) && $post->post_author == get_current_user_id()) {
2622
2623
            // we need to query real status direct as we dynamically change the status for author on author page so even non author status can view them.
2624
            $real_status = $wpdb->get_var("SELECT post_status from $wpdb->posts WHERE ID=$post->ID");
2625
            $status = "<strong>(";
2626
            $status_icon = '<i class="fas fa-play"></i>';
2627
            if ($real_status == 'publish') {
2628
                $status .= __('Published', 'geodirectory');
2629
            }elseif ($real_status == 'pending') {
2630
                $status .= __('Awaiting Review', 'geodirectory');
2631
            } else {
2632
                $status .= __('Not published', 'geodirectory');
2633
                $status_icon = '<i class="fas fa-pause"></i>';
2634
            }
2635
            $status .= ")</strong>";
2636
2637
            $html = '<span class="geodir-post-status">' . $status_icon . ' <font class="geodir-status-label">' . __('Status: ', 'geodirectory') . '</font>' . $status . '</span>';
2638
        }
2639
    }
2640
2641
    if ($html != '') {
2642
        /**
2643
         * Filter the post status text on the author page.
2644
         *
2645
         * @since 1.0.0
2646
         * @param string $html The HTML of the status.
2647
         */
2648
        echo apply_filters('geodir_filter_status_text_on_author_page', $html);
2649
    }
2650
2651
2652
}
2653
2654
add_action('init', 'geodir_init_no_rating', 100);
2655
/**
2656
 * remove rating stars fields if disabled.
2657
 *
2658
 * @since 1.0.0
2659
 * @since 1.6.16 Changes for disable review stars for certain post type.
2660
 * @package GeoDirectory
2661
 */
2662
function geodir_init_no_rating() {
2663
    if (geodir_rating_disabled_post_types()) {
2664
        add_filter('geodir_get_sort_options', 'geodir_no_rating_get_sort_options', 100, 2);
2665
    }
2666
}
2667
2668
/**
2669
 * Skip overall rating sort option when rating disabled.
2670
 *
2671
 * @since 1.0.0
2672
 * @since 1.6.16 Changes for disable review stars for certain post type.
2673
 * @package GeoDirectory
2674
 * @param array $options Sort options array.
2675
 * @param string $post_type The post type.
2676
 * @return array Modified sort options array.
2677
 */
2678
function geodir_no_rating_get_sort_options($options, $post_type = '') {
2679
    if (!empty($post_type) && geodir_cpt_has_rating_disabled($post_type)) {
2680
        $new_options = array();
2681
        
2682
        if (!empty($options)) {
2683
            foreach ($options as $option) {
2684
                if (is_object($option) && isset($option->htmlvar_name) && $option->htmlvar_name == 'overall_rating') {
2685
                    continue;
2686
                }
2687
                $new_options[] = $option;
2688
            }
2689
2690
            $options = $new_options;
2691
        }
2692
    }
2693
2694
    return $options;
2695
}
2696
2697
/**
2698
 * Add body class for current active map.
2699
 *
2700
 * @since 1.6.16
2701
 * @package GeoDirectory
2702
 * @param array $classes The class array of the HTML element.
2703
 * @return array Modified class array.
2704
 */
2705
function geodir_body_class_active_map($classes = array()) {
2706
    $classes[] = 'gd-map-' . geodir_map_name();
2707
2708
    return $classes;
2709
}
2710
add_filter('body_class', 'geodir_body_class_active_map', 100);
2711
2712
/**
2713
 * Add body class for current active map.
2714
 *
2715
 * @since 1.0.0
2716
 * @package GeoDirectory
2717
 * @param string $class The class of the HTML element.
2718
 * @return string Modified class string.
2719
 */
2720
function geodir_admin_body_class_active_map($class = '') {    
2721
    $class .= ' gd-map-' . geodir_map_name();
2722
2723
    return $class;
2724
}
2725
add_filter('admin_body_class', 'geodir_admin_body_class_active_map', 100);
2726
2727
add_filter('geodir_load_db_language', 'geodir_load_custom_field_translation');
2728
2729
add_filter('geodir_load_db_language', 'geodir_load_cpt_text_translation');
2730
2731
/**
2732
 * Get the geodirectory notification subject & content texts for translation.
2733
 *
2734
 * @since 1.5.7
2735
 * @package GeoDirectory
2736
 *
2737
 * @param  array $translation_texts Array of text strings.
2738
 * @return array Translation texts.
2739
 */
2740
function geodir_load_gd_options_text_translation($translation_texts = array()) {
2741
    $translation_texts = !empty( $translation_texts ) && is_array( $translation_texts ) ? $translation_texts : array();
2742
2743
    $gd_options = array('geodir_post_submited_success_email_subject_admin', 'geodir_post_submited_success_email_content_admin', 'geodir_post_submited_success_email_subject', 'geodir_post_submited_success_email_content', 'geodir_forgot_password_subject', 'geodir_forgot_password_content', 'geodir_registration_success_email_subject', 'geodir_registration_success_email_content', 'geodir_post_published_email_subject', 'geodir_post_published_email_content', 'geodir_email_enquiry_subject', 'geodir_email_enquiry_content', 'geodir_post_added_success_msg_content', 'geodir_post_edited_email_subject_admin', 'geodir_post_edited_email_content_admin');
2744
2745
    /**
2746
     * Filters the geodirectory option names that requires to add for translation.
2747
     *
2748
     * @since 1.5.7
2749
     * @package GeoDirectory
2750
     *
2751
     * @param  array $gd_options Array of option names.
2752
     */
2753
    $gd_options = apply_filters('geodir_gd_options_for_translation', $gd_options);
2754
    $gd_options = array_unique($gd_options);
2755
2756
    if (!empty($gd_options)) {
2757
        foreach ($gd_options as $gd_option) {
2758
            if ($gd_option != '' && $option_value = get_option($gd_option)) {
2759
                $option_value = is_string($option_value) ? stripslashes_deep($option_value) : '';
2760
                
2761
                if ($option_value != '' && !in_array($option_value, $translation_texts)) {
2762
                    $translation_texts[] = stripslashes_deep($option_value);
2763
                }
2764
            }
2765
        }
2766
    }
2767
2768
    $translation_texts = !empty($translation_texts) ? array_unique($translation_texts) : $translation_texts;
2769
2770
    return $translation_texts;
2771
}
2772
2773
add_filter('geodir_load_db_language', 'geodir_load_gd_options_text_translation');
2774
add_filter('geodir_action_get_request_info', 'geodir_attach_parent_categories', 0, 1);
2775
add_filter('geodir_show_listing_post_excerpt', 'geodir_show_listing_post_excerpt', 10, 3);
2776
add_filter('gd_rating_form_html', 'geodir_font_awesome_rating_form_html', 10, 2);
2777
add_filter('geodir_get_rating_stars_html', 'geodir_font_awesome_rating_stars_html', 10, 3);
2778
add_action('wp_head', 'geodir_font_awesome_rating_css');
2779
add_action('admin_head', 'geodir_font_awesome_rating_css');
2780
add_action('wp_insert_post', 'geodir_on_wp_insert_post', 10, 3);
2781
2782
add_filter('get_comments_link', 'gd_get_comments_link', 10, 2);
2783
function gd_get_comments_link($comments_link, $post_id) {
2784
    $post_type = get_post_type($post_id);
2785
2786
    $all_postypes = geodir_get_posttypes();
2787
    if (in_array($post_type, $all_postypes)) {
2788
        $comments_link = str_replace('#comments', '#reviews', $comments_link);
2789
        $comments_link = str_replace('#respond', '#reviews', $comments_link);
2790
    }
2791
2792
    return $comments_link;
2793
}
2794
2795
2796
/**
2797
 * Add a class to theme menus so we can adjust the z-index.
2798
 *
2799
 * We add a class and adjust the z-index so menus don't hide behind maps and menus on second lines
2800
 * don't overlap submenus of first line menus.
2801
 *
2802
 * @package GeoDirectory
2803
 * @since 1.6.3
2804
 * @param array $args The array of menu arguments.
2805
 * @return array The modified arguments.
2806
 */
2807
function geodir_add_nav_menu_class( $args )
2808
{
2809
2810
        if(isset($args['menu_class'])){
2811
            $args['menu_class'] = $args['menu_class']." gd-menu-z";
2812
        }
2813
    
2814
    return $args;
2815
}
2816
2817
add_filter( 'wp_nav_menu_args', 'geodir_add_nav_menu_class' );
2818
2819
/**
2820
 * Filters WordPress locale ID.
2821
 *
2822
 * Load current WPML language when editing the GD CPT.
2823
 *
2824
 * @since 1.6.16
2825
 * @package GeoDirectory
2826
 *
2827
 * @param string $locale The locale ID.
2828
 * @return string Filtered locale ID.
2829
 */
2830
function geodir_wpml_filter_locale($locale) {
2831
    global $sitepress;
2832
    
2833
    $post_type = !empty($_REQUEST['post_type']) ? $_REQUEST['post_type'] : (!empty($_REQUEST['post']) ? get_post_type($_REQUEST['post']) : '');
2834
    
2835
    if (!empty($sitepress) && $sitepress->is_post_edit_screen() && $post_type && in_array($post_type, geodir_get_posttypes()) && $current_lang = $sitepress->get_current_language()) {
2836
        $locale = $sitepress->get_locale($current_lang);
2837
    }
2838
    
2839
    return $locale;
2840
}
2841
2842
/**
2843
 * Set WordPress locale filter.
2844
 *
2845
 * @since 1.6.16
2846
 * @package GeoDirectory
2847
 */
2848
function geodir_wpml_set_filter() {
2849
    if (geodir_is_wpml()) {
2850
        global $sitepress;
2851
        
2852
        if ($sitepress->get_setting('sync_comments_on_duplicates')) {
2853
            add_action('comment_post', 'gepdir_wpml_sync_comment', 100, 1);
2854
        }
2855
        
2856
        add_action('geodir_after_save_listing', 'geodir_wpml_duplicate_listing', 100, 2);
2857
        add_action( 'geodir_edit_post_link_html', 'geodir_wpml_frontend_duplicate_listing', 0, 1 );
2858
		add_action( 'geodir_after_search_form', 'geodir_wpml_add_language_input_field' );
2859
        if (is_admin()) {
2860
            add_filter( 'geodir_design_settings', 'geodir_wpml_duplicate_settings', 10, 1 );
2861
        }
2862
    }
2863
}
2864
add_filter('plugins_loaded', 'geodir_wpml_set_filter');
2865
2866
/**
2867
 * Filters the WPML language switcher urls for GeoDirectory pages.
2868
 *
2869
 * @since 1.6.16
2870
 *
2871
 * @param array    $languages WPML active languages.
2872
 * @return array Filtered languages.
2873
 */
2874
function geodir_wpml_filter_ls_languages($languages) {    
2875
    if (geodir_is_geodir_page()) {        
2876
        $keep_vars = array();
2877
        
2878
        if (geodir_is_page('add-listing')) {
2879
            $keep_vars = array('listing_type', 'package_id');
2880
        } else if (geodir_is_page('search')) {
2881
            $keep_vars = array('geodir_search', 'stype', 'snear', 'set_location_type', 'set_location_val', 'sgeo_lat', 'sgeo_lon');
2882
        } else if (geodir_is_page('author')) {
2883
            $keep_vars = array('geodir_dashbord', 'stype', 'list');
2884
        } else if (geodir_is_page('login')) {
2885
            $keep_vars = array('forgot', 'signup');
2886
        }        
2887
        
2888
        if (!empty($keep_vars)) {
2889
            foreach ( $languages as $code => $url) {
2890
                $filter_url = $url['url'];
2891
                
2892
                foreach ($keep_vars as $var) {
2893
                    if (isset($_GET[$var]) && !is_array($_GET[$var])) {
2894
                        $filter_url = remove_query_arg(array($var), $filter_url);
2895
                        $filter_url = add_query_arg(array($var => $_GET[$var]), $filter_url);
2896
                    }
2897
                }
2898
                
2899
                if ($filter_url != $url['url']) {
2900
                    $languages[$code]['url'] = $filter_url;
2901
                }
2902
            }
2903
        }
2904
    }
2905
2906
    return $languages;
2907
}
2908
add_filter( 'icl_ls_languages', 'geodir_wpml_filter_ls_languages', 11, 1 );
2909
2910
/**
2911
 * Remove Yoast SEO hook if disabled on GD pages.
2912
 *
2913
 * @since 1.6.18
2914
 *
2915
 */
2916
function geodir_remove_yoast_seo_metas(){
2917
    if ( class_exists( 'WPSEO_Frontend' ) && geodir_is_geodir_page() && geodir_disable_yoast_seo_metas() ) {
2918
        $wpseo = WPSEO_Frontend::get_instance();
2919
        
2920
        remove_action( 'wp_head', array( $wpseo, 'metadesc' ), 6 );
2921
        remove_action( 'wp_head', array( $wpseo, 'metakeywords' ), 11 );
2922
        remove_filter( 'pre_get_document_title', array( $wpseo, 'title' ), 15 );
2923
        remove_filter( 'wp_title', array( $wpseo, 'title' ), 15, 3 );
2924
        remove_filter( 'thematic_doctitle', array( $wpseo, 'title' ), 15 );
2925
        remove_filter( 'woo_title', array( $wpseo, 'fix_woo_title' ), 99 );
2926
        
2927
        remove_action( 'template_redirect', 'wpseo_frontend_head_init', 999 );
2928
    }
2929
}
2930
2931
/**
2932
 * Set the WPML language for AJAX requests for non logged user.
2933
 *
2934
 * Custom AJAX requests always return the default language content.
2935
 *
2936
 * @since 1.6.18
2937
 *
2938
 * @global object $sitepress Sitepress WPML object.
2939
 *
2940
 */
2941
 function geodir_wpml_ajax_set_guest_lang() {    
2942
    if ( geodir_is_wpml() && wpml_is_ajax() && !is_user_logged_in() ) {
2943
        if ( empty( $_GET['lang'] ) && !( !empty( $_SERVER['REQUEST_URI'] ) && preg_match( '@\.(css|js|png|jpg|gif|jpeg|bmp)@i', basename( preg_replace( '@\?.*$@', '', $_SERVER['REQUEST_URI'] ) ) ) ) ) {
2944
            global $sitepress;
2945
            
2946
            $referer = wp_get_referer();
2947
            
2948
            $current_lang = $sitepress->get_current_language();
2949
            $referrer_lang = $sitepress->get_language_from_url( $referer );
2950
            
2951
            if ( $referrer_lang && $current_lang != $referrer_lang ) {
2952
                $_GET['lang'] = $referrer_lang;
2953
            }
2954
        }
2955
    }
2956
}
2957
add_action( 'plugins_loaded', 'geodir_wpml_ajax_set_guest_lang', -1 );
2958
2959
/**
2960
 * Change country slug czech-republic to czechia and redirect.
2961
 *
2962
 * @since 1.6.18
2963
 *
2964
 * @param object $wp The WordPress object.
2965
 */
2966
function geodir_check_redirect($wp) {
2967
    if (is_404() || (!empty($wp->query_vars['error']) && $wp->query_vars['error'] == '404')) {
2968
        $current_url = geodir_curPageURL();
2969
        $search = 'czech-republic';
2970
        $replace = 'czechia';        
2971
        
2972
        $has_slash = substr($current_url, -1);
2973
        if ($has_slash != "/") {
2974
            $current_url .= '/';
2975
        }
2976
        
2977
        $redirect = false;
2978
        if (strpos($current_url, '/' . $search . '/') !== false) {
2979
            $redirect = true;
2980
            $current_url = preg_replace('/\/' . $search . '\//', '/' . $replace . '/', $current_url, 1);
2981
        }
2982
        
2983
        if ($has_slash != "/") {
2984
            $current_url = trim($current_url, '/');
2985
        }
2986
        
2987
        if (strpos($current_url, 'gd_country=' . $search) !== false) {
2988
            $redirect = true;
2989
            $current_url = str_replace('gd_country=' . $search, 'gd_country=' . $replace, $current_url);
2990
        }
2991
2992
        if ($redirect) {
2993
            wp_redirect($current_url);
2994
            exit;
2995
        }
2996
    }
2997
}
2998
add_action('parse_request', 'geodir_check_redirect', 101, 1);
2999
3000
/**
3001
 * Filters the unique post slug.
3002
 *
3003
 * @since 1.6.20
3004
 *
3005
 * @global object $wpdb WordPress Database object.
3006
 * @global object $sitepress Sitepress WPML object.
3007
 *
3008
 * @param string $slug          The post slug.
3009 3
 * @param int    $post_ID       Post ID.
3010
 * @param string $post_status   The post status.
3011 3
 * @param string $post_type     Post type.
3012 3
 * @param int    $post_parent   Post parent ID
3013 3
 * @param string $original_slug The original post slug.
3014 3
 */
3015 3
function geodir_check_post_to_term_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
3016
    global $wpdb, $sitepress;
3017 3
    
3018
    if ( $post_type && strpos( $post_type, 'gd_' ) === 0 ) {
3019
        $wpml_post_join = "";
3020
        $wpml_post_where = "";
3021
        $wpml_term_join = "";
3022
        $wpml_term_where = "";
3023
        
3024
        if (geodir_wpml_is_post_type_translated($post_type)) {
3025
            $post_language = $post_ID ? $sitepress->post_translations()->get_element_lang_code($post_ID) : $sitepress->get_current_language();
3026
            $post_language = $post_language ? $post_language : $sitepress->post_translations()->get_save_post_lang($post_ID, $sitepress);
3027
            if (!$post_language) {
3028
                $post_language = $sitepress->get_current_language();
3029
            }
3030
            
3031 3
            $wpml_post_join = " JOIN {$wpdb->prefix}icl_translations AS icl_t ON p.ID = icl_t.element_id AND icl_t.element_type = CONCAT('post_', p.post_type)";
3032
            $wpml_post_where = " AND icl_t.language_code = '" . $post_language ."'";
3033 3
            
3034
            $wpml_term_join = " JOIN {$wpdb->prefix}icl_translations AS icl_t ON icl_t.element_id = tt.term_taxonomy_id AND icl_t.element_type = CONCAT('tax_', tt.taxonomy)";
3035
            $wpml_term_where = " AND icl_t.language_code = '" . $post_language ."'";
3036
        }
3037
3038
        $term_slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT t.slug FROM $wpdb->terms AS t LEFT JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id {$wpml_term_join} WHERE t.slug = '%s' AND ( tt.taxonomy = '" . $post_type . "category' OR tt.taxonomy = '" . $post_type . "_tags' ) {$wpml_term_where} LIMIT 1", $slug ) );
3039
3040
        if ( $term_slug_check ) {
3041
            $suffix = 1;
3042
            
3043
            do {
3044
                $alt_slug = _truncate_post_slug( $original_slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3045
                
3046
                $term_check = $wpdb->get_var( $wpdb->prepare( "SELECT t.slug FROM $wpdb->terms AS t LEFT JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id {$wpml_term_join} WHERE t.slug = '%s' AND ( tt.taxonomy = '" . $post_type . "category' OR tt.taxonomy = '" . $post_type . "_tags' ) {$wpml_term_where} LIMIT 1", $alt_slug ) );
3047
                
3048
                $post_check = !$term_check && $wpdb->get_var( $wpdb->prepare( "SELECT p.post_name FROM $wpdb->posts p {$wpml_post_join} WHERE p.post_name = %s AND p.post_type = %s AND p.ID != %d {$wpml_term_where} LIMIT 1", $alt_slug, $post_type, $post_ID ) );
3049
                
3050 3
                $term_slug_check = $term_check || $post_check;
3051
                
3052 3
                $suffix++;
3053
            } while ( $term_slug_check );
3054
            
3055
            $slug = $alt_slug;
3056
        }
3057
    }
3058
    
3059
    return $slug;
3060
}
3061
add_filter( 'wp_unique_post_slug', 'geodir_check_post_to_term_slug', 101, 6 );
3062
3063
/**
3064
 * Check whether a post name with slug exists or not.
3065
 *
3066
 * @since 1.6.20
3067
 *
3068
 * @global object $wpdb WordPress Database object.
3069
 * @global array $gd_term_post_type Cached array for term post type.
3070
 * @global array $gd_term_taxonomy Cached array for term taxonomy.
3071
 * @global object $sitepress Sitepress WPML object.
3072 3
 *
3073
 * @param bool $slug_exists Default: false.
3074 3
 * @param string $slug Term slug.
3075
 * @param int $term_id The term ID.
3076
 * @return bool true when exists. false when not exists.
3077
 */
3078 3
function geodir_check_term_to_post_slug( $slug_exists, $slug, $term_id ) {
3079
    global $wpdb, $gd_term_post_type, $gd_term_taxonomy, $sitepress;
3080
    
3081 3
    if ( $slug_exists ) {
3082 3
        return $slug_exists;
3083
    }
3084
    
3085 3
    if ( !empty( $gd_term_taxonomy ) && isset($gd_term_taxonomy[$term_id]) ) {
3086
        $taxonomy = $gd_term_taxonomy[$term_id];
3087
    } else {
3088
        $taxonomy = $wpdb->get_var( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d LIMIT 1", $term_id ) );
3089 3
        $gd_term_taxonomy[$term_id] = $taxonomy;
3090
    }
3091
    
3092 3
    if ( empty($taxonomy) ) {
3093 3
        return $slug_exists;
3094
    }
3095
    
3096 3
    if ( !empty( $gd_term_post_type ) && $gd_term_post_type[$term_id] ) {
3097 3
        $post_type = $gd_term_post_type[$term_id];
3098
    } else {
3099 3
        $taxonomy_obj = get_taxonomy( $taxonomy );
3100
        $post_type = !empty( $taxonomy_obj->object_type ) ? $taxonomy_obj->object_type[0] : NULL;
3101
    }
3102
    
3103
    $wpml_post_join = "";
3104
    $wpml_post_where = "";
3105
    
3106
    if (geodir_wpml_is_taxonomy_translated($taxonomy) || geodir_wpml_is_post_type_translated($post_type)) {
3107
        $term_language = $term_id ? geodir_get_language_for_element($term_id, 'tax_' . $taxonomy) : $sitepress->get_current_language();
3108
        if (!$term_language) {
3109 3
            $term_language = $sitepress->get_current_language();
3110
        }
3111
        
3112
        $wpml_post_join = " JOIN {$wpdb->prefix}icl_translations AS icl_t ON p.ID = icl_t.element_id AND icl_t.element_type = CONCAT('post_', p.post_type)";
3113 3
        $wpml_post_where = " AND icl_t.language_code = '" . $term_language ."'";
3114
    }
3115
    
3116
    if ( $post_type && $wpdb->get_var( $wpdb->prepare( "SELECT p.post_name FROM $wpdb->posts p {$wpml_post_join} WHERE p.post_name = %s AND p.post_type = %s  {$wpml_post_where} LIMIT 1", $slug, $post_type ) ) ) {
3117
        $slug_exists = true;
3118
    }
3119
3120
    return $slug_exists;
3121
}
3122
add_filter( 'geodir_term_slug_is_exists', 'geodir_check_term_to_post_slug', 10, 3 );
3123
3124
/**
3125
 * Add hidden WPML language input field.
3126
 *
3127
 * @since 2.0.0
3128
 * @package GeoDirectory
3129
 *
3130
 *
3131
 * @global SitePress $sitepress
3132
 */
3133
function geodir_wpml_add_language_input_field() {
3134
	global $sitepress;
3135
3136
	if ( function_exists( 'wpml_add_language_form_field_action' ) && WPML_LANGUAGE_NEGOTIATION_TYPE_PARAMETER === (int) $sitepress->get_setting( 'language_negotiation_type' ) ) {
3137
		wpml_add_language_form_field_action();
3138
	}
3139
}
3140
3141
/**
3142
 * Delete listing tag on term delete.
3143
 *
3144
 * @since 1.6.31
3145
 *
3146
 * @global object $wpdb WordPress Database object.
3147
 * @global string $plugin_prefix Geodirectory plugin table prefix.
3148
 *
3149
 * @param int     $term         Term ID.
3150
 * @param int     $tt_id        Term taxonomy ID.
3151
 * @param string  $taxonomy     Taxonomy slug.
3152
 * @param mixed   $deleted_term Copy of the already-deleted term, in the form specified
3153
 *                              by the parent function. WP_Error otherwise.
3154
 * @param array   $object_ids   List of term object IDs.
3155
 */
3156
function geodir_on_delete_term( $term, $tt_id, $taxonomy = '', $deleted_term = array(), $object_ids = array() ) {
3157
	global $wpdb, $plugin_prefix;
3158
3159
	if ( ! empty( $object_ids ) && strpos( $taxonomy, 'gd_' ) === 0 && substr( $taxonomy , -5 ) == '_tags' && ( $taxonomy_obj = get_taxonomy( $taxonomy ) ) ) {
3160
		$post_type = !empty( $taxonomy_obj ) ? $taxonomy_obj->object_type[0] : '';
3161
3162
		if ( $post_type ) {
3163
			$table = $plugin_prefix . $post_type . '_detail';
3164
		
3165
			foreach ( $object_ids as $post_id ) {
3166
				$post_tags = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'names' ) );
3167
				$post_tags = ! empty( $post_tags ) && ! is_wp_error( $post_tags ) ? array_map( 'trim', $post_tags ) : '';
3168
				$post_tags = ! empty( $post_tags ) ? implode( ',', array_filter( array_unique( $post_tags ) ) ) : '';
3169
3170
				$wpdb->query( $wpdb->prepare( "UPDATE {$table} SET post_tags = %s WHERE post_id = %d", array( $post_tags, $post_id ) ) );
3171
			}
3172
		}
3173
	}
3174
}