Test Failed
Push — master ( 4cd501...1b9ce5 )
by Stiofan
07:38
created

admin_functions.php ➔ geodir_gd_accounts()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 8
nop 0
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
ccs 0
cts 4
cp 0
crap 30
1
<?php
2
/**
3
 * Admin functions.
4
 *
5
 * @since 1.0.0
6
 * @package GeoDirectory
7
 */
8
9
/**
10
 * Updates option value when GeoDirectory get deactivated.
11
 * 
12
 * @since 1.0.0
13
 * @package GeoDirectory
14
 */
15
function geodir_deactivation() {
16
    // Update installed variable
17
    update_option("geodir_installed", 0);
18
19
    // Remove rewrite rules and then recreate rewrite rules.
20
    flush_rewrite_rules();
21
}
22
23
if (!function_exists('geodir_admin_styles')) {
24
    /**
25
     * Enqueue Admin Styles.
26
     *
27
     * @since 1.0.0
28
     * @package GeoDirectory
29
     */
30
    function geodir_admin_styles() {
31
        wp_register_style('geodirectory-admin-css', geodir_plugin_url() . '/geodirectory-assets/css/admin.css', array(), GEODIRECTORY_VERSION);
32
        wp_enqueue_style('geodirectory-admin-css');
33
34
        wp_register_style('geodirectory-frontend-style', geodir_plugin_url() . '/geodirectory-assets/css/style.css', array(), GEODIRECTORY_VERSION);
35
        wp_enqueue_style('geodirectory-frontend-style');
36
37
        wp_register_style('geodir-chosen-style', geodir_plugin_url() . '/geodirectory-assets/css/chosen.css', array(), GEODIRECTORY_VERSION);
38
        wp_enqueue_style('geodir-chosen-style');
39
40
        wp_register_style('geodirectory-jquery-ui-timepicker-css', geodir_plugin_url() . '/geodirectory-assets/css/jquery.ui.timepicker.css', array(), GEODIRECTORY_VERSION);
41
        wp_enqueue_style('geodirectory-jquery-ui-timepicker-css');
42
43
        wp_register_style('geodirectory-jquery-ui-css', geodir_plugin_url() . '/geodirectory-assets/css/jquery-ui.css', array(), GEODIRECTORY_VERSION);
44
        wp_enqueue_style('geodirectory-jquery-ui-css');
45
46
        wp_register_style('geodirectory-custom-fields-css', geodir_plugin_url() . '/geodirectory-assets/css/custom_field.css', array(), GEODIRECTORY_VERSION);
47
        wp_enqueue_style('geodirectory-custom-fields-css');
48
49
        wp_register_style('geodirectory-pluplodar-css', geodir_plugin_url() . '/geodirectory-assets/css/pluploader.css', array(), GEODIRECTORY_VERSION);
50
        wp_enqueue_style('geodirectory-pluplodar-css');
51
52
        wp_register_style('geodir-rating-style', geodir_plugin_url() . '/geodirectory-assets/css/jRating.jquery.css', array(), GEODIRECTORY_VERSION);
53
        wp_enqueue_style('geodir-rating-style');
54
55
        wp_register_style('geodir-rtl-style', geodir_plugin_url() . '/geodirectory-assets/css/rtl.css', array(), GEODIRECTORY_VERSION);
56
        wp_enqueue_style('geodir-rtl-style');
57
    }
58
}
59
60
if (!function_exists('geodir_admin_styles_req')) {
61
    /**
62
     * Loads stylesheets from CDN.
63
     *
64
     * @since 1.0.0
65
     * @package GeoDirectory
66
     */
67
    function geodir_admin_styles_req()
68
    {
69
70
        wp_register_style('font-awesome', '//netdna.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', array(), GEODIRECTORY_VERSION);
71
        wp_enqueue_style('font-awesome');
72
73
        wp_register_script('geodirectory-admin', geodir_plugin_url() . '/geodirectory-assets/js/admin-req.min.js', array('jquery'), GEODIRECTORY_VERSION);
74
        wp_enqueue_script('geodirectory-admin');
75
76
    }
77
}
78
79
if (!function_exists('geodir_admin_scripts')) {
80
    /**
81
     * Enqueue Admin Scripts.
82
     *
83
     * @since 1.0.0
84
     * @package GeoDirectory
85
     */
86
    function geodir_admin_scripts()
87
    {
88
        $geodir_map_name = geodir_map_name();
89
        
90
        wp_enqueue_script('jquery');
91
92
        wp_enqueue_script('geodirectory-jquery-ui-timepicker-js', geodir_plugin_url() . '/geodirectory-assets/js/jquery.ui.timepicker.js', array('jquery-ui-datepicker', 'jquery-ui-slider'), '', true);
93
94
        wp_register_script('chosen', geodir_plugin_url() . '/geodirectory-assets/js/chosen.jquery.js', array('jquery'), GEODIRECTORY_VERSION);
95
        wp_enqueue_script('chosen');
96
97
        wp_register_script('geodirectory-choose-ajax', geodir_plugin_url() . '/geodirectory-assets/js/ajax-chosen.js', array(), GEODIRECTORY_VERSION);
98
        wp_enqueue_script('geodirectory-choose-ajax');
99
100
        if (isset($_REQUEST['listing_type'])) {
101
            wp_register_script('geodirectory-custom-fields-script', geodir_plugin_url() . '/geodirectory-assets/js/custom_fields.js', array(), GEODIRECTORY_VERSION);
102
        }
103
104
        wp_enqueue_script('geodirectory-custom-fields-script');
105
        $plugin_path = geodir_plugin_url() . '/geodirectory-functions/cat-meta-functions';
106
107
        wp_enqueue_script('tax-meta-clss', $plugin_path . '/js/tax-meta-clss.js', array('jquery'), null, true);
108
109 View Code Duplication
        if (in_array($geodir_map_name, array('auto', 'google'))) {
110
            $map_lang = "&language=" . geodir_get_map_default_language();
111
            $map_key = "&key=" . geodir_get_map_api_key();
112
            /** This filter is documented in geodirectory_template_tags.php */
113
            $map_extra = apply_filters('geodir_googlemap_script_extra', '');
114
            wp_enqueue_script('geodirectory-googlemap-script', 'https://maps.google.com/maps/api/js?' . $map_lang . $map_key . $map_extra, '', NULL);
115
        }
116
        
117
        if ($geodir_map_name == 'osm') {
118
            // Leaflet OpenStreetMap
119
            wp_register_style('geodirectory-leaflet-style', geodir_plugin_url() . '/geodirectory-assets/leaflet/leaflet.css', array(), GEODIRECTORY_VERSION);
120
            wp_enqueue_style('geodirectory-leaflet-style');
121
                
122
            wp_register_script('geodirectory-leaflet-script', geodir_plugin_url() . '/geodirectory-assets/leaflet/leaflet.min.js', array(), GEODIRECTORY_VERSION);
123
            wp_enqueue_script('geodirectory-leaflet-script');
124
            
125
            wp_register_script('geodirectory-leaflet-geo-script', geodir_plugin_url() . '/geodirectory-assets/leaflet/osm.geocode.js', array('geodirectory-leaflet-script'), GEODIRECTORY_VERSION);
126
            wp_enqueue_script('geodirectory-leaflet-geo-script');
127
        }
128
        wp_enqueue_script( 'jquery-ui-autocomplete' );
129
        
130
        wp_register_script('geodirectory-goMap-script', geodir_plugin_url() . '/geodirectory-assets/js/goMap.min.js', array(), GEODIRECTORY_VERSION,true);
131
        wp_enqueue_script('geodirectory-goMap-script');
132
133
        wp_register_script('geodirectory-goMap-script', geodir_plugin_url() . '/geodirectory-assets/js/goMap.js', array(), GEODIRECTORY_VERSION);
134
        wp_enqueue_script('geodirectory-goMap-script');
135
136
		// font awesome rating script
137 View Code Duplication
		if (get_option('geodir_reviewrating_enable_font_awesome')) {
138
			wp_register_script('geodir-barrating-js', geodir_plugin_url() . '/geodirectory-assets/js/jquery.barrating.min.js', array(), GEODIRECTORY_VERSION);
139
			wp_enqueue_script('geodir-barrating-js');
140
		} else { // default rating script
141
			wp_register_script('geodir-jRating-js', geodir_plugin_url() . '/geodirectory-assets/js/jRating.jquery.js', array(), GEODIRECTORY_VERSION);
142
			wp_enqueue_script('geodir-jRating-js');
143
		}
144
145
        wp_register_script('geodir-on-document-load', geodir_plugin_url() . '/geodirectory-assets/js/on_document_load.min.js', array(), GEODIRECTORY_VERSION);
146
        wp_enqueue_script('geodir-on-document-load');
147
148
149
        // SCRIPT FOR UPLOAD
150
        wp_enqueue_script('plupload-all');
151
        wp_enqueue_script('jquery-ui-sortable');
152
153
        wp_register_script('geodirectory-plupload-script', geodir_plugin_url() . '/geodirectory-assets/js/geodirectory-plupload.js', array(), GEODIRECTORY_VERSION);
154
        wp_enqueue_script('geodirectory-plupload-script');
155
156
        // SCRIPT FOR UPLOAD END
157
158
159
        // place js config array for plupload
160
        $plupload_init = array(
161
            'runtimes' => 'html5,silverlight,flash,html4',
162
            'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
163
            'container' => 'plupload-upload-ui', // will be adjusted per uploader
164
            'drop_element' => 'dropbox', // will be adjusted per uploader
165
            'file_data_name' => 'async-upload', // will be adjusted per uploader
166
            'multiple_queues' => true,
167
            'max_file_size' => geodir_max_upload_size(),
168
            'url' => admin_url('admin-ajax.php'),
169
            'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
170
            'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
171
            'filters' => array(array('title' => __('Allowed Files', 'geodirectory'), 'extensions' => '*')),
172
            'multipart' => true,
173
            'urlstream_upload' => true,
174
            'multi_selection' => false, // will be added per uploader
175
            // additional post data to send to our ajax hook
176
            'multipart_params' => array(
177
                '_ajax_nonce' => "", // will be added per uploader
178
                'action' => 'plupload_action', // the ajax action name
179
                'imgid' => 0 // will be added per uploader
180
            )
181
        );
182
        $base_plupload_config = json_encode($plupload_init);
183
184
185
        $thumb_img_arr = array();
186
187
        if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '')
188
            $thumb_img_arr = geodir_get_images($_REQUEST['pid']);
189
190
        $totImg = '';
191
        $image_limit = '';
192
        if (!empty($thumb_img_arr)) {
193
            $totImg = count($thumb_img_arr);
194
        }
195
196
        $gd_plupload_init = array('base_plupload_config' => $base_plupload_config,
197
            'totalImg' => $totImg,
198
            'image_limit' => $image_limit,
199
            'upload_img_size' => geodir_max_upload_size());
200
201
        wp_localize_script('geodirectory-plupload-script', 'gd_plupload', $gd_plupload_init);
202
203
        $ajax_cons_data = array('url' => __(admin_url('admin-ajax.php')));
204
        wp_localize_script('geodirectory-custom-fields-script', 'geodir_admin_ajax', $ajax_cons_data);
205
206
207
        wp_register_script('geodirectory-admin-script', geodir_plugin_url() . '/geodirectory-assets/js/admin.js', array(), GEODIRECTORY_VERSION);
208
        wp_enqueue_script('geodirectory-admin-script');
209
210
        wp_enqueue_style('farbtastic');
211
        wp_enqueue_script('farbtastic');
212
213
        $screen = get_current_screen();
214
        if ($screen->base == 'post' && in_array($screen->post_type, geodir_get_posttypes())) {
215
            wp_enqueue_script('geodirectory-listing-validation-script', geodir_plugin_url() . '/geodirectory-assets/js/listing_validation_admin.js');
216
        }
217
218
        $ajax_cons_data = array('url' => esc_url(__(get_option('siteurl') . '?geodir_ajax=true')));
219
        wp_localize_script('geodirectory-admin-script', 'geodir_ajax', $ajax_cons_data);
220
221
    }
222
}
223
224
if (!function_exists('geodir_admin_menu')) {
225
    /**
226
     * Admin Menus
227
     *
228
     * Sets up the admin menus in wordpress.
229
     *
230
     * @since 1.0.0
231
     * @package GeoDirectory
232
     * @global array $menu Menu array.
233
     * @global object $geodirectory GeoDirectory plugin object.
234
     */
235
    function geodir_admin_menu()
236
    {
237
        global $menu, $geodirectory;
238
239
        if (current_user_can('manage_options')) $menu[] = array('', 'read', 'separator-geodirectory', '', 'wp-menu-separator geodirectory');
240
241
        add_menu_page(__('Geodirectory', 'geodirectory'), __('Geodirectory', 'geodirectory'), 'manage_options', 'geodirectory', 'geodir_admin_panel', geodir_plugin_url() . '/geodirectory-assets/images/favicon.ico', '55.1984');
242
243
244
    }
245
}
246
247
if (!function_exists('geodir_admin_menu_order')) {
248
    /**
249
     * Order admin menus.
250
     *
251
     * @since 1.0.0
252
     * @package GeoDirectory
253
     * @param array $menu_order Menu order array.
254
     * @return array Modified menu order array.
255
     */
256
    function geodir_admin_menu_order($menu_order)
257
    {
258
259
        // Initialize our custom order array
260
        $geodir_menu_order = array();
261
262
        // Get the index of our custom separator
263
        $geodir_separator = array_search('separator-geodirectory', $menu_order);
264
265
        // Get index of posttype menu
266
        $post_types = geodir_get_posttypes();
267
268
        // Loop through menu order and do some rearranging
269
        foreach ($menu_order as $index => $item) :
270
271
            if ((('geodirectory') == $item)) :
272
                $geodir_menu_order[] = 'separator-geodirectory';
273
                if (!empty($post_types)) {
274
                    foreach ($post_types as $post_type) {
0 ignored issues
show
Bug introduced by
The expression $post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
275
                        $geodir_menu_order[] = 'edit.php?post_type=' . $post_type;
276
                    }
277
                }
278
                $geodir_menu_order[] = $item;
279
280
                unset($menu_order[$geodir_separator]);
281
            //unset( $menu_order[$geodir_places] );
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
282
            elseif (!in_array($item, array('separator-geodirectory'))) :
283
                $geodir_menu_order[] = $item;
284
            endif;
285
286
        endforeach;
287
288
        // Return order
289
        return $geodir_menu_order;
290
    }
291
}
292
293
if (!function_exists('geodir_admin_custom_menu_order')) {
294
    /**
295
     * Enables custom menu order.
296
     *
297
     * @since 1.0.0
298
     * @package GeoDirectory
299
     * @return bool
300
     */
301
    function geodir_admin_custom_menu_order()
302
    {
303
        if (!current_user_can('manage_options')) return false;
304
        return true;
305
    }
306
}
307
308
/**
309
 * Function to show success or error message on admin option form submission.
310
 *
311
 * @since 1.0.0
312
 * @package GeoDirectory
313
 */
314
function geodir_before_admin_panel()
315
{
316
    if (isset($_REQUEST['installed']) && $_REQUEST['installed'] != '') {
317
        echo '<div id="message" class="updated fade">
318
                        <p style="float:right;">' . __('Like Geodirectory?', 'geodirectory') . ' <a href="http://wordpress.org/extend/plugins/Geodirectory/" target="_blank">' . __('Support us by leaving a rating!', 'geodirectory') . '</a></p>
319
                        <p><strong>' . __('Geodirectory has been installed and setup. Enjoy :)', 'geodirectory') . '</strong></p>
320
                </div>';
321
322
    }
323
324
    if (isset($_REQUEST['msg']) && $_REQUEST['msg'] != '') {
325
        switch ($_REQUEST['msg']) {
326
            case 'success':
327
                echo '<div id="message" class="updated fade"><p><strong>' . __('Your settings have been saved.', 'geodirectory') . '</strong></p></div>';
328
                flush_rewrite_rules(false);
329
330
                break;
331
			case 'fail':
332
				$gderr = isset($_REQUEST['gderr']) ? $_REQUEST['gderr'] : '';
333
				
334
				if ($gderr == 21)
335 1
			    	echo '<div id="message" class="error fade"><p><strong>' . __('Error: You can not add same permalinks for both Listing and Location, please try again.', 'geodirectory') . '</strong></p></div>';
336
				else
337
					echo '<div id="message" class="error fade"><p><strong>' . __('Error: Your settings have not been saved, please try again.', 'geodirectory') . '</strong></p></div>';
338
                break;
339
        }
340
    }
341
342
    $geodir_load_map = get_option('geodir_load_map');
343 1
    $need_map_key = false;
344
    if($geodir_load_map=='' || $geodir_load_map=='google' || $geodir_load_map=='auto' ){
345
        $need_map_key = true;
346
    }
347
348 View Code Duplication
    if (!geodir_get_map_api_key() && $need_map_key) {
349
        echo '<div class="error"><p><strong>' . sprintf(__('Google Maps API KEY not set, %sclick here%s to set one OR use Open Street Maps instead.', 'geodirectory'), '<a href=\'' . admin_url('admin.php?page=geodirectory&tab=design_settings&active_tab=geodir_map_settings') . '\'>', '</a>') . '</strong></p></div>';
350
    }
351
352 View Code Duplication
    if (!geodir_is_default_location_set()) {
353
        echo '<div class="updated fade"><p><strong>' . sprintf(__('Please %sclick here%s to set a default location, this will make the plugin work properly.', 'geodirectory'), '<a href=\'' . admin_url('admin.php?page=geodirectory&tab=default_location_settings') . '\'>', '</a>') . '</strong></p></div>';
354
355
    }
356
357
    if (!function_exists('curl_init')) {
358
        echo '<div class="error"><p><strong>' . __('CURL is not installed on this server, this can cause problems, please ask your server admin to install it.', 'geodirectory') . '</strong></p></div>';
359
360
    }
361 1
362 1
363 1
364 1
365 1
}
366
367 1
/**
368 1
 * Handles data posted from GeoDirectory settings form.
369 1
 *
370
 * @since 1.0.0
371 1
 * @package GeoDirectory
372
 * @global array $geodir_settings Geodirectory settings array.
373
 * @param string $current_tab The current settings tab name.
374
 */
375
function geodir_handle_option_form_submit($current_tab)
376 1
{
377
    global $geodir_settings;
378
    if (file_exists(dirname(__FILE__) . '/option-pages/' . $current_tab . '_array.php')) {
379
        /**
380
         * Contains settings array for current tab.
381
         *
382
         * @since 1.0.0
383
         * @package GeoDirectory
384 1
         */
385
        include_once('option-pages/' . $current_tab . '_array.php');
386
    }
387
    if (isset($_POST) && $_POST && isset($_REQUEST['page']) && $_REQUEST['page'] == 'geodirectory') :
388
        if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'geodir-settings')) die(__('Action failed. Please refresh the page and retry.', 'geodirectory'));
389
        if (!wp_verify_nonce($_REQUEST['_wpnonce-' . $current_tab], 'geodir-settings-' . $current_tab)) die(__('Action failed. Please refresh the page and retry.', 'geodirectory'));
390
		
391
		/**
392
		 * Fires before updating geodirectory admin settings.
393
		 *
394
		 * @since 1.4.2
395
		 *
396
		 * @param string $current_tab Current tab in geodirectory settings.
397
		 * @param array  $geodir_settings Array of geodirectory settings.
398
		 */
399
		do_action('geodir_before_update_options', $current_tab, $geodir_settings);		
400
		
401
        if (!empty($geodir_settings[$current_tab]))
402
            geodir_update_options($geodir_settings[$current_tab]);
403
404
        /**
405
         * Called after GeoDirectory options settings are updated.
406
         *
407
         * @since 1.0.0
408
         * @param array $geodir_settings The array of GeoDirectory settings.
409
         * @see 'geodir_before_update_options'
410
         */
411
        do_action('geodir_update_options', $geodir_settings);
412
413
        /**
414
         * Called after GeoDirectory options settings are updated.
415
         *
416
         * Provides tab specific settings.
417
         *
418
         * @since 1.0.0
419
         * @param string $current_tab The current settings tab name.
420
         * @param array $geodir_settings[$current_tab] The array of settings for the current settings tab.
421
         */
422
        do_action('geodir_update_options_' . $current_tab, $geodir_settings[$current_tab]);
423
424
        flush_rewrite_rules(false);
425
426
        $current_tab = isset($_REQUEST['tab']) ? $_REQUEST['tab'] : '';
427
428
        $redirect_url = admin_url('admin.php?page=geodirectory&tab=' . $current_tab . '&active_tab=' . $_REQUEST['active_tab'] . '&msg=success');
429
430
        wp_redirect($redirect_url);
431
        exit();
432
    endif;
433
434
435
}
436
437
438
/**
439
 * Update options
440
 *
441
 * Updates the options on the geodirectory settings pages. Returns true if saved.
442
 *
443
 * @since 1.0.0
444
 * @package GeoDirectory
445
 * @param array $options The option array.
446
 * @param bool $dummy Is this dummy settings? Default: false.
447
 * @return bool Returns true if saved.
448
 */
449
function geodir_update_options($options, $dummy = false) {
450
    if ((!isset($_POST) || !$_POST) && !$dummy) return false;
451
452
    foreach ($options as $value) {
453
        if ($dummy && isset($value['std']))
454
            $_POST[$value['id']] = $value['std'];
455
456
457
        if (isset($value['type']) && $value['type'] == 'checkbox') :
458
459 View Code Duplication
            if (isset($value['id']) && isset($_POST[$value['id']])) {
460
                update_option($value['id'], $_POST[$value['id']]);
461
            } else {
462
                update_option($value['id'], 0);
463
            }
464
465
        elseif (isset($value['type']) && $value['type'] == 'image_width') :
466
467
            if (isset($value['id']) && isset($_POST[$value['id'] . '_width'])) {
468
                update_option($value['id'] . '_width', $_POST[$value['id'] . '_width']);
469
                update_option($value['id'] . '_height', $_POST[$value['id'] . '_height']);
470 1 View Code Duplication
                if (isset($_POST[$value['id'] . '_crop'])) :
471
                    update_option($value['id'] . '_crop', 1);
472 1
                else :
473
                    update_option($value['id'] . '_crop', 0);
474
                endif;
475 View Code Duplication
            } else {
476 1
                update_option($value['id'] . '_width', $value['std']);
477
                update_option($value['id'] . '_height', $value['std']);
478 1
                update_option($value['id'] . '_crop', 1);
479
            }
480 1
481 1
        elseif (isset($value['type']) && $value['type'] == 'map') :
482
            $post_types = array();
483 1
            $categories = array();
484 1
485 1
            if (!empty($_POST['home_map_post_types'])) :
486
                foreach ($_POST['home_map_post_types'] as $post_type) :
487
                    $post_types[] = $post_type;
488
                endforeach;
489
            endif;
490
491
            update_option('geodir_exclude_post_type_on_map', $post_types);
492
493
            if (!empty($_POST['post_category'])) :
494
                foreach ($_POST['post_category'] as $texonomy => $cat_arr) :
495
                    $categories[$texonomy] = array();
496
                    foreach ($cat_arr as $category) :
497
                        $categories[$texonomy][] = $category;
498
                    endforeach;
499
                    $categories[$texonomy] = !empty($categories[$texonomy]) ? array_unique($categories[$texonomy]) : array();
500
                endforeach;
501 1
            endif;
502
            update_option('geodir_exclude_cat_on_map', $categories);
503
            update_option('geodir_exclude_cat_on_map_upgrade', 1);
504
        elseif (isset($value['type']) && $value['type'] == 'map_default_settings') :
505 1
506 1
507 1
            if (!empty($_POST['geodir_default_map_language'])):
508 1
                update_option('geodir_default_map_language', $_POST['geodir_default_map_language']);
509 1
            endif;
510 1
511
512
            if (!empty($_POST['geodir_default_map_search_pt'])):
513
                update_option('geodir_default_map_search_pt', $_POST['geodir_default_map_search_pt']);
514
            endif;
515
516
517
        elseif (isset($value['type']) && $value['type'] == 'file') :
518
519
520
            if (isset($_POST[$value['id'] . '_remove']) && $_POST[$value['id'] . '_remove']) {// if remove is set then remove the file
521
522 View Code Duplication
                if (get_option($value['id'])) {
523
                    $image_name_arr = explode('/', get_option($value['id']));
524
                    $noimg_name = end($image_name_arr);
525
                    $img_path = $uploads['path'] . '/' . $noimg_name;
0 ignored issues
show
Bug introduced by
The variable $uploads does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
526
                    if (file_exists($img_path))
527
                        unlink($img_path);
528
                }
529
530
                update_option($value['id'], '');
531
            }
532
533
            $uploadedfile = isset($_FILES[$value['id']]) ? $_FILES[$value['id']] : '';
534
            $filename = isset($_FILES[$value['id']]['name']) ? $_FILES[$value['id']]['name'] : '';
535
536
            if (!empty($filename)):
537
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
0 ignored issues
show
Unused Code introduced by
$ext is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
538
                $uplaods = array();
539
540
                foreach ($uploadedfile as $key => $uplaod):
541
                    if ($key == 'name'):
542
                        $uplaods[$key] = $filename;
543
                    else :
544
                        $uplaods[$key] = $uplaod;
545
                    endif;
546
                endforeach;
547
548
                $uploads = wp_upload_dir();
549
550 View Code Duplication
                if (get_option($value['id'])) {
551
                    $image_name_arr = explode('/', get_option($value['id']));
552
                    $noimg_name = end($image_name_arr);
553
                    $img_path = $uploads['path'] . '/' . $noimg_name;
554
                    if (file_exists($img_path))
555
                        unlink($img_path);
556
                }
557
558
                $upload_overrides = array('test_form' => false);
559
                $movefile = wp_handle_upload($uplaods, $upload_overrides);
560
561
                update_option($value['id'], $movefile['url']);
562
563
            endif;
564
565
            if (!get_option($value['id']) && isset($value['value'])):
566
                update_option($value['id'], $value['value']);
567
            endif;
568
569
570
        else :
571
            // same menu setting per theme.
572
            if (isset($value['id']) && $value['id'] == 'geodir_theme_location_nav' && isset($_POST[$value['id']])) {
573
                $theme = wp_get_theme();
574
                update_option('geodir_theme_location_nav_' . $theme->name, $_POST[$value['id']]);
575
            }
576
577 View Code Duplication
            if (isset($value['id']) && isset($_POST[$value['id']])) {
578
                update_option($value['id'], $_POST[$value['id']]);
579
            } else {
580
                delete_option($value['id']);
581
            }
582
583
        endif;
584
    }
585
    if ($dummy)
586
        $_POST = array();
587
    return true;
588
589
}
590
591
/**
592
 * create custom fields for place.
593
 *
594
 * @since 1.0.0
595
 * @package GeoDirectory
596
 * @param array $tabs {
597
 *    Attributes of the tabs array.
598
 *
599
 *    @type array $general_settings {
600
 *        Attributes of general settings.
601
 *
602
 *        @type string $label Default "General".
603 1
 *
604
 *    }
605
 *    @type array $design_settings {
606
 *        Attributes of design settings.
607
 *
608
 *        @type string $label Default "Design".
609
 *
610
 *    }
611
 *    @type array $permalink_settings {
612
 *        Attributes of permalink settings.
613
 *
614
 *        @type string $label Default "Permalinks".
615
 *
616
 *    }
617
 *    @type array $notifications_settings {
618
 *        Attributes of notifications settings.
619
 *
620
 *        @type string $label Default "Notifications".
621
 *
622
 *    }
623
 *    @type array $default_location_settings {
624
 *        Attributes of default location settings.
625
 *
626
 *        @type string $label Default "Set Default Location".
627
 *
628
 *    }
629
 *
630
 * }
631
 * @return array Modified tabs array.
632
 */
633
function places_custom_fields_tab($tabs)
634
{
635
636
    $geodir_post_types = get_option('geodir_post_types');
637
638
    if (!empty($geodir_post_types)) {
639
640
        foreach ($geodir_post_types as $geodir_post_type => $geodir_posttype_info):
641
642
            $listing_slug = $geodir_posttype_info['labels']['singular_name'];
643 2
644
            $tabs[$geodir_post_type . '_fields_settings'] = array(
645
                'label' => __(ucfirst($listing_slug) . ' Settings', 'geodirectory'),
646 2
                'subtabs' => array(
647
                    array('subtab' => 'custom_fields',
648
                        'label' => __('Custom Fields', 'geodirectory'),
649 2
                        'request' => array('listing_type' => $geodir_post_type)),
650 2
                    array('subtab' => 'sorting_options',
651 2
                        'label' => __('Sorting Options', 'geodirectory'),
652
                        'request' => array('listing_type' => $geodir_post_type)),
653
                ),
654 2
                'tab_index' => 9,
655 2
                'request' => array('listing_type' => $geodir_post_type)
656
            );
657
658
        endforeach;
659
660
    }
661
662
    return $tabs;
663
}
664
665
666
/**
667
 * Adds GD Tools settings menu to GeoDirectory settings.
668 1
 *
669
 * Can be found here. WP Admin -> Geodirectory -> GD Tools.
670 1
 *
671
 * @since 1.0.0
672 1
 * @package GeoDirectory
673
 * @param array $tabs Tab menu array {@see places_custom_fields_tab()}.
674 1
 * @return array Modified tab menu array.
675
 */
676 1
function geodir_tools_setting_tab($tabs)
677 1
{
678 1
    wp_enqueue_script( 'jquery-ui-progressbar' );
679
    $tabs['tools_settings'] = array('label' => __('GD Tools', 'geodirectory'));
680
    return $tabs;
681
}
682
683
/**
684
 * Adds Theme Compatibility menu item to GeoDirectory settings page.
685
 *
686
 * Can be found here. WP Admin -> Geodirectory -> Theme Compatibility.
687
 *
688
 * @since 1.0.0
689
 * @package GeoDirectory
690
 * @param array $tabs Tab menu array {@see places_custom_fields_tab()}.
691
 * @return array Modified tab menu array.
692
 */
693
function geodir_compatibility_setting_tab($tabs)
694
{
695
    $tabs['compatibility_settings'] = array('label' => __('Theme Compatibility', 'geodirectory'));
696
    return $tabs;
697
}
698
699
700
/**
701
 * Adds Extend Geodirectory menu item to GeoDirectory settings page.
702
 *
703
 * Can be found here. WP Admin -> Geodirectory -> Extend Geodirectory.
704
 *
705
 * @since 1.0.0
706
 * @package GeoDirectory
707
 * @param array $tabs Tab menu array {@see places_custom_fields_tab()}.
708
 * @return array Modified tab menu array.
709
 */
710
function geodir_extend_geodirectory_setting_tab($tabs)
711
{
712
    $tabs['extend_geodirectory_settings'] = array('label' => __('Extend Geodirectory', 'geodirectory'). ' <i class="fa fa-plug"></i>', 'url' => 'https://wpgeodirectory.com', 'target' => '_blank');
713
    return $tabs;
714
}
715
716
717
if (!function_exists('geodir_edit_post_columns')) {
718
    /**
719
     * Modify admin post listing page columns.
720
     *
721
     * @since 1.0.0
722
     * @package GeoDirectory
723
     * @param array $columns The column array.
724
     * @return array Altered column array.
725
     */
726
    function geodir_edit_post_columns($columns)
727
    {
728
729
        $new_columns = array('location' => __('Location (ID)', 'geodirectory'),
730 1
            'categorys' => __('Categories', 'geodirectory'));
731
732 1
        if (($offset = array_search('author', array_keys($columns))) === false) // if the key doesn't exist
733
        {
734
            $offset = 0; // should we prepend $array with $data?
0 ignored issues
show
Unused Code introduced by
$offset is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
735
            $offset = count($columns); // or should we append $array with $data? lets pick this one...
736
        }
737
738
        $columns = array_merge(array_slice($columns, 0, $offset), $new_columns, array_slice($columns, $offset));
739
740
        $columns = array_merge($columns, array('expire' => __('Expires', 'geodirectory')));
741
742
        return $columns;
743
    }
744
}
745
746
747
if (!function_exists('geodir_manage_post_columns')) {
748
    /**
749
     * Adds content to our custom post listing page columns.
750
     *
751
     * @since 1.0.0
752
     * @package GeoDirectory
753
     * @global object $wpdb WordPress Database object.
754
     * @global object $post WordPress Post object.
755
     * @param string $column The column name.
756
     * @param int $post_id The post ID.
757
     */
758
    function geodir_manage_post_columns($column, $post_id)
759
    {
760
        global $post, $wpdb;
761
762
        switch ($column):
763
            /* If displaying the 'city' column. */
764
            case 'location' :
765
                $location_id = geodir_get_post_meta($post->ID, 'post_location_id', true);
766
                $location = geodir_get_location($location_id);
767
                /* If no city is found, output a default message. */
768
                if (empty($location)) {
769
                    _e('Unknown', 'geodirectory');
770
                } else {
771
                    /* If there is a city id, append 'city name' to the text string. */
772
                    $add_location_id = $location_id > 0 ? ' (' . $location_id . ')' : '';
773
                    echo(__($location->country, 'geodirectory') . '-' . $location->region . '-' . $location->city . $add_location_id);
774
                }
775 1
                break;
776 1
777
            /* If displaying the 'expire' column. */
778
            case 'expire' :
779
                $expire_date = geodir_get_post_meta($post->ID, 'expire_date', true);
780
                $d1 = $expire_date; // get expire_date
781
                $d2 = date('Y-m-d'); // get current date
782
                $state = __('days left', 'geodirectory');
783
                $date_diff_text = '';
784
                $expire_class = 'expire_left';
785
                if ($expire_date != 'Never') {
786
                    if (strtotime($d1) < strtotime($d2)) {
787
                        $state = __('days overdue', 'geodirectory');
788
                        $expire_class = 'expire_over';
789
                    }
790 1
                    $date_diff = round(abs(strtotime($d1) - strtotime($d2)) / 86400); // get the difference in days
791
                    $date_diff_text = '<br /><span class="' . $expire_class . '">(' . $date_diff . ' ' . $state . ')</span>';
792 1
                }
793 1
                /* If no expire_date is found, output a default message. */
794 1
                if (empty($expire_date))
795
                    echo __('Unknown', 'geodirectory');
796
                /* If there is a expire_date, append 'days left' to the text string. */
797 1
                else
798
                    echo $expire_date . $date_diff_text;
799 1
                break;
800 1
801 1
            /* If displaying the 'categorys' column. */
802
            case 'categorys' :
803
804
                /* Get the categorys for the post. */
805 1
806
807
                $terms = wp_get_object_terms($post_id, get_object_taxonomies($post));
808
809
                /* If terms were found. */
810
                if (!empty($terms)) {
811
                    $out = array();
812
                    /* Loop through each term, linking to the 'edit posts' page for the specific term. */
813
                    foreach ($terms as $term) {
814
                        if (!strstr($term->taxonomy, 'tag')) {
815
                            $out[] = sprintf('<a href="%s">%s</a>',
816
                                esc_url(add_query_arg(array('post_type' => $post->post_type, $term->taxonomy => $term->slug), 'edit.php')),
817
                                esc_html(sanitize_term_field('name', $term->name, $term->term_id, $term->taxonomy, 'display'))
818
                            );
819
                        }
820
                    }
821 1
                    /* Join the terms, separating them with a comma. */
822 1
                    echo(join(', ', $out));
823 1
                } /* If no terms were found, output a default message. */
824
                else {
825 1
                    _e('No Categories', 'geodirectory');
826
                }
827
                break;
828
829
        endswitch;
830
    }
831 1
}
832
833 1
834
if (!function_exists('geodir_post_sortable_columns')) {
835
    /**
836
     * Makes admin post listing page columns sortable.
837
     *
838
     * @since 1.0.0
839
     * @package GeoDirectory
840
     * @param array $columns The column array.
841
     * @return array Altered column array.
842 1
     */
843 1
    function geodir_post_sortable_columns($columns)
844 1
    {
845
846
        $columns['expire'] = 'expire';
847 1
848
        return $columns;
849
    }
850
}
851
852 1
/**
853
 * Saves listing data from request variable to database.
854
 *
855
 * @since 1.0.0
856
 * @package GeoDirectory
857 1
 * @global object $wpdb WordPress Database object.
858
 * @global object $current_user Current user object.
859
 * @global object $post WordPress Post object.
860 1
 * @param int $post_id The post ID.
861
 */
862
function geodir_post_information_save($post_id, $post) {
863
    global $wpdb, $current_user;
864
865
    if (isset($post->post_type) && ($post->post_type=='nav_menu_item' || $post->post_type=='page' || $post->post_type=='post')) {
866
        return;
867
    }
868
869
    $geodir_posttypes = geodir_get_posttypes();
870
871
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
872
        return;
873 1
874 1
    if (!wp_is_post_revision($post_id) && isset($post->post_type) && in_array($post->post_type, $geodir_posttypes)) {
875
        if (isset($_REQUEST['_status']))
876 1
            geodir_change_post_status($post_id, $_REQUEST['_status']);
877
878
        if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'trash' || $_REQUEST['action'] == 'untrash'))
879
            return;
880
881 View Code Duplication
        if (!isset($_POST['geodir_post_info_noncename']) || !wp_verify_nonce($_POST['geodir_post_info_noncename'], plugin_basename(__FILE__)))
882
            return;
883
884 View Code Duplication
        if (!isset($_POST['geodir_post_attachments_noncename']) || !wp_verify_nonce($_POST['geodir_post_attachments_noncename'], plugin_basename(__FILE__)))
885
            return;
886
887
        geodir_save_listing($_REQUEST);
888
    }
889
}
890
891
/**
892
 * Admin fields
893
 *
894
 * Loops though the geodirectory options array and outputs each field.
895
 *
896
 * @since 1.0.0
897
 * @package GeoDirectory
898
 * @global object $geodirectory GeoDirectory plugin object.
899
 * @global object $sitepress Sitepress WPML object.
900
 * @param array $options The options array.
901
 */
902
function geodir_admin_fields($options)
903
{
904
    global $geodirectory;
905 1
906
    $first_title = true;
907
    $tab_id = '';
908
    $i = 0;
909
    foreach ($options as $value) :
910 1
        if (!isset($value['name'])) $value['name'] = '';
911
        if (!isset($value['class'])) $value['class'] = '';
912 1
        if (!isset($value['css'])) $value['css'] = '';
913 1
        if (!isset($value['std'])) $value['std'] = '';
914 1
        $desc = '';
915 1
        switch ($value['type']) :
916
            case 'dummy_installer':
917 1
                $post_type = isset($value['post_type']) ? $value['post_type'] : 'gd_place';
918 1
                geodir_autoinstall_admin_header($post_type);
919 1
                break;
920 1
            case 'title':
921
922
                if ($i == 0) {
923
                    echo '<dl id="geodir_oiption_tabs" class="gd-tab-head"></dl>';
924 1
                    echo '<div class="inner_content_tab_main">';
925
                }
926 1
927 1
                $i++;
928
929
                if (isset($value['id']) && $value['id'])
930
                    $tab_id = $value['id'];
931
932 View Code Duplication
                if (isset($value['desc']) && $value['desc'])
933
                    $desc = '<span style=" text-transform:none;">:- ' . $value['desc'] . '</span>';
0 ignored issues
show
Unused Code introduced by
$desc is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
934
935
                if (isset($value['name']) && $value['name']) {
936
                    if ($first_title === true) {
937
                        $first_title = false;
938
                    } else {
939
                        echo '</div>';
940
                    }
941
                    echo '<dd id="' . trim($tab_id) . '" class="geodir_option_tabs" ><a href="javascript:void(0);">' . $value['name'] . '</a></dd>';
942
943
                    echo '<div id="sub_' . trim($tab_id) . '" class="gd-content-heading" style=" margin-bottom:10px;" >';
944
                }
945
946
                /**
947
                 * Called after a GeoDirectory settings title is output in the GD settings page.
948
                 *
949
                 * The action is called dynamically geodir_settings_$value['id'].
950
                 *
951
                 * @since 1.0.0
952
                 */
953
                do_action('geodir_settings_' . sanitize_title($value['id']));
954
                break;
955
956
            case 'no_tabs':
957
958
                echo '<div class="inner_content_tab_main">';
959
                echo '<div id="sub_' . trim($tab_id) . '" class="gd-content-heading" style=" margin-bottom:10px;" >';
960
961
                break;
962
963
            case 'sectionstart':
964 View Code Duplication
                if (isset($value['desc']) && $value['desc'])
965
                    $desc = '<span style=" text-transform:none;"> - ' . $value['desc'] . '</span>';
966 View Code Duplication
                if (isset($value['name']) && $value['name'])
967
                    echo '<h3>' . $value['name'] . $desc . '</h3>';
968
                /**
969
                 * Called after a GeoDirectory settings sectionstart is output in the GD settings page.
970
                 *
971
                 * The action is called dynamically geodir_settings_$value['id']_start.
972
                 *
973
                 * @since 1.0.0
974
                 */
975 View Code Duplication
                if (isset($value['id']) && $value['id']) do_action('geodir_settings_' . sanitize_title($value['id']) . '_start');
976
                echo '<table class="form-table">' . "\n\n";
977
978
                break;
979
            case 'sectionend':
980
                /**
981
                 * Called before a GeoDirectory settings sectionend is output in the GD settings page.
982
                 *
983
                 * The action is called dynamically geodir_settings_$value['id']_end.
984
                 *
985
                 * @since 1.0.0
986
                 */
987 View Code Duplication
                if (isset($value['id']) && $value['id']) do_action('geodir_settings_' . sanitize_title($value['id']) . '_end');
988
                echo '</table>';
989
                /**
990
                 * Called after a GeoDirectory settings sectionend is output in the GD settings page.
991
                 *
992
                 * The action is called dynamically geodir_settings_$value['id']_end.
993
                 *
994
                 * @since 1.0.0
995
                 */
996 View Code Duplication
                if (isset($value['id']) && $value['id']) do_action('geodir_settings_' . sanitize_title($value['id']) . '_after');
997
                break;
998 View Code Duplication
            case 'text':
999
                ?>
1000
                <tr valign="top">
1001
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1002
                <td class="forminp"><input name="<?php echo esc_attr($value['id']); ?>"
1003
                                           id="<?php echo esc_attr($value['id']); ?>"
1004
                                           type="<?php echo esc_attr($value['type']); ?>"
1005
                                           <?php if(isset($value['placeholder'])){?>placeholder="<?php echo esc_attr($value['placeholder']); ?>"<?php }?>
1006
                                           style=" <?php echo esc_attr($value['css']); ?>"
1007
                                           value="<?php if (get_option($value['id']) !== false && get_option($value['id']) !== null) {
1008
                                               echo esc_attr(stripslashes(get_option($value['id'])));
1009
                                           } else {
1010
                                               echo esc_attr($value['std']);
1011
                                           } ?>"/> <span class="description"><?php echo $value['desc']; ?></span></td>
1012
                </tr><?php
1013
                break;
1014
1015 View Code Duplication
            case 'password':
1016
                ?>
1017
                <tr valign="top">
1018
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1019
                <td class="forminp"><input name="<?php echo esc_attr($value['id']); ?>"
1020
                                           id="<?php echo esc_attr($value['id']); ?>"
1021
                                           type="<?php echo esc_attr($value['type']); ?>"
1022
                                           <?php if(isset($value['placeholder'])){?>placeholder="<?php echo esc_attr($value['placeholder']); ?>"<?php }?>
1023
                                           style="<?php echo esc_attr($value['css']); ?>"
1024
                                           value="<?php if (get_option($value['id']) !== false && get_option($value['id']) !== null) {
1025
                                               echo esc_attr(stripslashes(get_option($value['id'])));
1026
                                           } else {
1027
                                               echo esc_attr($value['std']);
1028
                                           } ?>"/> <span class="description"><?php echo $value['desc']; ?></span></td>
1029
                </tr><?php
1030
                break;
1031
1032
            case 'html_content':
1033
                ?>
1034
                <tr valign="top">
1035
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1036
                <td class="forminp"><span class="description"><?php echo $value['desc']; ?></span></td>
1037
                </tr><?php
1038
                break;
1039
1040
            case 'color' :
1041
                ?>
1042
                <tr valign="top">
1043
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1044
                <td class="forminp"><input name="<?php echo esc_attr($value['id']); ?>"
1045
                                           id="<?php echo esc_attr($value['id']); ?>" type="text"
1046
                                           style="<?php echo esc_attr($value['css']); ?>"
1047
                                           value="<?php if (get_option($value['id']) !== false && get_option($value['id']) !== null) {
1048
                                               echo esc_attr(stripslashes(get_option($value['id'])));
1049
                                           } else {
1050
                                               echo esc_attr($value['std']);
1051
                                           } ?>" class="colorpick"/> <span
1052
                        class="description"><?php echo $value['desc']; ?></span>
1053
1054
                    <div id="colorPickerDiv_<?php echo esc_attr($value['id']); ?>" class="colorpickdiv"
1055
                         style="z-index: 100;background:#eee;border:1px solid #ccc;position:absolute;display:none;"></div>
1056
                </td>
1057
                </tr><?php
1058
                break;
1059
            case 'image_width' :
1060
                ?>
1061
                <tr valign="top">
1062
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1063
                <td class="forminp">
1064
1065
                    <?php _e('Width', 'geodirectory'); ?> <input
1066
                        name="<?php echo esc_attr($value['id']); ?>_width"
1067
                        id="<?php echo esc_attr($value['id']); ?>_width" type="text" size="3"
1068
                        value="<?php if ($size = get_option($value['id'] . '_width')) echo stripslashes($size); else echo $value['std']; ?>"/>
1069
1070
                    <?php _e('Height', 'geodirectory'); ?> <input
1071
                        name="<?php echo esc_attr($value['id']); ?>_height"
1072
                        id="<?php echo esc_attr($value['id']); ?>_height" type="text" size="3"
1073
                        value="<?php if ($size = get_option($value['id'] . '_height')) echo stripslashes($size); else echo $value['std']; ?>"/>
1074
1075
                    <label><?php _e('Hard Crop', 'geodirectory'); ?> <input
1076
                            name="<?php echo esc_attr($value['id']); ?>_crop"
1077
                            id="<?php echo esc_attr($value['id']); ?>_crop"
1078
                            type="checkbox" <?php if (get_option($value['id'] . '_crop') != '') checked(get_option($value['id'] . '_crop'), 1); else checked(1); ?> /></label>
1079
1080
                    <span class="description"><?php echo $value['desc'] ?></span></td>
1081
                </tr><?php
1082
                break;
1083
            case 'select':
1084
                $option_value = get_option($value['id']);
1085
                $option_value = !empty($option_value) ? stripslashes_deep($option_value) : $option_value;
1086
                ?>
1087
                <tr valign="top">
1088
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1089
                <td class="forminp"><select name="<?php echo esc_attr($value['id']); ?>"
1090
                                            id="<?php echo esc_attr($value['id']); ?>"
1091
                                            style="<?php echo esc_attr($value['css']); ?>"
1092
                                            class="<?php if (isset($value['class'])) echo $value['class']; ?>"
1093
                                            option-ajaxchosen="false">
1094
                        <?php
1095
                        foreach ($value['options'] as $key => $val) {
1096
                            $geodir_select_value = '';
1097
                            if ($option_value != '') {
1098
                                if ($option_value != '' && $option_value == $key)
1099
                                    $geodir_select_value = ' selected="selected" ';
1100
                            } else {
1101
                                if ($value['std'] == $key)
1102
                                    $geodir_select_value = ' selected="selected" ';
1103
                            }
1104
                            ?>
1105
                            <option
1106
                                value="<?php echo esc_attr($key); ?>" <?php echo $geodir_select_value; ?> ><?php echo ucfirst($val) ?></option>
1107
                        <?php
1108
                        }
1109
                        ?>
1110
                    </select> <span class="description"><?php echo $value['desc'] ?></span>
1111
                </td>
1112
                </tr><?php
1113
                break;
1114
1115
            case 'multiselect':
1116
                $option_values = get_option($value['id']);
1117
                if ($option_values === '' && !empty($value['std']) && is_array($value['std'])) {
1118
                   $option_values = $value['std'];
1119
                }
1120
                $option_values = !empty($option_values) ? stripslashes_deep($option_values) : $option_values;
1121
                ?>
1122
                <tr valign="top">
1123
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1124
                <td class="forminp"><select multiple="multiple" name="<?php echo esc_attr($value['id']); ?>[]"
1125
                                            id="<?php echo esc_attr($value['id']); ?>"
1126
                                            style="<?php echo esc_attr($value['css']); ?>"
1127
                                            class="<?php if (isset($value['class'])) echo $value['class']; ?>"
1128
                                            data-placeholder="<?php if (isset($value['placeholder_text'])) echo $value['placeholder_text'];?>"
1129
                                            option-ajaxchosen="false">
1130
                        <?php
1131
                        foreach ($value['options'] as $key => $val) {
1132
                            if (strpos($key, 'optgroup_start-') === 0) {
1133
                                ?><optgroup label="<?php echo ucfirst($val); ?>"><?php
1134
                            } else if (strpos($key, 'optgroup_end-') === 0) {
1135
                                ?></optgroup><?php
1136
                            } else {
1137
                                ?>
1138
                                <option
1139
                                    value="<?php echo esc_attr($key); ?>" <?php selected(true, (is_array($option_values) && in_array($key, $option_values)));?>><?php echo ucfirst($val) ?></option>
1140
                            <?php
1141
                            }
1142
                        }
1143
                        ?>
1144
                    </select> <span class="description"><?php echo $value['desc'] ?></span>
1145
                </td>
1146
                </tr><?php
1147
                break;
1148
            case 'file':
1149
                ?>
1150
                <tr valign="top">
1151
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1152
                <td class="forminp">
1153
                    <input type="file" name="<?php echo esc_attr($value['id']); ?>"
1154
                           id="<?php echo esc_attr($value['id']); ?>" style="<?php echo esc_attr($value['css']); ?>"
1155
                           class="<?php if (isset($value['class'])) echo $value['class']; ?>"/>
1156
                    <?php if (get_option($value['id'])) { ?>
1157
                        <input type="hidden" name="<?php echo esc_attr($value['id']); ?>_remove"
1158
                               id="<?php echo esc_attr($value['id']); ?>_remove" value="0">
1159
                        <span class="description"> <a
1160
                                href="<?php echo get_option($value['id']); ?>"
1161
                                target="_blank"><?php echo get_option($value['id']); ?></a> <i
1162
                                title="<?php _e('remove file (set to empty)', 'geodirectory'); ?>"
1163
                                onclick="jQuery('#<?php echo esc_attr($value['id']); ?>_remove').val('1'); jQuery( this ).parent().text('<?php _e('save to remove file', 'geodirectory'); ?>');"
1164
                                class="fa fa-times gd-remove-file"></i></span>
1165
1166
                    <?php } ?>
1167
                </td>
1168
                </tr><?php
1169
                break;
1170
            case 'map_default_settings' :
1171
                ?>
1172
1173
                <tr valign="top">
1174
                    <th class="titledesc" width="40%"><?php _e('Default map language', 'geodirectory');?></th>
1175
                    <td width="60%">
1176
                        <select name="geodir_default_map_language" style="width:60%">
1177
                            <?php
1178
                            $arr_map_langages = array(
1179
                                'ar' => __('ARABIC', 'geodirectory'),
1180
                                'eu' => __('BASQUE', 'geodirectory'),
1181
                                'bg' => __('BULGARIAN', 'geodirectory'),
1182
                                'bn' => __('BENGALI', 'geodirectory'),
1183
                                'ca' => __('CATALAN', 'geodirectory'),
1184
                                'cs' => __('CZECH', 'geodirectory'),
1185
                                'da' => __('DANISH', 'geodirectory'),
1186
                                'de' => __('GERMAN', 'geodirectory'),
1187
                                'el' => __('GREEK', 'geodirectory'),
1188
                                'en' => __('ENGLISH', 'geodirectory'),
1189
                                'en-AU' => __('ENGLISH (AUSTRALIAN)', 'geodirectory'),
1190
                                'en-GB' => __('ENGLISH (GREAT BRITAIN)', 'geodirectory'),
1191
                                'es' => __('SPANISH', 'geodirectory'),
1192
                                'eu' => __('BASQUE', 'geodirectory'),
1193
                                'fa' => __('FARSI', 'geodirectory'),
1194
                                'fi' => __('FINNISH', 'geodirectory'),
1195
                                'fil' => __('FILIPINO', 'geodirectory'),
1196
                                'fr' => __('FRENCH', 'geodirectory'),
1197
                                'gl' => __('GALICIAN', 'geodirectory'),
1198
                                'gu' => __('GUJARATI', 'geodirectory'),
1199
                                'hi' => __('HINDI', 'geodirectory'),
1200
                                'hr' => __('CROATIAN', 'geodirectory'),
1201
                                'hu' => __('HUNGARIAN', 'geodirectory'),
1202
                                'id' => __('INDONESIAN', 'geodirectory'),
1203 2
                                'it' => __('ITALIAN', 'geodirectory'),
1204
                                'iw' => __('HEBREW', 'geodirectory'),
1205 2
                                'ja' => __('JAPANESE', 'geodirectory'),
1206 2
                                'kn' => __('KANNADA', 'geodirectory'),
1207
                                'ko' => __('KOREAN', 'geodirectory'),
1208
                                'lt' => __('LITHUANIAN', 'geodirectory'),
1209
                                'lv' => __('LATVIAN', 'geodirectory'),
1210
                                'ml' => __('MALAYALAM', 'geodirectory'),
1211
                                'mr' => __('MARATHI', 'geodirectory'),
1212
                                'nl' => __('DUTCH', 'geodirectory'),
1213
                                'no' => __('NORWEGIAN', 'geodirectory'),
1214
                                'pl' => __('POLISH', 'geodirectory'),
1215
                                'pt' => __('PORTUGUESE', 'geodirectory'),
1216
                                'pt-BR' => __('PORTUGUESE (BRAZIL)', 'geodirectory'),
1217
                                'pt-PT' => __('PORTUGUESE (PORTUGAL)', 'geodirectory'),
1218
                                'ro' => __('ROMANIAN', 'geodirectory'),
1219
                                'ru' => __('RUSSIAN', 'geodirectory'),
1220
                                'ru' => __('RUSSIAN', 'geodirectory'),
1221
                                'sk' => __('SLOVAK', 'geodirectory'),
1222
                                'sl' => __('SLOVENIAN', 'geodirectory'),
1223
                                'sr' => __('SERBIAN', 'geodirectory'),
1224
                                'sv' => __('	SWEDISH', 'geodirectory'),
1225
                                'tl' => __('TAGALOG', 'geodirectory'),
1226
                                'ta' => __('TAMIL', 'geodirectory'),
1227
                                'te' => __('TELUGU', 'geodirectory'),
1228
                                'th' => __('THAI', 'geodirectory'),
1229
                                'tr' => __('TURKISH', 'geodirectory'),
1230
                                'uk' => __('UKRAINIAN', 'geodirectory'),
1231
                                'vi' => __('VIETNAMESE', 'geodirectory'),
1232
                                'zh-CN' => __('CHINESE (SIMPLIFIED)', 'geodirectory'),
1233
                                'zh-TW' => __('CHINESE (TRADITIONAL)', 'geodirectory'),
1234
                            );
1235
                            $geodir_default_map_language = get_option('geodir_default_map_language');
1236
                            if (empty($geodir_default_map_language))
1237
                                $geodir_default_map_language = 'en';
1238
                            foreach ($arr_map_langages as $language_key => $language_txt) {
1239
                                if (!empty($geodir_default_map_language) && $language_key == $geodir_default_map_language)
1240
                                    $geodir_default_language_selected = "selected='selected'";
1241
                                else
1242
                                    $geodir_default_language_selected = '';
1243
1244 1
                                ?>
1245
                                <option
1246 1
                                    value="<?php echo $language_key?>" <?php echo $geodir_default_language_selected; ?>><?php echo $language_txt; ?></option>
1247 1
1248 1
                            <?php }
1249 1
                            ?>
1250 1
                        </select>
1251 1
                    </td>
1252 1
                </tr>
1253 1
1254 1
                <tr valign="top">
1255 1
                    <th class="titledesc"
1256 1
                        width="40%"><?php _e('Default post type search on map', 'geodirectory');?></th>
1257 1
                    <td width="60%">
1258 1
                        <select name="geodir_default_map_search_pt" style="width:60%">
1259 1
                            <?php
1260 1
                            $post_types = geodir_get_posttypes('array');
1261
                            $geodir_default_map_search_pt = get_option('geodir_default_map_search_pt');
1262 1
                            if (empty($geodir_default_map_search_pt))
1263 1
                                $geodir_default_map_search_pt = 'gd_place';
1264 1
                            if (is_array($post_types)) {
1265 1
                                foreach ($post_types as $key => $post_types_obj) {
1266
                                    if (!empty($geodir_default_map_search_pt) && $key == $geodir_default_map_search_pt)
1267 1
                                        $geodir_search_pt_selected = "selected='selected'";
1268
                                    else
1269 1
                                        $geodir_search_pt_selected = '';
1270 1
1271
                                    ?>
1272 1
                                    <option
1273 1
                                        value="<?php echo $key?>" <?php echo $geodir_search_pt_selected; ?>><?php echo $post_types_obj['labels']['singular_name']; ?></option>
1274
1275 1
                                <?php }
1276 1
1277 1
                            }
1278 1
1279 1
                            ?>
1280
                        </select>
1281 1
                    </td>
1282
                </tr>
1283 1
1284 1
                <?php
1285
                break;
1286
1287
            case 'map':
1288
                ?>
1289
                <tr valign="top">
1290
                    <td class="forminp">
1291
                        <?php
1292
                        global $post_cat, $cat_display;
1293 1
                        $post_types = geodir_get_posttypes('object');
1294 1
                        $cat_display = 'checkbox';
1295
                        $gd_post_types = get_option('geodir_exclude_post_type_on_map');
1296 1
                        $gd_cats = get_option('geodir_exclude_cat_on_map');
1297
                        $gd_cats_upgrade = (int)get_option('geodir_exclude_cat_on_map_upgrade');
1298 1
                        $count = 1;
1299 1
                        ?>
1300
                        <table width="70%" class="widefat">
1301 1
                            <thead>
1302
                            <tr>
1303 1
                                <th><b><?php echo DESIGN_POST_TYPE_SNO; ?></b></th>
1304 1
                                <th><b><?php echo DESIGN_POST_TYPE; ?></b></th>
1305 1
                                <th><b><?php echo DESIGN_POST_TYPE_CAT; ?></b></th>
1306 1
                            </tr>
1307 1
                            <?php
1308
                            $gd_categs = $gd_cats;
1309
                            foreach ($post_types as $key => $post_types_obj) :
0 ignored issues
show
Bug introduced by
The expression $post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1310
                                $checked = is_array($gd_post_types) && in_array($key, $gd_post_types) ? 'checked="checked"' : '';
1311
                                $gd_taxonomy = geodir_get_taxonomies($key);
1312 View Code Duplication
                                if ($gd_cats_upgrade) {
1313
                                    $gd_cat_taxonomy = isset($gd_taxonomy[0]) ? $gd_taxonomy[0] : '';
1314
                                    $gd_cats = isset($gd_categs[$gd_cat_taxonomy]) ? $gd_categs[$gd_cat_taxonomy] : array();
1315 1
                                    $gd_cats = !empty($gd_cats) && is_array($gd_cats) ? array_unique($gd_cats) : array();
1316 1
                                }
1317
                                $post_cat = implode(',', $gd_cats);
1318 1
                                $gd_taxonomy_list = geodir_custom_taxonomy_walker($gd_taxonomy);
0 ignored issues
show
Documentation introduced by
$gd_taxonomy is of type array|boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1319 1
                                ?>
1320
                                <tr>
1321
                                    <td valign="top" width="5%"><?php echo $count; ?></td>
1322
                                    <td valign="top" width="25%" id="td_post_types"><input type="checkbox"
1323
                                                                                           name="home_map_post_types[]"
1324
                                                                                           id="<?php echo esc_attr($value['id']); ?>"
1325
                                                                                           value="<?php echo $key; ?>"
1326
                                                                                           class="map_post_type" <?php echo $checked;?> />
1327 1
                                        <?php echo $post_types_obj->labels->singular_name; ?></td>
1328 1
                                    <td width="40%">
1329
                                        <div class="home_map_category" style="overflow:auto;width:200px;height:100px;"
1330
                                             id="<?php echo $key; ?>"><?php echo $gd_taxonomy_list; ?></div>
1331
                                    </td>
1332
                                </tr>
1333
                                <?php $count++; endforeach; ?>
1334
                            </thead>
1335
                        </table>
1336 1
                        <p><?php _e('Note: Tick respective post type or categories which you want to hide from home page map widget.', 'geodirectory')?></p>
1337 1
                    </td>
1338 1
                </tr>
1339
                <?php
1340
                break;
1341
1342
            case 'checkbox' :
1343
1344
                if (!isset($value['checkboxgroup']) || (isset($value['checkboxgroup']) && $value['checkboxgroup'] == 'start')) :
1345
                    ?>
1346
                    <tr valign="top">
1347
                    <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1348 1
                    <td class="forminp">
1349 1
                <?php
1350
                endif;
1351
1352
                ?>
1353 1
                <fieldset>
1354
                    <legend class="screen-reader-text"><span><?php echo $value['name'] ?></span></legend>
1355 1
                    <label for="<?php echo $value['id'] ?>">
1356
                        <input name="<?php echo esc_attr($value['id']); ?>" id="<?php echo esc_attr($value['id']); ?>"
1357
                               type="checkbox" value="1" <?php checked(get_option($value['id']), true); ?> />
1358
                        <?php echo $value['desc'] ?></label><br>
1359
                </fieldset>
1360
                <?php
1361
1362
                if (!isset($value['checkboxgroup']) || (isset($value['checkboxgroup']) && $value['checkboxgroup'] == 'end')) :
1363
                    ?>
1364
                    </td>
1365 1
                    </tr>
1366 1
                <?php
1367
                endif;
1368
1369
                break;
1370 1
1371
            case 'radio' :
1372 1
1373 View Code Duplication
                if (!isset($value['radiogroup']) || (isset($value['radiogroup']) && $value['radiogroup'] == 'start')) :
1374
                    ?>
1375
                    <tr valign="top">
1376
                    <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1377
                    <td class="forminp">
1378 1
                <?php
1379
                endif;
1380 1
1381
                ?>
1382
                <fieldset>
1383
                    <legend class="screen-reader-text"><span><?php echo $value['name'] ?></span></legend>
1384
                    <label for="<?php echo $value['id'];?>">
1385
                        <input name="<?php echo esc_attr($value['id']); ?>"
1386
                               id="<?php echo esc_attr($value['id'] . $value['value']); ?>" type="radio"
1387
                               value="<?php echo $value['value'] ?>" <?php if (get_option($value['id']) == $value['value']) {
1388 1
                            echo 'checked="checked"';
1389 1
                        }elseif(get_option($value['id'])=='' && $value['std']==$value['value']){echo 'checked="checked"';} ?> />
1390
                        <?php echo $value['desc']; ?></label><br>
1391
                </fieldset>
1392
                <?php
1393
1394 View Code Duplication
                if (!isset($value['radiogroup']) || (isset($value['radiogroup']) && $value['radiogroup'] == 'end')) :
1395
                    ?>
1396
                    </td>
1397
                    </tr>
1398 1
                <?php
1399 1
                endif;
1400
1401
                break;
1402
1403
            case 'textarea':
1404
                ?>
1405
                <tr valign="top">
1406
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1407
                <td class="forminp">
1408
                    <textarea
1409
                        <?php if (isset($value['args'])) echo $value['args'] . ' '; ?>name="<?php echo esc_attr($value['id']); ?>"
1410
                        id="<?php echo esc_attr($value['id']); ?>"
1411
                        <?php if(isset($value['placeholder'])){?>placeholder="<?php echo esc_attr($value['placeholder']); ?>"<?php }?>
1412
                        style="<?php echo esc_attr($value['css']); ?>"><?php if (get_option($value['id'])) echo esc_textarea(stripslashes(get_option($value['id']))); else echo esc_textarea($value['std']); ?></textarea><span
1413
                        class="description"><?php echo $value['desc'] ?></span>
1414
1415
                </td>
1416
                </tr><?php
1417
                break;
1418
1419
            case 'editor':
1420
                ?>
1421
                <tr valign="top">
1422
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1423 1
                <td class="forminp"><?php
1424 1
                    if (get_option($value['id']))
1425 1
                        $content = stripslashes(get_option($value['id']));
1426
                    else
1427
                        $content = $value['std'];
1428
1429
                    $editor_settings = array('media_buttons' => false, 'textarea_rows' => 10);
1430
1431
                    wp_editor($content, esc_attr($value['id']), $editor_settings);
1432
1433
                    ?> <span class="description"><?php echo $value['desc'] ?></span>
1434
1435 1
                </td>
1436 1
                </tr><?php
1437 1
                break;
1438 1
1439 1
            case 'single_select_page' :
1440 1
                // WPML
1441 1
				$switch_lang = false;
1442 1
				$disabled = '';
1443
				if (geodir_is_wpml() && isset($_REQUEST['tab']) && $_REQUEST['tab'] == 'permalink_settings') {
1444
					global $sitepress;
1445
					
1446
					$default_lang = $sitepress->get_default_language();
1447
					$current_lang = $sitepress->get_current_language();
1448 1
					
1449
					if ($current_lang != 'all' && $current_lang != $default_lang) {
1450
						$disabled = "disabled='disabled'";
1451
						$switch_lang = $current_lang;
1452
						$sitepress->switch_lang('all', true);
1453 1
					}
1454
				}
1455 1
				//
1456 1
				$page_setting = (int)get_option($value['id']);
1457 1
1458
                $args = array('name' => $value['id'],
1459
                    'id' => $value['id'],
1460 1
                    'sort_column' => 'menu_order',
1461
                    'sort_order' => 'ASC',
1462
                    'show_option_none' => ' ',
1463
                    'class' => $value['class'],
1464
                    'echo' => false,
1465
                    'selected' => $page_setting);
1466
1467
                if (isset($value['args'])) $args = wp_parse_args($value['args'], $args);
1468
1469
                ?>
1470
                <tr valign="top" class="single_select_page">
1471 1
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1472 1
                <td class="forminp">
1473
                    <?php echo str_replace(' id=', " data-placeholder='" . __('Select a page...', 'geodirectory') . "' style='" . $value['css'] . "' class='" . $value['class'] . "' " . $disabled . " id=", wp_dropdown_pages($args)); ?>
1474 1
                    <span class="description"><?php echo $value['desc'] ?></span>
1475
                </td>
1476
                </tr><?php
1477
				if ($switch_lang) {
1478
					$sitepress->switch_lang($switch_lang, true);
0 ignored issues
show
Bug introduced by
The variable $sitepress does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1479
				}
1480
                break;
1481
            case 'single_select_country' :
1482 1
                $country_setting = (string)get_option($value['id']);
1483
                if (strstr($country_setting, ':')) :
1484
                    $country = current(explode(':', $country_setting));
1485
                    $state = end(explode(':', $country_setting));
0 ignored issues
show
Bug introduced by
explode(':', $country_setting) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
1486
                else :
1487 1
                    $country = $country_setting;
1488 1
                    $state = '*';
1489
                endif;
1490
                ?>
1491
                <tr valign="top">
1492
                <th scope="rpw" class="titledesc"><?php echo $value['name'] ?></th>
1493
                <td class="forminp"><select name="<?php echo esc_attr($value['id']); ?>"
1494
                                            style="<?php echo esc_attr($value['css']); ?>"
1495
                                            data-placeholder="<?php _e('Choose a country&hellip;', 'geodirectory'); ?>"
1496
                                            title="Country" class="chosen_select">
1497
                        <?php echo $geodirectory->countries->country_dropdown_options($country, $state); ?>
1498
                    </select> <span class="description"><?php echo $value['desc'] ?></span>
1499
                </td>
1500
                </tr><?php
1501
                break;
1502
            case 'multi_select_countries' :
1503
                $countries = $geodirectory->countries->countries;
1504
                asort($countries);
1505
                $selections = (array)get_option($value['id']);
1506
                ?>
1507
                <tr valign="top">
1508
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1509 1
                <td class="forminp">
1510 1
                    <select multiple="multiple" name="<?php echo esc_attr($value['id']); ?>[]" style="width:450px;"
1511
                            data-placeholder="<?php _e('Choose countries&hellip;', 'geodirectory'); ?>"
1512
                            title="Country" class="chosen_select">
1513
                        <?php
1514
                        if ($countries) foreach ($countries as $key => $val) :
0 ignored issues
show
Bug Best Practice introduced by
The expression $countries of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1515
                            echo '<option value="' . $key . '" ' . selected(in_array($key, $selections), true, false) . '>' . $val . '</option>';
1516
                        endforeach;
1517
                        ?>
1518
                    </select>
1519 1
                </td>
1520 1
                </tr>
1521 1
1522 1
                <?php
1523 1
1524 1
                break;
1525 1
1526 1
            case 'google_analytics' :
1527 1
                $selections = (array)get_option($value['id']);
0 ignored issues
show
Unused Code introduced by
$selections is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1528 1
                    ?>
1529 1
                    <tr valign="top">
1530 1
                        <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1531 1
                        <td class="forminp">
1532 1
1533 1
1534 1
                            <?php
1535 1
1536 1
                            $oAuthURL = "https://accounts.google.com/o/oauth2/auth?";
1537 1
                            $scope = "scope=https://www.googleapis.com/auth/analytics.readonly";
1538 1
                            $state = "&state=123";//any string
1539 1
                            $redirect_uri = "&redirect_uri=" . admin_url('admin-ajax.php') . "?action=geodir_ga_callback";
1540 1
                            $response_type = "&response_type=code";
1541 1
                            $client_id = "&client_id=".get_option('geodir_ga_client_id');
1542 1
                            $access_type = "&access_type=offline";
1543 1
                            $approval_prompt = "&approval_prompt=force";
1544 1
1545 1
                            $auth_url = $oAuthURL . $scope . $state . $redirect_uri . $response_type . $client_id . $access_type . $approval_prompt;
0 ignored issues
show
Unused Code introduced by
$auth_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1546 1
1547 1
1548 1
                            if (get_option('geodir_ga_auth_token')) {
1549 1
                                ?>
1550 1
                                <span class="button-primary"
1551 1
                                      onclick="window.open('<?php echo  geodir_ga_activation_url();?>', 'activate','width=700, height=600, menubar=0, status=0, location=0, toolbar=0')"><?php _e('Re-authorize', 'geodirectory'); ?></span>
1552 1
                                <span
1553 1
                                    style="color: green; font-weight: bold;"><?php _e('Authorized', 'geodirectory'); ?></span>
1554 1
                            <?php
1555 1
                            } else {
1556 1
                                ?>
1557 1
                                <span class="button-primary"
1558 1
                                      onclick="window.open('<?php echo  geodir_ga_activation_url();?>', 'activate','width=700, height=600, menubar=0, status=0, location=0, toolbar=0')"><?php _e('Authorize', 'geodirectory');?></span>
1559 1
                            <?php
1560 1
                            }
1561 1
                            ?>
1562 1
                        </td>
1563 1
                    </tr>
1564 1
1565 1
                <?php
1566 1
1567 1
1568 1
                break;
1569 1
1570 1
            case 'field_seperator' :
1571 1
1572 1
                ?>
1573 1
                <tr valign="top">
1574 1
                    <td colspan="2" class="forminp geodir_line_seperator"></td>
1575 1
                </tr>
1576 1
                <?php
1577 1
1578 1
                break;
1579 1
1580 1
        endswitch;
1581
1582 1
    endforeach;
1583
1584
    if ($first_title === false) {
1585
        echo "</div>";
1586
    }
1587
1588
    ?>
1589
1590
    <script type="text/javascript">
1591
1592
1593
        jQuery(document).ready(function () {
1594
1595
            jQuery('.geodir_option_tabs').each(function (ele) {
1596
                jQuery('#geodir_oiption_tabs').append(jQuery(this));
1597
            });
1598
1599
1600 1
            jQuery('.geodir_option_tabs').removeClass('gd-tab-active');
1601 1
            jQuery('.geodir_option_tabs:first').addClass('gd-tab-active');
1602 1
1603 1
            jQuery('.gd-content-heading').hide();
1604 1
            jQuery('.gd-content-heading:first').show();
1605 1
            jQuery('.geodir_option_tabs').bind('click', function () {
1606 1
                var tab_id = jQuery(this).attr('id');
1607 1
1608
                if (tab_id == 'dummy_data_settings') {
1609
                    jQuery('p .button-primary').hide();
1610
                } else if (tab_id == 'csv_upload_settings') {
1611
                    jQuery('p .button-primary').hide();
1612
                } else {
1613
                    jQuery('.button-primary').show();
1614
                }
1615
1616
                if (jQuery('#sub_' + tab_id + ' div').hasClass('geodir_auto_install'))
1617 1
                    jQuery('p .button-primary').hide();
1618
1619
                jQuery('.geodir_option_tabs').removeClass('gd-tab-active');
1620
                jQuery(this).addClass('gd-tab-active');
1621
                jQuery('.gd-content-heading').hide();
1622
                jQuery('#sub_' + tab_id).show();
1623
                jQuery('.active_tab').val(tab_id);
1624
                jQuery("select.chosen_select").trigger("chosen:updated"); //refresh chosen
1625 1
            });
1626
1627 1
            <?php if (isset($_REQUEST['active_tab']) && $_REQUEST['active_tab'] != '') { ?>
1628
            jQuery('.geodir_option_tabs').removeClass('gd-tab-active');
1629
            jQuery('#<?php echo sanitize_text_field($_REQUEST['active_tab']);?>').addClass('gd-tab-active');
1630
            jQuery('.gd-content-heading').hide();
1631
            jQuery('#sub_<?php echo sanitize_text_field($_REQUEST['active_tab']);?>').show();
1632 1
            <?php } ?>
1633 1
        });
1634 1
    </script>
1635 1
<?php
1636 1
}
1637 1
1638 1
/**
1639
 * Prints post information meta box content.
1640
 *
1641
 * @since 1.0.0
1642
 * @package GeoDirectory
1643
 * @global object $post The post object.
1644
 * @global int $post_id The post ID.
1645
 */
1646
function geodir_post_info_setting()
1647
{
1648 1
    global $post, $post_id;
1649 1
1650 1
    $post_type = get_post_type();
1651 1
1652 1
    $package_info = array();
1653 1
1654 1
    $package_info = geodir_post_package_info($package_info, $post, $post_type);
1655 1
    wp_nonce_field(plugin_basename(__FILE__), 'geodir_post_info_noncename');
1656 1
    echo '<div id="geodir_wrapper">';
1657 1
    /**
1658 1
     * Called before the GD custom fields are output in the wp-admin area.
1659
     *
1660
     * @since 1.0.0
1661
     * @see 'geodir_after_default_field_in_meta_box'
1662
     */
1663
    do_action('geodir_before_default_field_in_meta_box');
1664
    //geodir_get_custom_fields_html($package_info->pid,'default',$post_type);
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1665
    // to display all fields in one information box
1666
    geodir_get_custom_fields_html($package_info->pid, 'all', $post_type);
1667
    /**
1668
     * Called after the GD custom fields are output in the wp-admin area.
1669
     *
1670
     * @since 1.0.0
1671
     * @see 'geodir_before_default_field_in_meta_box'
1672
     */
1673
    do_action('geodir_after_default_field_in_meta_box');
1674
    echo '</div>';
1675
}
1676
1677
/**
1678
 * Prints additional information meta box content.
1679
 *
1680 1
 * @since 1.0.0
1681
 * @package GeoDirectory
1682 1
 * @global object $post The post object.
1683
 * @global int $post_id The post ID.
1684 1
 */
1685
function geodir_post_addinfo_setting()
1686
{
1687
    global $post, $post_id;
1688
1689
    $post_type = get_post_type();
1690 1
1691
    $package_info = array();
1692
1693
    $package_info = geodir_post_package_info($package_info, $post, $post_type);
1694
1695
    wp_nonce_field(plugin_basename(__FILE__), 'geodir_post_addinfo_noncename');
1696
    echo '<div id="geodir_wrapper">';
1697
    geodir_get_custom_fields_html($package_info->pid, 'custom', $post_type);
1698
    echo '</div>';
1699
1700
}
1701
1702 1
/**
1703
 * Prints Attachments meta box content.
1704
 *
1705
 * @since 1.0.0
1706
 * @package GeoDirectory
1707 1
 * @global object $post The post object.
1708
 * @global int $post_id The post ID.
1709 1
 */
1710
function geodir_post_attachments()
1711 1
{
1712
    global $post, $post_id;
1713 1
1714
    wp_nonce_field(plugin_basename(__FILE__), 'geodir_post_attachments_noncename');
1715
1716
    if (geodir_get_featured_image($post_id, 'thumbnail')) {
1717
        echo '<h4>' . __('Featured Image', 'geodirectory') . '</h4>';
1718
        geodir_show_featured_image($post_id, 'thumbnail');
1719 1
    }
1720
1721
    $image_limit = 0;
1722
1723
    ?>
1724
1725
1726
    <h5 class="form_title">
1727 View Code Duplication
        <?php if ($image_limit != 0 && $image_limit == 1) {
1728 1
            echo '<br /><small>(' . __('You can upload', 'geodirectory') . ' ' . $image_limit . ' ' . __('image with this package', 'geodirectory') . ')</small>';
1729
        } ?>
1730 View Code Duplication
        <?php if ($image_limit != 0 && $image_limit > 1) {
1731
            echo '<br /><small>(' . __('You can upload', 'geodirectory') . ' ' . $image_limit . ' ' . __('images with this package', 'geodirectory') . ')</small>';
1732
        } ?>
1733
        <?php if ($image_limit == 0) {
1734 1
            echo '<br /><small>(' . __('You can upload unlimited images with this package', 'geodirectory') . ')</small>';
1735
        } ?>
1736
    </h5>
1737
1738
1739 1
    <?php
1740
1741 1
    $curImages = geodir_get_images($post_id);
1742
    $place_img_array = array();
1743 1
1744
    if (!empty($curImages)):
1745
        foreach ($curImages as $p_img):
0 ignored issues
show
Bug introduced by
The expression $curImages of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1746
            $place_img_array[] = $p_img->src;
1747
        endforeach;
1748
    endif;
1749
1750
    if (!empty($place_img_array))
1751
        $curImages = implode(',', $place_img_array);
1752
1753
1754
    // adjust values here
1755
    $id = "post_images"; // this will be the name of form field. Image url(s) will be submitted in $_POST using this key. So if $id == �img1� then $_POST[�img1�] will have all the image urls
1756
1757 1
    $svalue = $curImages; // this will be initial value of the above form field. Image urls.
1758
1759 1
    $multiple = true; // allow multiple files upload
1760
1761
    $width = geodir_media_image_large_width(); // If you want to automatically resize all uploaded images then provide width here (in pixels)
1762
1763
    $height = geodir_media_image_large_height(); // If you want to automatically resize all uploaded images then provide height here (in pixels)
1764
1765
    ?>
1766
1767
    <div class="gtd-form_row clearfix" id="<?php echo $id; ?>dropbox" style="border:1px solid #999999;padding:5px;text-align:center;">
1768
        <input type="hidden" name="<?php echo $id; ?>" id="<?php echo $id; ?>" value="<?php echo $svalue; ?>"/>
1769
1770
        <div
1771
            class="plupload-upload-uic hide-if-no-js <?php if ($multiple): ?>plupload-upload-uic-multiple<?php endif; ?>"
1772
            id="<?php echo $id; ?>plupload-upload-ui">
1773
            <h4><?php _e('Drop files to upload', 'geodirectory');?></h4>
1774
            <input id="<?php echo $id; ?>plupload-browse-button" type="button"
1775
                   value="<?php _e('Select Files', 'geodirectory'); ?>" class="button"/>
1776
            <span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce($id . 'pluploadan'); ?>"></span>
1777
            <?php if ($width && $height): ?>
1778
                <span class="plupload-resize"></span>
1779 1
                <span class="plupload-width" id="plupload-width<?php echo $width; ?>"></span>
1780
                <span class="plupload-height" id="plupload-height<?php echo $height; ?>"></span>
1781 1
            <?php endif; ?>
1782 1
            <div class="filelist"></div>
1783 1
        </div>
1784
        <div class="plupload-thumbs <?php if ($multiple): ?>plupload-thumbs-multiple<?php endif; ?> clearfix"
1785
             id="<?php echo $id; ?>plupload-thumbs" style="border-top:1px solid #ccc; padding-top:10px;">
1786
        </div>
1787
        <span
1788
            id="upload-msg"><?php _e('Please drag &amp; drop the images to rearrange the order', 'geodirectory');?></span>
1789
        <span id="<?php echo $id; ?>upload-error" style="display:none"></span>
1790
    </div>
1791
1792
<?php
1793
1794
}
1795
1796 1
/**
1797
 * Updates custom table when post get updated.
1798 1
 *
1799 1
 * @since 1.0.0
1800 1
 * @package GeoDirectory
1801 1
 * @param int $post_ID The post ID.
1802 1
 * @param object $post_after Post object after the update.
1803 1
 * @param object $post_before Post object before the update.
1804 1
 */
1805 1
function geodir_action_post_updated($post_ID, $post_after, $post_before)
1806
{
1807 1
    $post_type = get_post_type($post_ID);
1808
1809
    if (isset($_POST['action']) && $_POST['action'] == 'inline-save') {
1810
        if ($post_type != '' && in_array($post_type, geodir_get_posttypes()) && !wp_is_post_revision($post_ID) && !empty($post_after->post_title) && $post_after->post_title != $post_before->post_title) {
1811
            geodir_save_post_meta($post_ID, 'post_title', $post_after->post_title);
1812
        }
1813
    }
1814
}
1815
1816
/**
1817 1
 * Add Listing published bcc option.
1818
 *
1819
 * WP Admin -> Geodirectory -> Notifications -> Site Bcc Options
1820 1
 *
1821 1
 * @since 1.0.0
1822
 * @package GeoDirectory
1823
 * @param array $settings The settings array.
1824
 * @return array
1825
 */
1826
function geodir_notification_add_bcc_option($settings)
1827
{
1828
    if (!empty($settings)) {
1829
        $new_settings = array();
1830
        foreach ($settings as $setting) {
1831
            if (isset($setting['id']) && $setting['id'] == 'site_bcc_options' && isset($setting['type']) && $setting['type'] == 'sectionend') {
1832
                $geodir_bcc_listing_published_yes = array(
1833
                    'name' => __('Listing published', 'geodirectory'),
1834
                    'desc' => __('Yes', 'geodirectory'),
1835
                    'id' => 'geodir_bcc_listing_published',
1836
                    'std' => 'yes',
1837
                    'type' => 'radio',
1838
                    'value' => '1',
1839
                    'radiogroup' => 'start'
1840
                );
1841
1842 1
                $geodir_bcc_listing_published_no = array(
1843
                    'name' => __('Listing published', 'geodirectory'),
1844
                    'desc' => __('No', 'geodirectory'),
1845
                    'id' => 'geodir_bcc_listing_published',
1846
                    'std' => 'yes',
1847
                    'type' => 'radio',
1848
                    'value' => '0',
1849
                    'radiogroup' => 'end'
1850
                );
1851
1852
                $new_settings[] = $geodir_bcc_listing_published_yes;
1853
                $new_settings[] = $geodir_bcc_listing_published_no;
1854
            }
1855
            $new_settings[] = $setting;
1856
        }
1857
        $settings = $new_settings;
1858
    }
1859
1860
    return $settings;
1861
}
1862
1863
1864
add_action('wp_ajax_get_gd_theme_compat_callback', 'get_gd_theme_compat_callback');
1865
1866 1
/**
1867 1
 * Exports theme compatibility data for given theme.
1868 1
 *
1869
 * @since 1.0.0
1870
 * @package GeoDirectory
1871
 * @global object $wpdb WordPress Database object.
1872
 */
1873
function get_gd_theme_compat_callback()
1874
{
1875
    global $wpdb;
1876
    $themes = get_option('gd_theme_compats');
1877
1878
    if (isset($_POST['theme']) && isset($themes[$_POST['theme']]) && !empty($themes[$_POST['theme']])) {
1879
        if (isset($_POST['export'])) {
1880
            echo json_encode(array($_POST['theme'] => $themes[$_POST['theme']]));
1881
        } else {
1882
            echo json_encode($themes[$_POST['theme']]);
1883
        }
1884
1885
    }
1886
1887
    die();
1888
}
1889
1890
add_action('wp_ajax_get_gd_theme_compat_import_callback', 'get_gd_theme_compat_import_callback');
1891
1892
/**
1893
 * Imports theme compatibility data for given theme.
1894
 *
1895
 * @since 1.0.0
1896
 * @package GeoDirectory
1897
 * @global object $wpdb WordPress Database object.
1898
 */
1899
function get_gd_theme_compat_import_callback()
1900
{
1901
    global $wpdb;
1902
    $themes = get_option('gd_theme_compats');
1903
    if (isset($_POST['theme']) && !empty($_POST['theme'])) {
1904
        $json = json_decode(stripslashes($_POST['theme']), true);
1905
        if (!empty($json) && is_array($json)) {
1906
            $key = sanitize_text_field(key($json));
1907
            $themes[$key] = $json[$key];
1908
            update_option('gd_theme_compats', $themes);
1909
            echo $key;
1910
            die();
1911
        }
1912
    }
1913
    echo '0';
1914
    die();
1915
}
1916
1917
1918
/**
1919
 * Sets theme compatibility options.
1920
 *
1921
 * @since 1.0.0
1922
 * @package GeoDirectory
1923
 * @global object $wpdb WordPress Database object.
1924 1
 */
1925
function gd_set_theme_compat()
1926
{
1927
    global $wpdb;
1928
    $theme = wp_get_theme();
1929
1930 View Code Duplication
    if ($theme->parent()) {
1931
        $theme_name = str_replace(" ", "_", $theme->parent()->get('Name'));
1932
    } else {
1933
        $theme_name = str_replace(" ", "_", $theme->get('Name'));
1934
    }
1935
1936 1
    $theme_compats = get_option('gd_theme_compats');
1937
    $current_compat = get_option('gd_theme_compat');
1938 1
    $current_compat = str_replace("_custom", "", $current_compat);
1939
1940 1
    if ($current_compat == $theme_name && strpos("_custom", get_option('gd_theme_compat')) !== false) {
1941 1
        return;
1942 1
    }// if already running correct compat then bail
1943
1944
    if (isset($theme_compats[$theme_name])) {// if there is a compat avail then set it
1945
        update_option('gd_theme_compat', $theme_name);
1946
        update_option('theme_compatibility_setting', $theme_compats[$theme_name]);
1947
1948
        // if there are default options to set then set them
1949
        if (isset($theme_compats[$theme_name]['geodir_theme_compat_default_options']) && !empty($theme_compats[$theme_name]['geodir_theme_compat_default_options'])) {
1950
1951
            foreach ($theme_compats[$theme_name]['geodir_theme_compat_default_options'] as $key => $val) {
1952
                update_option($key, $val);
1953
            }
1954
        }
1955
1956
    } else {
1957
        update_option('gd_theme_compat', '');
1958
        update_option('theme_compatibility_setting', '');
1959
    }
1960
1961
1962
}
1963
1964
1965
add_action('wp_loaded', 'gd_check_avada_compat');
1966
/**
1967
 * Function to check if Avada needs header.php replaced
1968
 *
1969
 * @since 1.0.0
1970
 * @package GeoDirectory
1971
 */
1972
function gd_check_avada_compat()
1973
{
1974
    if (function_exists('avada_load_textdomain') && !get_option('avada_nag')) {
1975
        add_action('admin_notices', 'gd_avada_compat_warning');
1976
    }
1977
}
1978
1979
1980
/**
1981
 * Displays Avada compatibility warning.
1982
 *
1983
 * @since 1.0.0
1984
 * @package GeoDirectory
1985
 */
1986
function gd_avada_compat_warning()
1987
{
1988
1989
    /*
1990
    $msg_type = error
1991
    $msg_type = updated fade
1992 1
    $msg_type = update-nag
1993
    */
1994
1995
    $plugin = 'avada-nag';
1996
    $timestamp = 'avada-nag1234';
1997
    $message = __('Welcome to GeoDirectory, please have a look <a href="https://docs.wpgeodirectory.com/category/getting-started/" target="_blank">here</a> to get started. :)', 'geodirectory');
1998
    echo '<div id="' . $timestamp . '"  class="error">';
1999
    echo '<span class="gd-remove-noti" onclick="gdRemoveANotification(\'' . $plugin . '\',\'' . $timestamp . '\');" ><i class="fa fa-times"></i></span>';
2000
    echo "<img class='gd-icon-noti' src='" . plugin_dir_url('') . "geodirectory/geodirectory-assets/images/favicon.ico' > ";
2001
    echo "<p>$message</p>";
2002
    echo "</div>";
2003
2004
    ?>
2005
    <script>
2006
        function gdRemoveANotification($plugin, $timestamp) {
2007
2008
            jQuery('#' + $timestamp).css("background-color", "red");
2009
            jQuery('#' + $timestamp).fadeOut("slow");
2010
            // This does the ajax request
2011
            jQuery.ajax({
2012
                url: ajaxurl,
2013
                type: 'POST',
2014
                data: {
2015
                    'action': 'geodir_avada_remove_notification',
2016
                    'plugin': $plugin,
2017
                    'timestamp': $timestamp
2018
                },
2019
                success: function (data) {
2020
                    // This outputs the result of the ajax request
2021
                    //alert(data);
2022
                },
2023
                error: function (errorThrown) {
2024
                    console.log(errorThrown);
2025
                }
2026
            });
2027
2028
        }
2029
    </script>
2030
    <style>
2031
        .gd-icon-noti {
2032
            float: left;
2033
            margin-top: 10px;
2034
            margin-right: 5px;
2035
        }
2036
2037
        .update-nag .gd-icon-noti {
2038
            margin-top: 2px;
2039
        }
2040
2041
        .gd-remove-noti {
2042
            float: right;
2043
            margin-top: -20px;
2044
            margin-right: -20px;
2045
            color: #FF0000;
2046
            cursor: pointer;
2047
        }
2048
2049
        .updated .gd-remove-noti, .error .gd-remove-noti {
2050
            float: right;
2051
            margin-top: -10px;
2052
            margin-right: -17px;
2053
            color: #FF0000;
2054
            cursor: pointer;
2055
        }
2056
2057
2058
    </style>
2059
<?php
2060
2061
}
2062
2063
2064
/**
2065
 * Removes Avada compatibility warning.
2066
 *
2067
 * @since 1.0.0
2068
 * @package GeoDirectory
2069
 */
2070
function geodir_avada_remove_notification()
2071
{
2072
    update_option('avada_nag', TRUE);
2073
2074
    // Always die in functions echoing ajax content
2075
    die();
2076
}
2077
2078
2079
add_action('wp_ajax_geodir_avada_remove_notification', 'geodir_avada_remove_notification');
2080
2081
/**
2082
 * Get the current post type in the WordPress admin
2083
 *
2084
 * @since 1.4.2
2085
 * @package GeoDirectory
2086
 *
2087
 * @global null|WP_Post $post Post object.
2088
 * @global string $typenow Post type.
2089
 * @global object|WP_Screen $current_screen Current screen object
2090
 *
2091
 * @return string Post type ex: gd_place
2092
 */
2093
function geodir_admin_current_post_type() {
2094
	global $post, $typenow, $current_screen;
2095
	
2096
	$post_type = NULL;
2097
    if (isset($_REQUEST['post']) && get_post_type($_REQUEST['post']))
2098
		$post_type = get_post_type($_REQUEST['post']);
2099
    elseif ($post && isset($post->post_type))
2100
		$post_type = $post->post_type;
2101
	elseif ($typenow)
2102
		$post_type = $typenow;
2103
	elseif ($current_screen && isset($current_screen->post_type))
2104
		$post_type = $current_screen->post_type;
2105
	elseif (isset($_REQUEST['post_type']))
2106
		$post_type = sanitize_key($_REQUEST['post_type']);
2107
2108
2109
	return $post_type;
2110
}
2111
2112
/**
2113
 * Fires before updating geodirectory admin settings.
2114
 *
2115
 * @since 1.4.2
2116
 * @package GeoDirectory
2117
 *
2118
 * @global object $sitepress Sitepress WPML object.
2119
 *
2120
 * @param string $current_tab Current tab in geodirectory settings.
2121
 * @param array  $geodir_settings Array of geodirectory settings.
2122
 */
2123
function geodir_before_update_options($current_tab, $geodir_settings) {
0 ignored issues
show
Unused Code introduced by
The parameter $geodir_settings is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2124
	$active_tab = isset($_REQUEST['active_tab']) ? trim($_REQUEST['active_tab']) : '';
2125
		
2126
	// Permalink settings
2127
	if ($current_tab == 'permalink_settings') {
2128
		$listing_prefix = isset($_POST['geodir_listing_prefix']) ? trim($_POST['geodir_listing_prefix']) : '';
2129
		$location_prefix = isset($_POST['geodir_location_prefix']) ? trim($_POST['geodir_location_prefix']) : '';
2130
		
2131
		// Don't allow same slug url for listing and location
2132
		if (geodir_strtolower($listing_prefix) == geodir_strtolower($location_prefix)) {
2133
			$redirect_url = admin_url('admin.php?page=geodirectory&tab=' . $current_tab . '&active_tab=' . $active_tab . '&msg=fail&gderr=21');
2134
        	wp_redirect($redirect_url);
2135
			exit;
2136
		}
2137
		
2138
		// Don't allow to update page settings on different language.
2139
		if (geodir_is_wpml()) {
2140
			global $sitepress;
2141
			$current_language = $sitepress->get_current_language();
2142
			$default_language = $sitepress->get_default_language();
2143
			
2144
			if ($current_language != 'all' && $current_language != $default_language) {
2145
				$redirect_url = admin_url('admin.php?page=geodirectory&tab=' . $current_tab . '&active_tab=' . $active_tab);
2146
				wp_redirect($redirect_url);
2147
				exit;
2148
			}
2149
		}
2150
	}
2151
}
2152
2153
2154
/**
2155
 * Removes the preview buttons from the wp-admin area for GD post types.
2156
 *
2157
 * This was removed as the preview page was causing bugs.
2158
 *
2159
 * @global string $post_type The current post type.
2160
 * @since 1.4.3
2161
 * @package GeoDirectory
2162
 */
2163 1
function geodir_hide_admin_preview_button() {
2164
    global $post_type;
2165 1
    $post_types = geodir_get_posttypes();
2166
    if(in_array($post_type, $post_types))
2167
        echo '<style type="text/css">#post-preview, #view-post-btn{display: none;}</style>';
2168
}
2169
add_action( 'admin_head-post-new.php', 'geodir_hide_admin_preview_button' );
2170 1
add_action( 'admin_head-post.php', 'geodir_hide_admin_preview_button' );
2171
2172
/**
2173
 * Add the tab in left sidebar menu fro import & export page.
2174
 *
2175
 * @since 1.4.6
2176
 * @package GeoDirectory
2177
 *
2178
 * @return array Array of tab data.
2179
 */
2180
function geodir_import_export_tab( $tabs ) {
2181
	$tabs['import_export'] = array( 'label' => __( 'Import & Export', 'geodirectory' ) );
2182
    return $tabs;
2183
}
2184
2185
/**
2186
 * Display the page to manage import/export categories/listings.
2187
 *
2188
 * @since 1.4.6
2189
 * @since 1.5.6 Option added to export max number listings per csv file.
2190
 * @package GeoDirectory
2191
 *
2192
 * @return string Html content.
2193
 */
2194
function geodir_import_export_page() {
2195
	$nonce = wp_create_nonce( 'geodir_import_export_nonce' );
2196
	$gd_cats_sample_csv = geodir_plugin_url() . '/geodirectory-assets/gd_sample_categories.csv';
2197
    /**
2198
     * Filter sample category data csv file url.
2199
     *
2200
     * @since 1.0.0
2201
     * @package GeoDirectory
2202
     *
2203
     * @param string $gd_cats_sample_csv Sample category data csv file url.
2204
     */
2205
	$gd_cats_sample_csv = apply_filters( 'geodir_export_cats_sample_csv', $gd_cats_sample_csv );
2206
	
2207
	$gd_posts_sample_csv = geodir_plugin_url() . '/geodirectory-assets/place_listing.csv';
2208
    /**
2209
     * Filter sample post data csv file url.
2210
     *
2211
     * @since 1.0.0
2212
     * @package GeoDirectory
2213
     *
2214
     * @param string $gd_posts_sample_csv Sample post data csv file url.
2215
     */
2216
    $gd_posts_sample_csv = apply_filters( 'geodir_export_posts_sample_csv', $gd_posts_sample_csv );
2217
	
2218
	$gd_posttypes = geodir_get_posttypes( 'array' );
2219
	
2220
	$gd_posttypes_option = '';
2221
	foreach ( $gd_posttypes as $gd_posttype => $row ) {
0 ignored issues
show
Bug introduced by
The expression $gd_posttypes of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2222
		$gd_posttypes_option .= '<option value="' . $gd_posttype . '" data-cats="' . (int)geodir_get_terms_count( $gd_posttype ) . '" data-posts="' . (int)geodir_get_posts_count( $gd_posttype ) . '">' . __( $row['labels']['name'], 'geodirectory' ) . '</option>';
2223
	}
2224
	wp_enqueue_script( 'jquery-ui-progressbar' );
2225
	
2226
	$gd_chunksize_options = array();
2227
	$gd_chunksize_options[100] = 100;
2228
	$gd_chunksize_options[200] = 200;
2229
	$gd_chunksize_options[500] = 500;
2230
	$gd_chunksize_options[1000] = 1000;
2231
	$gd_chunksize_options[2000] = 2000;
2232
	$gd_chunksize_options[5000] = 5000;
2233
	$gd_chunksize_options[10000] = 10000;
2234
	$gd_chunksize_options[20000] = 20000;
2235
	$gd_chunksize_options[50000] = 50000;
2236
	$gd_chunksize_options[100000] = 100000;
2237
	 
2238
	 /**
2239
     * Filter max entries per export csv file.
2240
     *
2241
     * @since 1.5.6
2242
     * @package GeoDirectory
2243
     *
2244
     * @param string $gd_chunksize_options Entries options.
2245
     */
2246
    $gd_chunksize_options = apply_filters( 'geodir_export_csv_chunksize_options', $gd_chunksize_options );
2247
	
2248
	$gd_chunksize_option = '';
2249
	foreach ($gd_chunksize_options as $value => $title) {
2250
		$gd_chunksize_option .= '<option value="' . $value . '" ' . selected($value, 5000, false) . '>' . $title . '</option>';
2251
	}
2252
	
2253
	$uploads = wp_upload_dir();
2254
?>
2255
</form>
2256
<div class="inner_content_tab_main gd-import-export">
2257
  <h3><?php _e( 'GD Import & Export CSV', 'geodirectory' ) ;?></h3>
2258
  <span class="description"><?php _e( 'Import & export csv for GD listings & categories.', 'geodirectory' ) ;?></span>
2259
  <div class="gd-content-heading">
2260
2261
  <?php
2262
    ini_set('max_execution_time', 999999);
2263
    $ini_max_execution_time_check = @ini_get( 'max_execution_time' );
2264
    ini_restore('max_execution_time');
2265
2266
    if($ini_max_execution_time_check != 999999){ // only show these setting to the user if we can't change the ini setting
2267
        ?>
2268
	<div id="gd_ie_reqs" class="metabox-holder">
2269
      <div class="meta-box-sortables ui-sortable">
2270
        <div class="postbox">
2271
          <h3 class="hndle"><span style='vertical-align:top;'><?php echo __( 'PHP Requirements for GD Import & Export CSV', 'geodirectory' );?></span></h3>
2272
          <div class="inside">
2273
            <span class="description"><?php echo __( 'Note: In case GD import & export csv not working for larger data then please check and configure following php settings.', 'geodirectory' );?></span>
2274
			<table class="form-table">
2275
				<thead>
2276
				  <tr>
2277
				  	<th><?php _e( 'PHP Settings', 'geodirectory' );?></th><th><?php _e( 'Current Value', 'geodirectory' );?></th><th><?php _e( 'Recommended Value', 'geodirectory' );?></th>
2278
				  </tr>
2279
				</thead>
2280
				<tbody>
2281
				  <tr>
2282
				  	<td>max_input_time</td><td><?php echo @ini_get( 'max_input_time' );?></td><td>3000</td>
2283 1
				  </tr>
2284 1
				  <tr>
2285
				  	<td>max_execution_time</td><td><?php  echo @ini_get( 'max_execution_time' );?></td><td>3000</td>
2286 1
				  </tr>
2287
				  <tr>
2288
				  	<td>memory_limit</td><td><?php echo @ini_get( 'memory_limit' );?></td><td>256M</td>
2289 1
				  </tr>
2290
				</tbody>
2291
		    </table>
2292 1
		  </div>
2293 1
		</div>
2294 1
	  </div>
2295
	</div>
2296 1
	<?php }?>
2297
	<div id="gd_ie_imposts" class="metabox-holder">
2298
      <div class="meta-box-sortables ui-sortable">
2299
        <div id="gd_ie_im_posts" class="postbox gd-hndle-pbox">
2300 1
          <button class="handlediv button-link" type="button"><span class="screen-reader-text"><?php _e( 'Toggle panel - GD Listings: Import CSV', 'geodirectory' );?></span><span aria-hidden="true" class="toggle-indicator"></span></button>
2301
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Listings: Import CSV', 'geodirectory' );?></span></h3>
2302
          <div class="inside">
2303
            <table class="form-table">
2304
				<tbody>
2305
				  <tr>
2306
					<td class="gd-imex-box">
2307
						<div class="gd-im-choices">
2308
						<p><input type="radio" value="update" name="gd_im_choicepost" id="gd_im_pchoice_u" /><label for="gd_im_pchoice_u"><?php _e( 'Update listing if post with post_id already exists.', 'geodirectory' );?></label></p>
2309
						<p><input type="radio" checked="checked" value="skip" name="gd_im_choicepost" id="gd_im_pchoice_s" /><label for="gd_im_pchoice_s"><?php _e( 'Ignore listing if post with post_id already exists.', 'geodirectory' );?></label></p>
2310
						</div>
2311
						<div class="plupload-upload-uic hide-if-no-js" id="gd_im_postplupload-upload-ui">
2312
							<input type="text" readonly="readonly" name="gd_im_post_file" class="gd-imex-file gd_im_post_file" id="gd_im_post" onclick="jQuery('#gd_im_postplupload-browse-button').trigger('click');" />
2313 1
							<input id="gd_im_postplupload-browse-button" type="button" value="<?php echo SELECT_UPLOAD_CSV; ?>" class="gd-imex-pupload button-primary" /><input type="button" value="<?php echo esc_attr( __( 'Download Sample CSV', 'geodirectory' ) );?>" class="button-secondary" name="gd_ie_imposts_sample" id="gd_ie_imposts_sample">
2314 1
						<input type="hidden" id="gd_ie_imposts_csv" value="<?php echo $gd_posts_sample_csv;?>" />
2315
							<?php
2316
							/**
2317
							 * Called just after the sample CSV download link.
2318 1
							 *
2319
							 * @since 1.0.0
2320
							 */
2321
							do_action('geodir_sample_csv_download_link');
2322
							?>
2323
							<span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce( 'gd_im_postpluploadan' ); ?>"></span>
2324
							<div class="filelist"></div>
2325
						</div>
2326
						<span id="gd_im_catupload-error" style="display:none"></span>
2327
						<span class="description"></span>
2328
						<div id="gd_importer" style="display:none">
2329
							<input type="hidden" id="gd_total" value="0"/>
2330
							<input type="hidden" id="gd_prepared" value="continue"/>
2331
							<input type="hidden" id="gd_processed" value="0"/>
2332
							<input type="hidden" id="gd_created" value="0"/>
2333
							<input type="hidden" id="gd_updated" value="0"/>
2334
							<input type="hidden" id="gd_skipped" value="0"/>
2335
							<input type="hidden" id="gd_invalid" value="0"/>
2336
							<input type="hidden" id="gd_invalid_addr" value="0"/>
2337
							<input type="hidden" id="gd_images" value="0"/>
2338
							<input type="hidden" id="gd_terminateaction" value="continue"/>
2339
						</div>
2340
						<div class="gd-import-progress" id="gd-import-progress" style="display:none">
2341
							<div class="gd-import-file"><b><?php _e("Import Data Status :", 'geodirectory');?> </b><font
2342
									id="gd-import-done">0</font> / <font id="gd-import-total">0</font>&nbsp;( <font
2343
									id="gd-import-perc">0%</font> )
2344
								<div class="gd-fileprogress"></div>
2345
							</div>
2346
						</div>
2347
						<div class="gd-import-msg" id="gd-import-msg" style="display:none">
2348
							<div id="message" class="message fade"></div>
2349
						</div>
2350
                    	<div class="gd-imex-btns" style="display:none;">
2351
                        	<input type="hidden" class="geodir_import_file" name="geodir_import_file" value="save"/>
2352
                        	<input onclick="gd_imex_PrepareImport(this, 'post')" type="button" value="<?php echo CSV_IMPORT_DATA; ?>" id="gd_import_data" class="button-primary" />
2353
                        	<input onclick="gd_imex_ContinueImport(this, 'post')" type="button" value="<?php _e( "Continue Import Data", 'geodirectory' );?>" id="gd_continue_data" class="button-primary" style="display:none"/>
2354
                        	<input type="button" value="<?php _e("Terminate Import Data", 'geodirectory');?>" id="gd_stop_import" class="button-primary" name="gd_stop_import" style="display:none" onclick="gd_imex_TerminateImport(this, 'post')"/>
2355
							<div id="gd_process_data" style="display:none">
2356
								<span class="spinner is-active" style="display:inline-block;margin:0 5px 0 5px;float:left"></span><?php _e("Wait, processing import data...", 'geodirectory');?>
2357
							</div>
2358
						</div>
2359
					</td>
2360
				  </tr>
2361
				</tbody>
2362
			</table>
2363
          </div>
2364
        </div>
2365
      </div>
2366
    </div>
2367
	<div id="gd_ie_excategs" class="metabox-holder">
2368
	  <div class="meta-box-sortables ui-sortable">
2369
		<div id="gd_ie_ex_posts" class="postbox gd-hndle-pbox">
2370
		  <button class="handlediv button-link" type="button"><span class="screen-reader-text"><?php _e( 'Toggle panel - Listings: Export CSV', 'geodirectory' );?></span><span aria-hidden="true" class="toggle-indicator"></span></button>
2371
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Listings: Export CSV', 'geodirectory' );?></span></h3>
2372
		  <div class="inside">
2373
			<table class="form-table">
2374
			  <tbody>
2375
				<tr>
2376
				  <td class="fld"><label for="gd_post_type">
2377
					<?php _e( 'Post Type:', 'geodirectory' );?>
2378
					</label></td>
2379
				  <td><select name="gd_post_type" id="gd_post_type" style="min-width:140px">
2380
					  <?php echo $gd_posttypes_option;?>
2381
					</select></td>
2382
				</tr>
2383
				<tr>
2384
					<td class="fld" style="vertical-align:top"><label for="gd_chunk_size"><?php _e( 'Max entries per csv file:', 'geodirectory' );?></label></td>
2385
					<td><select name="gd_chunk_size" id="gd_chunk_size" style="min-width:140px"><?php echo $gd_chunksize_option;?></select><span class="description"><?php _e( 'Please select the maximum number of entries per csv file (defaults to 5000, you might want to lower this to prevent memory issues on some installs)', 'geodirectory' );?></span></td>
2386
				</tr>
2387
                <tr class="gd-imex-dates">
2388
					<td class="fld"><label><?php _e( 'Published Date:', 'geodirectory' );?></label></td>
2389
					<td><label><span class="label-responsive"><?php _e( 'Start date:', 'geodirectory' );?></span><input type="text" id="gd_imex_start_date" name="gd_imex[start_date]" data-type="date" /></label><label><span class="label-responsive"><?php _e( 'End date:', 'geodirectory' );?></span><input type="text" id="gd_imex_end_date" name="gd_imex[end_date]" data-type="date" /></label></td>
2390
				</tr>
2391
				<tr>
2392
				  <td class="fld" style="vertical-align:top"><label>
2393
					<?php _e( 'Progress:', 'geodirectory' );?>
2394
					</label></td>
2395
				  <td><div id='gd_progressbar_box'>
2396
					  <div id="gd_progressbar" class="gd_progressbar">
2397
						<div class="gd-progress-label"></div>
2398
					  </div>
2399
					</div>
2400
					<p style="display:inline-block">
2401
					  <?php _e( 'Elapsed Time:', 'geodirectory' );?>
2402
					</p>
2403
					  
2404
					<p id="gd_timer" class="gd_timer">00:00:00</p></td>
2405
				</tr>
2406
				<tr class="gd-ie-actions">
2407
				  <td style="vertical-align:top"><input type="submit" value="<?php echo esc_attr( __( 'Export CSV', 'geodirectory' ) );?>" class="button-primary" name="gd_ie_exposts_submit" id="gd_ie_exposts_submit">
2408
				  </td>
2409
				  <td id="gd_ie_ex_files" class="gd-ie-files"></td>
2410
				</tr>
2411
			  </tbody>
2412
			</table>
2413
		  </div>
2414
		</div>
2415
	  </div>
2416
	</div>
2417
	<div id="gd_ie_imcategs" class="metabox-holder">
2418
      <div class="meta-box-sortables ui-sortable">
2419
        <div id="gd_ie_imcats" class="postbox gd-hndle-pbox">
2420
          <button class="handlediv button-link" type="button"><span class="screen-reader-text"><?php _e( 'Toggle panel - GD Categories: Import CSV', 'geodirectory' );?></span><span aria-hidden="true" class="toggle-indicator"></span></button>
2421
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Categories: Import CSV', 'geodirectory' );?></span></h3>
2422
          <div class="inside">
2423
            <table class="form-table">
2424
				<tbody>
2425
				  <tr>
2426
					<td class="gd-imex-box">
2427
						<div class="gd-im-choices">
2428
						<p><input type="radio" value="update" name="gd_im_choicecat" id="gd_im_cchoice_u" /><label for="gd_im_cchoice_u"><?php _e( 'Update item if item with cat_id/cat_slug already exists.', 'geodirectory' );?></label></p>
2429
						<p><input type="radio" checked="checked" value="skip" name="gd_im_choicecat" id="gd_im_cchoice_s" /><label for="gd_im_cchoice_s"><?php _e( 'Ignore item if item with cat_id/cat_slug already exists.', 'geodirectory' );?></label></p>
2430
						</div>
2431
						<div class="plupload-upload-uic hide-if-no-js" id="gd_im_catplupload-upload-ui">
2432
							<input type="text" readonly="readonly" name="gd_im_cat_file" class="gd-imex-file gd_im_cat_file" id="gd_im_cat" onclick="jQuery('#gd_im_catplupload-browse-button').trigger('click');" />
2433
							<input id="gd_im_catplupload-browse-button" type="button" value="<?php echo SELECT_UPLOAD_CSV; ?>" class="gd-imex-cupload button-primary" /><input type="button" value="<?php echo esc_attr( __( 'Download Sample CSV', 'geodirectory' ) );?>" class="button-secondary" name="gd_ie_imcats_sample" id="gd_ie_imcats_sample">
2434
						<input type="hidden" id="gd_ie_imcats_csv" value="<?php echo $gd_cats_sample_csv;?>" />
2435
						<?php
2436
						/**
2437
						 * Called just after the sample CSV download link.
2438
						 *
2439
						 * @since 1.0.0
2440
                         * @package GeoDirectory
2441
						 */
2442
						do_action('geodir_sample_cats_csv_download_link');
2443
						?>
2444
							<span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce( 'gd_im_catpluploadan' ); ?>"></span>
2445
							<div class="filelist"></div>
2446
						</div>
2447
						<span id="gd_im_catupload-error" style="display:none"></span>
2448
						<span class="description"></span>
2449
						<div id="gd_importer" style="display:none">
2450
							<input type="hidden" id="gd_total" value="0"/>
2451
							<input type="hidden" id="gd_prepared" value="continue"/>
2452
							<input type="hidden" id="gd_processed" value="0"/>
2453
							<input type="hidden" id="gd_created" value="0"/>
2454
							<input type="hidden" id="gd_updated" value="0"/>
2455
							<input type="hidden" id="gd_skipped" value="0"/>
2456
							<input type="hidden" id="gd_invalid" value="0"/>
2457
							<input type="hidden" id="gd_images" value="0"/>
2458
							<input type="hidden" id="gd_terminateaction" value="continue"/>
2459
						</div>
2460
						<div class="gd-import-progress" id="gd-import-progress" style="display:none">
2461
							<div class="gd-import-file"><b><?php _e("Import Data Status :", 'geodirectory');?> </b><font
2462
									id="gd-import-done">0</font> / <font id="gd-import-total">0</font>&nbsp;( <font
2463
									id="gd-import-perc">0%</font> )
2464
								<div class="gd-fileprogress"></div>
2465
							</div>
2466
						</div>
2467
						<div class="gd-import-msg" id="gd-import-msg" style="display:none">
2468
							<div id="message" class="message fade"></div>
2469
						</div>
2470
                    	<div class="gd-imex-btns" style="display:none;">
2471
                        	<input type="hidden" class="geodir_import_file" name="geodir_import_file" value="save"/>
2472
                        	<input onclick="gd_imex_PrepareImport(this, 'cat')" type="button" value="<?php echo CSV_IMPORT_DATA; ?>" id="gd_import_data" class="button-primary" />
2473
                        	<input onclick="gd_imex_ContinueImport(this, 'cat')" type="button" value="<?php _e( "Continue Import Data", 'geodirectory' );?>" id="gd_continue_data" class="button-primary" style="display:none"/>
2474
                        	<input type="button" value="<?php _e("Terminate Import Data", 'geodirectory');?>" id="gd_stop_import" class="button-primary" name="gd_stop_import" style="display:none" onclick="gd_imex_TerminateImport(this, 'cat')"/>
2475
							<div id="gd_process_data" style="display:none">
2476
								<span class="spinner is-active" style="display:inline-block;margin:0 5px 0 5px;float:left"></span><?php _e("Wait, processing import data...", 'geodirectory');?>
2477
							</div>
2478
						</div>
2479
					</td>
2480
				  </tr>
2481
				</tbody>
2482
			</table>
2483
          </div>
2484
        </div>
2485
      </div>
2486
    </div>
2487
	<div id="gd_ie_excategs" class="metabox-holder">
2488
      <div class="meta-box-sortables ui-sortable">
2489
        <div id="gd_ie_ex_cats" class="postbox gd-hndle-pbox">
2490
          <button class="handlediv button-link" type="button"><span class="screen-reader-text"><?php _e( 'Toggle panel - GD Categories: Export CSV', 'geodirectory' );?></span><span aria-hidden="true" class="toggle-indicator"></span></button>
2491
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Categories: Export CSV', 'geodirectory' );?></span></h3>
2492
          <div class="inside">
2493
            <table class="form-table">
2494
				<tbody>
2495
				  <tr>
2496
					<td class="fld"><label for="gd_post_type"><?php _e( 'Post Type:', 'geodirectory' );?></label></td>
2497
					<td><select name="gd_post_type" id="gd_post_type" style="min-width:140px"><?php echo $gd_posttypes_option;?></select></td>
2498
				  </tr>
2499
				   <tr>
2500
					<td class="fld" style="vertical-align:top"><label for="gd_chunk_size"><?php _e( 'Max entries per csv file:', 'geodirectory' );?></label></td>
2501
					<td><select name="gd_chunk_size" id="gd_chunk_size" style="min-width:140px"><?php echo $gd_chunksize_option;?></select><span class="description"><?php _e( 'Please select the maximum number of entries per csv file (defaults to 5000, you might want to lower this to prevent memory issues on some installs)', 'geodirectory' );?></span></td>
2502
				  </tr>
2503
				  <tr>
2504
					<td class="fld" style="vertical-align:top"><label><?php _e( 'Progress:', 'geodirectory' );?></label></td>
2505
					<td><div id='gd_progressbar_box'><div id="gd_progressbar" class="gd_progressbar"><div class="gd-progress-label"></div></div></div><p style="display:inline-block"><?php _e( 'Elapsed Time:', 'geodirectory' );?></p>&nbsp;&nbsp;<p id="gd_timer" class="gd_timer">00:00:00</p></td>
2506
				  </tr>
2507
				  <tr class="gd-ie-actions">
2508
					<td style="vertical-align:top">
2509
						<input type="submit" value="<?php echo esc_attr( __( 'Export CSV', 'geodirectory' ) );?>" class="button-primary" name="gd_ie_excats_submit" id="gd_ie_excats_submit">
2510
					</td>
2511
					<td id="gd_ie_ex_files" class="gd-ie-files"></td>
2512
				  </tr>
2513
				</tbody>
2514
			</table>
2515
          </div>
2516
        </div>
2517
      </div>
2518
    </div>
2519
	<?php
2520
	/**
2521
	 * Allows you to add more setting to the GD > Import & Export page.
2522
	 *
2523
	 * Called after the last setting on the GD > Import & Export page.
2524
	 * @since 1.4.6
2525
     * @package GeoDirectory
2526
	 *
2527
	 * @param array $gd_posttypes GD post types.
2528
     * @param array $gd_chunksize_options File chunk size options.
2529
     * @param string $nonce Wordpress security token for GD import & export.
2530
	 */
2531
	do_action( 'geodir_import_export', $gd_posttypes, $gd_chunksize_options, $nonce );
2532
	?>
2533
  </div>
2534
</div>
2535
<script type="text/javascript">
2536
var timoutC, timoutP, timoutL, timoutH;
2537 1
2538 1
function gd_imex_PrepareImport(el, type) {
2539
    var cont = jQuery(el).closest('.gd-imex-box');
2540
    var gd_prepared = jQuery('#gd_prepared', cont).val();
2541
    var uploadedFile = jQuery('#gd_im_' + type, cont).val();
2542
    jQuery('gd-import-msg', cont).hide();
2543
    if(gd_prepared == uploadedFile) {
2544
        gd_imex_ContinueImport(el, type);
2545
        jQuery('#gd_import_data', cont).attr('disabled', 'disabled');
2546
    } else {
2547
        jQuery.ajax({
2548
            url: ajaxurl,
2549
            type: "POST",
2550
            data: 'action=geodir_import_export&task=prepare_import&_pt=' + type + '&_file=' + uploadedFile + '&_nonce=<?php echo $nonce;?>',
2551 1
            dataType: 'json',
2552 1
            cache: false,
2553
            success: function(data) {
2554
                if(typeof data == 'object') {
2555
                    if(data.error) {
2556
                        jQuery('#gd-import-msg', cont).find('#message').removeClass('updated').addClass('error').html('<p>' + data.error + '</p>');
2557
                        jQuery('#gd-import-msg', cont).show();
2558
                    } else if(!data.error && typeof data.rows != 'undefined') {
2559
                        jQuery('#gd_total', cont).val(data.rows);
2560
                        jQuery('#gd_prepared', cont).val(uploadedFile);
2561 1
                        jQuery('#gd_processed', cont).val('0');
2562
                        jQuery('#gd_created', cont).val('0');
2563 1
                        jQuery('#gd_updated', cont).val('0');
2564
                        jQuery('#gd_skipped', cont).val('0');
2565
                        jQuery('#gd_invalid', cont).val('0');
2566
                        jQuery('#gd_images', cont).val('0');
2567
                        if(type == 'post') {
2568
                            jQuery('#gd_invalid_addr', cont).val('0');
2569
                        }
2570
                        gd_imex_StartImport(el, type);
2571
                    }
2572 1
                }
2573
            },
2574 1
            error: function(errorThrown) {
2575
                console.log(errorThrown);
2576 1
            }
2577 1
        });
2578 1
    }
2579 1
}
2580 1
2581
function gd_imex_StartImport(el, type) {
2582 1
    var cont = jQuery(el).closest('.gd-imex-box');
2583 1
2584 1
    var limit = 1;
2585 1
    var total = parseInt(jQuery('#gd_total', cont).val());
2586 1
    var total_processed = parseInt(jQuery('#gd_processed', cont).val());
2587 1
    var uploadedFile = jQuery('#gd_im_' + type, cont).val();
2588 1
    var choice = jQuery('input[name="gd_im_choice'+ type +'"]:checked', cont).val();
2589 1
2590 1
    if (!uploadedFile) {
2591 1
        jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2592 1
        jQuery('#gd_stop_import', cont).hide();
2593
        jQuery('#gd_process_data', cont).hide();
2594
        jQuery('#gd-import-progress', cont).hide();
2595
        jQuery('.gd-fileprogress', cont).width(0);
2596
        jQuery('#gd-import-done', cont).text('0');
2597
        jQuery('#gd-import-total', cont).text('0');
2598
        jQuery('#gd-import-perc', cont).text('0%');
2599
2600
        jQuery(cont).find('.filelist .file').remove();
2601
        
2602 1
        jQuery('#gd-import-msg', cont).find('#message').removeClass('updated').addClass('error').html("<p><?php echo esc_attr( PLZ_SELECT_CSV_FILE );?></p>");
2603
        jQuery('#gd-import-msg', cont).show();
2604 1
        
2605 1
        return false;
2606 1
    }
2607 1
2608
    jQuery('#gd-import-total', cont).text(total);
2609 1
    jQuery('#gd_stop_import', cont).show();
2610
    jQuery('#gd_process_data', cont).css({
2611
        'display': 'inline-block'
2612
    });
2613
    jQuery('#gd-import-progress', cont).show();
2614
    if ((parseInt(total) / 100) > 0) {
2615
        limit = parseInt(parseInt(total) / 100);
2616
    }
2617
    if (limit == 1) {
2618 1
        if (parseInt(total) > 50) {
2619 1
            limit = 5;
2620 1
        } else if (parseInt(total) > 10 && parseInt(total) < 51) {
2621
            limit = 2;
2622 1
        }
2623
    }
2624
    if (limit > 10) {
2625
        limit = 10;
2626
    }
2627
    if (limit < 1) {
2628
        limit = 1;
2629
    }
2630
2631
    if ( parseInt(limit) > parseInt(total) )
2632
        limit = parseInt(total);
2633
    if (total_processed >= total) {
2634
        jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2635
        jQuery('#gd_stop_import', cont).hide();
2636
        jQuery('#gd_process_data', cont).hide();
2637
        
2638
        gd_imex_showStatusMsg(el, type);
2639
        
2640
        jQuery('#gd_im_' + type, cont).val('');
2641
        jQuery('#gd_prepared', cont).val('');
2642
2643
        return false;
2644
    }
2645
    jQuery('#gd-import-msg', cont).hide();
2646
        
2647
    var gd_processed = parseInt(jQuery('#gd_processed', cont).val());
2648
    var gd_created = parseInt(jQuery('#gd_created', cont).val());
2649
    var gd_updated = parseInt(jQuery('#gd_updated', cont).val());
2650
    var gd_skipped = parseInt(jQuery('#gd_skipped', cont).val());
2651
    var gd_invalid = parseInt(jQuery('#gd_invalid', cont).val());
2652
    var gd_images = parseInt(jQuery('#gd_images', cont).val());
2653
    if (type=='post') {
2654
        var gd_invalid_addr = parseInt(jQuery('#gd_invalid_addr', cont).val());
2655
    }
2656
2657
    var gddata = '&limit=' + limit + '&processed=' + gd_processed;
2658
    jQuery.ajax({
2659
        url: ajaxurl,
2660
        type: "POST",
2661
        data: 'action=geodir_import_export&task=import_' + type + '&_pt=' + type + '&_file=' + uploadedFile + gddata + '&_ch=' + choice + '&_nonce=<?php echo $nonce;?>',
2662
        dataType : 'json',
2663
        cache: false,
2664
        success: function (data) {
2665
            if (typeof data == 'object') {
2666
                if (data.error) {
2667
                    jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2668
                    jQuery('#gd_stop_import', cont).hide();
2669
                    jQuery('#gd_process_data', cont).hide();
2670
                    jQuery('#gd-import-msg', cont).find('#message').removeClass('updated').addClass('error').html('<p>' + data.error + '</p>');
2671
                    jQuery('#gd-import-msg', cont).show();
2672
                } else {
2673
                    gd_processed = gd_processed + parseInt(data.processed);
2674
                    gd_processed = Math.min(gd_processed, total);
2675
                    gd_created = gd_created + parseInt(data.created);
2676
                    gd_updated = gd_updated + parseInt(data.updated);
2677 1
                    gd_skipped = gd_skipped + parseInt(data.skipped);
2678
                    gd_invalid = gd_invalid + parseInt(data.invalid);
2679
                    gd_images = gd_images + parseInt(data.images);
2680
                    if (type=='post' && typeof data.invalid_addr != 'undefined') {
2681
                        gd_invalid_addr = gd_invalid_addr + parseInt(data.invalid_addr);
2682
                    }
2683
2684
                    jQuery('#gd_processed', cont).val(gd_processed);
2685
                    jQuery('#gd_created', cont).val(gd_created);
2686
                    jQuery('#gd_updated', cont).val(gd_updated);
2687
                    jQuery('#gd_skipped', cont).val(gd_skipped);
2688
                    jQuery('#gd_invalid', cont).val(gd_invalid);
2689
                    jQuery('#gd_images', cont).val(gd_images);
2690
                    if (type=='post') {
2691
                        jQuery('#gd_invalid_addr', cont).val(gd_invalid_addr);
2692
                    }
2693
2694
                    if (parseInt(gd_processed) == parseInt(total)) {
2695
                        jQuery('#gd-import-done', cont).text(total);
2696
                        jQuery('#gd-import-perc', cont).text('100%');
2697
                        jQuery('.gd-fileprogress', cont).css({
2698
                            'width': '100%'
2699
                        });
2700
                        jQuery('#gd_im_' + type, cont).val('');
2701
                        jQuery('#gd_prepared', cont).val('');
2702
                        
2703
                        gd_imex_showStatusMsg(el, type);
2704
                        gd_imex_FinishImport(el, type);
2705
2706
                        jQuery('#gd_stop_import', cont).hide();
2707
                    }
2708
                    if (parseInt(gd_processed) < parseInt(total)) {
2709
                        var terminate_action = jQuery('#gd_terminateaction', cont).val();
2710
                        if (terminate_action == 'continue') {
2711
                            var nTmpCnt = parseInt(total_processed) + parseInt(limit);
2712
                            nTmpCnt = nTmpCnt > total ? total : nTmpCnt;
2713
2714
                            jQuery('#gd_processed', cont).val(nTmpCnt);
2715
2716
                            jQuery('#gd-import-done', cont).text(nTmpCnt);
2717
                            if (parseInt(total) > 0) {
2718
                                var percentage = ((parseInt(nTmpCnt) / parseInt(total)) * 100);
2719
                                percentage = percentage > 100 ? 100 : percentage;
2720
                                jQuery('#gd-import-perc', cont).text(parseInt(percentage) + '%');
2721
                                jQuery('.gd-fileprogress', cont).css({
2722
                                    'width': percentage + '%'
2723
                                });
2724
                            }
2725
                            
2726
                            if (type=='cat') {
2727
                                clearTimeout(timoutC);
2728
                                timoutC = setTimeout(function () {
2729
                                    gd_imex_StartImport(el, type);
2730
                                }, 0);
2731
                            }
2732
                            if (type=='post') {
2733
                                clearTimeout(timoutP);
2734
                                timoutP = setTimeout(function () {
2735
                                    gd_imex_StartImport(el, type);
2736
                                }, 0);
2737
                            }
2738
                            if (type=='loc') {
2739
                                clearTimeout(timoutL);
2740
                                timoutL = setTimeout(function () {
2741
                                    gd_imex_StartImport(el, type);
2742
                                }, 0);
2743
                            }
2744
                            if (type=='hood') {
2745
                                clearTimeout(timoutH);
2746
                                timoutH = setTimeout(function () {
2747
                                    gd_imex_StartImport(el, type);
2748
                                }, 0);
2749
                            }
2750
                        } else {
2751
                            jQuery('#gd_import_data', cont).hide();
2752
                            jQuery('#gd_stop_import', cont).hide();
2753
                            jQuery('#gd_process_data', cont).hide();
2754
                            jQuery('#gd_continue_data', cont).show();
2755
                            return false;
2756
                        }
2757
                    } else {
2758
                        jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2759
                        jQuery('#gd_stop_import', cont).hide();
2760
                        jQuery('#gd_process_data', cont).hide();
2761
                        return false;
2762
                    }
2763
                }
2764
            } else {
2765
                jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2766
                jQuery('#gd_stop_import', cont).hide();
2767
                jQuery('#gd_process_data', cont).hide();
2768
            }
2769
        },
2770
        error: function (errorThrown) {
2771
            jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2772
            jQuery('#gd_stop_import', cont).hide();
2773
            jQuery('#gd_process_data', cont).hide();
2774
            console.log(errorThrown);
2775
        }
2776
    });
2777
}
2778
2779
function gd_imex_TerminateImport(el, type) {
2780
    var cont = jQuery(el).closest('.gd-imex-box');
2781
    jQuery('#gd_terminateaction', cont).val('terminate');
2782
    jQuery('#gd_import_data', cont).hide();
2783
    jQuery('#gd_stop_import', cont).hide();
2784
    jQuery('#gd_process_data', cont).hide();
2785
    jQuery('#gd_continue_data', cont).show();
2786
}
2787
2788
function gd_imex_ContinueImport(el, type) {	
2789
    var cont = jQuery(el).closest('.gd-imex-box');
2790
    var processed = jQuery('#gd_processed', cont).val();
2791
    var total = jQuery('#gd_total', cont).val();
2792
    if (parseInt(processed) > parseInt(total)) {
2793
        jQuery('#gd_stop_import', cont).hide();
2794
    } else {
2795
        jQuery('#gd_stop_import', cont).show();
2796
    }
2797
    jQuery('#gd_import_data', cont).show();
2798 1
    jQuery('#gd_import_data', cont).attr('disabled', 'disabled');
2799
    jQuery('#gd_process_data', cont).css({
2800
        'display': 'inline-block'
2801
    });
2802
    jQuery('#gd_continue_data', cont).hide();
2803
    jQuery('#gd_terminateaction', cont).val('continue');
2804
2805
    if (type=='cat') {
2806
        clearTimeout(timoutC);
2807
        timoutC = setTimeout(function () {
2808
            gd_imex_StartImport(el, type);
2809
        }, 0);
2810
    }
2811
2812
    if (type=='post') {
2813
        clearTimeout(timoutP);
2814
        timoutP = setTimeout(function () {
2815
            gd_imex_StartImport(el, type);
2816
        }, 0);
2817
    }
2818
2819
    if (type=='loc') {
2820
        clearTimeout(timoutL);
2821
        timoutL = setTimeout(function () {
2822
            gd_imex_StartImport(el, type);
2823
        }, 0);
2824
    }
2825
    
2826
    if (type=='hood') {
2827
        clearTimeout(timoutH);
2828
        timoutH = setTimeout(function () {
2829
            gd_imex_StartImport(el, type);
2830
        }, 0);
2831
    }
2832
}
2833
2834
function gd_imex_showStatusMsg(el, type) {
2835
    var cont = jQuery(el).closest('.gd-imex-box');
2836
2837
    var total = parseInt(jQuery('#gd_total', cont).val());
2838
    var processed = parseInt(jQuery('#gd_processed', cont).val());
2839
    var created = parseInt(jQuery('#gd_created', cont).val());
2840
    var updated = parseInt(jQuery('#gd_updated', cont).val());
2841
    var skipped = parseInt(jQuery('#gd_skipped', cont).val());
2842
    var invalid = parseInt(jQuery('#gd_invalid', cont).val());
2843
    var images = parseInt(jQuery('#gd_images', cont).val());
2844
    if (type=='post') {
2845
        var invalid_addr = parseInt(jQuery('#gd_invalid_addr', cont).val());
2846
    }
2847
2848
    var gdMsg = '<p></p>';
2849
    if ( processed > 0 ) {
2850
        var msgParse = '<p><?php echo addslashes( sprintf( __( 'Total %s item(s) found.', 'geodirectory' ), '%s' ) );?></p>';
2851
        msgParse = msgParse.replace("%s", processed);
2852
        gdMsg += msgParse;
2853
    }
2854
2855
    if ( updated > 0 ) {
2856
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) updated.', 'geodirectory' ), '%s', '%d' ) );?></p>';
2857
        msgParse = msgParse.replace("%s", updated);
2858
        msgParse = msgParse.replace("%d", processed);
2859
        gdMsg += msgParse;
2860
    }
2861
2862
    if ( created > 0 ) {
2863
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) added.', 'geodirectory' ), '%s', '%d' ) );?></p>';
2864
        msgParse = msgParse.replace("%s", created);
2865
        msgParse = msgParse.replace("%d", processed);
2866
        gdMsg += msgParse;
2867
    }
2868
2869
    if ( skipped > 0 ) {
2870
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) ignored due to already exists.', 'geodirectory' ), '%s', '%d' ) );?></p>';
2871
        msgParse = msgParse.replace("%s", skipped);
2872
        msgParse = msgParse.replace("%d", processed);
2873
        gdMsg += msgParse;
2874
    }
2875
2876
    if ((type=='post' && invalid_addr > 0) || (type=='loc' && invalid > 0)) {
2877
        if (type=='loc') {
2878
            invalid_addr = invalid;
2879
        }
2880
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) could not be added due to blank/invalid address(city, region, country, latitude, longitude).', 'geodirectory' ), '%s', '%d' ) );?></p>';
2881
        msgParse = msgParse.replace("%s", invalid_addr);
2882
        msgParse = msgParse.replace("%d", total);
2883
        gdMsg += msgParse;
2884
    }
2885
2886
    if (invalid > 0 && type!='loc') {
2887 1
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) could not be added due to blank title/invalid post type/invalid characters used in data.', 'geodirectory' ), '%s', '%d' ) );?></p>';
2888
        
2889
        if (type=='hood') {
2890
            msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) could not be added due to invalid neighbourhood data(name, latitude, longitude) or invalid location data(either location_id or city/region/country is empty)', 'geodirectory' ), '%s', '%d' ) );?></p>';
2891
        }
2892
        msgParse = msgParse.replace("%s", invalid);
2893
        msgParse = msgParse.replace("%d", total);
2894
        gdMsg += msgParse;
2895
    }
2896
2897
    if (images > 0) {
2898
        gdMsg += '<p><?php echo addslashes( sprintf( CSV_TRANSFER_IMG_FOLDER, $uploads['subdir'] ) );?></p>';
2899
    }
2900
    gdMsg += '<p></p>';
2901
    jQuery('#gd-import-msg', cont).find('#message').removeClass('error').addClass('updated').html(gdMsg);
2902
    jQuery('#gd-import-msg', cont).show();
2903
    return;
2904
}
2905
2906
2907
2908
jQuery(function(){
2909
    jQuery('.postbox.gd-hndle-pbox').addClass('closed');
2910
    jQuery('.gd-import-export .postbox .gd-hndle-click, .gd-import-export .postbox .button-link').click(function(e){
2911
        var $this = this;
2912
        var $postbox = jQuery($this).closest('.postbox');
2913
        
2914
        $postbox.toggleClass('closed');
2915
    });
2916
2917
    var intIp;
2918
    var intIc;
2919
2920
    jQuery(".gd-imex-pupload").click(function () {
2921
        var $this = this;
2922
        var $cont = jQuery($this).closest('.gd-imex-box');
2923
        clearInterval(intIp);
2924
        intIp = setInterval(function () {
2925
            if (jQuery($cont).find('.gd-imex-file').val()) {
2926
                jQuery($cont).find('.gd-imex-btns').show();
2927
            }
2928
        }, 1000);
2929
    });
2930
2931
    jQuery(".gd-imex-cupload").click(function () {
2932
        var $this = this;
2933
        var $cont = jQuery($this).closest('.gd-imex-box');
2934
        clearInterval(intIc);
2935
        intIc = setInterval(function () {
2936
            if (jQuery($cont).find('.gd-imex-file').val()) {
2937
                jQuery($cont).find('.gd-imex-btns').show();
2938
            }
2939
        }, 1000);
2940
    });
2941
                
2942
    jQuery('#gd_ie_imposts_sample').click(function(){
2943
        if (jQuery('#gd_ie_imposts_csv').val() != '') {
2944
            window.location.href = jQuery('#gd_ie_imposts_csv').val();
2945
            return false;
2946
        }
2947
    });
2948
2949
    jQuery('#gd_ie_imcats_sample').click(function(){
2950
        if (jQuery('#gd_ie_imcats_csv').val() != '') {
2951
            window.location.href = jQuery('#gd_ie_imcats_csv').val();
2952
            return false;
2953
        }
2954
    });
2955
2956
    jQuery('.gd-import-export .geodir_event_csv_download a').addClass('button-secondary');
2957
2958
    jQuery( '.gd_progressbar' ).each(function(){
2959
        jQuery(this).progressbar({value:0});
2960
    });
2961
2962
    var timer_posts;
2963
    var pseconds;
2964
    jQuery('#gd_ie_exposts_submit').click(function(){
2965
        pseconds = 1;
2966
        
2967
        var el = jQuery(this).closest('.postbox');
2968
        var post_type = jQuery(el).find('#gd_post_type').val();
2969
        if ( !post_type ) {
2970
            jQuery(el).find('#gd_post_type').focus();
2971
            return false;
2972
        }
2973
        window.clearInterval(timer_posts);
2974
        
2975
        jQuery(this).prop('disabled', true);
2976
        
2977
        timer_posts = window.setInterval( function() {
2978
            jQuery(el).find(".gd_timer").gdposts_timer();
2979
        }, 1000);
2980
        
2981
        var chunk_size = parseInt(jQuery('#gd_chunk_size', el).val());
2982
        var total_posts = parseInt(jQuery('option:selected', jQuery(el).find('#gd_post_type')).attr('data-posts'));
2983
        chunk_size = chunk_size < 50 || chunk_size > 100000 ? 5000 : chunk_size;
2984
        if (chunk_size > total_posts) {
2985
            chunk_size = total_posts;
2986
        }
2987
        var pages = Math.ceil( total_posts / chunk_size );
2988
        
2989
        var filters = ''; 
2990
        var v;
2991
        jQuery('[name^="gd_imex["]', el).each(function() {
2992
           v = jQuery(this).val();
2993
           v = typeof v == 'string' && v !== '' ? v.trim() : '';
2994
           if (v !== '') {
2995
               filters += '&' + jQuery(this).prop('name') + '=' + v;
2996
           }
2997
        });
2998
        
2999
        gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, 1, filters, true);
3000
    });
3001
3002
    jQuery.fn.gdposts_timer = function() {
3003
        pseconds++;
3004
        jQuery(this).text( pseconds.toString().toHMS() );
3005
    }
3006
3007
    var timer_cats;
3008
    var cseconds;
3009
    jQuery('#gd_ie_excats_submit').click(function(){
3010
        cseconds = 1;
3011
        
3012
        var el = jQuery(this).closest('.postbox');
3013
        var post_type = jQuery(el).find('#gd_post_type').val();
3014
        if ( !post_type ) {
3015
            jQuery(el).find('#gd_post_type').focus();
3016
            return false;
3017
        }
3018
        window.clearInterval(timer_cats);
3019
        
3020
        jQuery(this).prop('disabled', true);
3021
        
3022
        timer_cats = window.setInterval( function() {
3023
            jQuery(el).find(".gd_timer").gdcats_timer();
3024
        }, 1000);
3025
        
3026
        var chunk_size = parseInt(jQuery('#gd_chunk_size', el).val());
3027
        var total_cats = parseInt(jQuery('option:selected', jQuery(el).find('#gd_post_type')).attr('data-cats'));
3028
        chunk_size = chunk_size < 50 || chunk_size > 100000 ? 5000 : chunk_size;
3029
        if (chunk_size > total_cats) {
3030
            chunk_size = total_cats;
3031
        }
3032
        var pages = Math.ceil( total_cats / chunk_size );
3033
        
3034
        gd_process_export_cats(el, post_type, total_cats, chunk_size, pages, 1);
3035
    });
3036
3037
    jQuery.fn.gdcats_timer = function() {
3038
        cseconds++;
3039
        jQuery(this).text( cseconds.toString().toHMS() );
3040
    }
3041
3042
    String.prototype.toHMS = function () {
3043
        var sec_num = parseInt(this, 10); // don't forget the second param
3044
        var hours   = Math.floor(sec_num / 3600);
3045
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
3046
        var seconds = sec_num - (hours * 3600) - (minutes * 60);
3047
3048
        if (hours   < 10) {hours   = "0"+hours;}
3049
        if (minutes < 10) {minutes = "0"+minutes;}
3050
        if (seconds < 10) {seconds = "0"+seconds;}
3051
        var time    = hours+':'+minutes+':'+seconds;
3052
        return time;
3053
    }
3054
        
3055
    function gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, page, filters, doFilter) {
3056
        var attach = (typeof filters !== 'undefined' && filters) ? filters : '';
3057
        var getTotal = false;
3058
        if (page < 2) {
3059
            if (typeof filters !== 'undefined' && filters && doFilter) {
3060
                getTotal = true;
3061
                attach += '&_c=1';
3062
                gd_progressbar(el, 0, '<i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Preparing...', 'geodirectory' ) );?>');
3063
            } else {
3064
                gd_progressbar(el, 0, '0% (0 / ' + total_posts + ') <i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Exporting...', 'geodirectory' ) );?>');
3065
            }
3066
            jQuery(el).find('#gd_timer').text('00:00:01');
3067
            jQuery('#gd_ie_ex_files', el).html('');
3068
        }
3069
3070
        jQuery.ajax({
3071
            url: ajaxurl,
3072
            type: "POST",
3073
            data: 'action=geodir_import_export&task=export_posts&_pt=' + post_type + '&_n=' + chunk_size + '&_nonce=<?php echo $nonce;?>&_p=' + page + attach,
3074
            dataType : 'json',
3075
            cache: false,
3076
            beforeSend: function (jqXHR, settings) {},
3077
            success: function( data ) {
3078
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3079
                
3080
                if (typeof data == 'object') {
3081
                    if (typeof data.error != 'undefined' && data.error) {
3082
                        gd_progressbar(el, 0, '<i class="fa fa-warning"></i>' + data.error);
3083
                        window.clearInterval(timer_posts);
3084
                    } else {
3085
                        if (getTotal) {
3086
                            if (typeof data.total != 'undefined' ) {
3087
                                total_posts = parseInt(data.total);
3088
                                if (chunk_size > total_posts) {
3089
                                    chunk_size = total_posts;
3090
                                }
3091
                                pages = Math.ceil( total_posts / chunk_size );
3092
                                
3093
                                return gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, 1, filters);
3094
                            }
3095
                        } else {
3096
                            if (pages < page || pages == page) {
3097
                                window.clearInterval(timer_posts);
3098
                                gd_progressbar(el, 100, '100% (' + total_posts + ' / ' + total_posts + ') <i class="fa fa-check"></i><?php echo esc_attr( __( 'Complete!', 'geodirectory' ) );?>');
3099
                            } else {
3100
                                var percentage = Math.round(((page * chunk_size) / total_posts) * 100);
3101
                                percentage = percentage > 100 ? 100 : percentage;
3102
                                gd_progressbar(el, percentage, '' + percentage + '% (' + ( page * chunk_size ) + ' / ' + total_posts + ') <i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Exporting...', 'geodirectory' ) );?>');
3103
                            }
3104
                            if (typeof data.files != 'undefined' && jQuery(data.files).length ) {
3105
                                var obj_files = data.files;
3106
                                var files = '';
3107
                                for (var i in data.files) {
3108
                                    files += '<p>'+ obj_files[i].i +' <a class="gd-ie-file" href="' + obj_files[i].u + '" target="_blank">' + obj_files[i].u + '</a> (' + obj_files[i].s + ')</p>';
3109
                                }
3110
                                jQuery('#gd_ie_ex_files', el).append(files);
3111
                                if (pages > page) {
3112
                                    return gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, (page + 1));
3113
                                }
3114
                                return true;
3115
                            }
3116
                        }
3117
                    }
3118
                }
3119
            },
3120
            error: function( data ) {
3121
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3122
                window.clearInterval(timer_posts);
3123
                return;
3124
            },
3125
            complete: function( jqXHR, textStatus  ) {
3126
                return;
3127
            }
3128
        });
3129
    }
3130
3131
    function gd_process_export_cats(el, post_type, total_cats, chunk_size, pages, page) {
3132
        if (page < 2) {
3133
            gd_progressbar(el, 0, '0% (0 / ' + total_cats + ') <i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Exporting...', 'geodirectory' ) );?>');
3134
            jQuery(el).find('#gd_timer').text('00:00:01');
3135
            jQuery('#gd_ie_ex_files', el).html('');
3136
        }
3137
3138
        jQuery.ajax({
3139
            url: ajaxurl,
3140
            type: "POST",
3141
            data: 'action=geodir_import_export&task=export_cats&_pt=' + post_type + '&_n=' + chunk_size + '&_nonce=<?php echo $nonce;?>&_p=' + page,
3142
            dataType : 'json',
3143
            cache: false,
3144
            beforeSend: function (jqXHR, settings) {},
3145
            success: function( data ) {
3146
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3147
                
3148
                if (typeof data == 'object') {
3149
                    if (typeof data.error != 'undefined' && data.error) {
3150
                        gd_progressbar(el, 0, '<i class="fa fa-warning"></i>' + data.error);
3151
                        window.clearInterval(timer_cats);
3152
                    } else {
3153
                        if (pages < page || pages == page) {
3154
                            window.clearInterval(timer_cats);
3155
                            gd_progressbar(el, 100, '100% (' + total_cats + ' / ' + total_cats + ') <i class="fa fa-check"></i><?php echo esc_attr( __( 'Complete!', 'geodirectory' ) );?>');
3156
                        } else {
3157
                            var percentage = Math.round(((page * chunk_size) / total_cats) * 100);
3158
                            percentage = percentage > 100 ? 100 : percentage;
3159
                            gd_progressbar(el, percentage, '' + percentage + '% (' + ( page * chunk_size ) + ' / ' + total_cats + ') <i class="fa fa-refresh fa-spin"></i><?php esc_attr_e( 'Exporting...', 'geodirectory' );?>');
3160
                        }
3161
                        if (typeof data.files != 'undefined' && jQuery(data.files).length ) {
3162
                            var obj_files = data.files;
3163
                            var files = '';
3164
                            for (var i in data.files) {
3165
                                files += '<p>'+ obj_files[i].i +' <a class="gd-ie-file" href="' + obj_files[i].u + '" target="_blank">' + obj_files[i].u + '</a> (' + obj_files[i].s + ')</p>';
3166
                            }
3167
                            jQuery('#gd_ie_ex_files', el).append(files);
3168
                            if (pages > page) {
3169
                                return gd_process_export_cats(el, post_type, total_cats, chunk_size, pages, (page + 1));
3170
                            }
3171
                            return true;
3172
                        }
3173
                    }
3174
                }
3175
            },
3176
            error: function( data ) {
3177
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3178
                window.clearInterval(timer_cats);
3179
                return;
3180
            },
3181
            complete: function( jqXHR, textStatus  ) {
3182
                return;
3183
            }
3184
        });
3185
    }
3186
});
3187
3188
function gd_imex_FinishImport(el, type) {
3189
    if (type=='post') {
3190
        jQuery.ajax({
3191
            url: ajaxurl,
3192
            type: "POST",
3193
            data: 'action=geodir_import_export&task=import_finish&_pt=' + type + '&_nonce=<?php echo $nonce; ?>',
3194
            dataType : 'json',
3195
            cache: false,
3196
            success: function (data) {
3197
                //import done
3198
            }
3199
        });
3200
    }
3201
}
3202
</script>
3203
<?php
3204
}
3205
3206
/**
3207
 * Initiate the WordPress file system and provide fallback if needed.
3208
 *
3209
 * @since 1.4.8
3210
 * @package GeoDirectory
3211
 * @return bool|string Returns the file system class on success. False on failure.
3212
 */
3213
function geodir_init_filesystem()
3214
{
3215
3216
    if(!function_exists('get_filesystem_method')){
3217
        require_once(ABSPATH."/wp-admin/includes/file.php");
3218
    }
3219
    $access_type = get_filesystem_method();
3220
    if ($access_type === 'direct') {
3221
        /* you can safely run request_filesystem_credentials() without any issues and don't need to worry about passing in a URL */
3222
        $creds = request_filesystem_credentials(trailingslashit(site_url()) . 'wp-admin/', '', false, false, array());
3223
3224
        /* initialize the API */
3225
        if (!WP_Filesystem($creds)) {
3226
            /* any problems and we exit */
3227
            //return '@@@3';
3228
            return false;
3229
        }
3230
3231
        global $wp_filesystem;
3232
        return $wp_filesystem;
3233
        /* do our file manipulations below */
3234
    } elseif (defined('FTP_USER')) {
3235
        $creds = request_filesystem_credentials(trailingslashit(site_url()) . 'wp-admin/', '', false, false, array());
3236
3237
        /* initialize the API */
3238
        if (!WP_Filesystem($creds)) {
3239
            /* any problems and we exit */
3240
            //return '@@@33';
3241
            return false;
3242
        }
3243
3244
        global $wp_filesystem;
3245
        //return '@@@1';
3246
        return $wp_filesystem;
3247
3248
    } else {
3249
        //return '@@@2';
3250
        /* don't have direct write access. Prompt user with our notice */
3251
        add_action('admin_notice', 'geodir_filesystem_notice');
3252
        return false;
3253
    }
3254
3255
}
3256
3257
3258
add_action('admin_init', 'geodir_filesystem_notice');
3259
3260
/**
3261
 * Output error message for file system access.
3262
 *
3263
 * Displays an admin message if the WordPress file system can't be automatically accessed. Called via admin_init hook.
3264
 *
3265
 * @since 1.4.8
3266
 * @since 1.4.9 Added check to not run function when doing ajax calls.
3267
 * @package GeoDirectory
3268
 */
3269
function geodir_filesystem_notice()
3270
{   if ( defined( 'DOING_AJAX' ) ){return;}
3271
    $access_type = get_filesystem_method();
3272
    if ($access_type === 'direct') {
3273
    } elseif (!defined('FTP_USER')) {
3274
        ?>
3275
        <div class="error">
3276
            <p><?php _e('GeoDirectory does not have access to your filesystem, thing like import/export will not work. Please define your details in wp-config.php as explained here', 'geodirectory'); ?>
3277
                <a target="_blank" href="http://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants">http://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants</a>
3278
            </p>
3279
        </div>
3280
    <?php }
3281
}
3282
3283
3284
3285
/**
3286
 * Handle import/export for categories & listings.
3287
 *
3288
 * @since 1.4.6
3289
 * @since 1.5.4 Modified to add default category via csv import.
3290
 * @since 1.5.7 Modified to fix 504 Gateway Time-out for very large data.
3291
 * @package GeoDirectory
3292
 *
3293
 * @global object $wpdb WordPress Database object.
3294
 * @global string $plugin_prefix Geodirectory plugin table prefix.
3295
 * @global object $current_user Current user object.
3296
 * @global null|object $wp_filesystem WP_Filesystem object.
3297
 * @return string Json data.
3298
 */
3299
function geodir_ajax_import_export() {
3300
    global $wpdb, $plugin_prefix, $current_user, $wp_filesystem;
3301
    
3302
    error_reporting(0);
3303
3304
    // try to set higher limits for import
3305
    $max_input_time = ini_get('max_input_time');
3306
    $max_execution_time = ini_get('max_execution_time');
3307
    $memory_limit= ini_get('memory_limit');
3308
3309
    if(!$max_input_time || $max_input_time<3000){
3310
        ini_set('max_input_time', 3000);
3311
    }
3312
3313
    if(!$max_execution_time || $max_execution_time<3000){
3314
        ini_set('max_execution_time', 3000);
3315
    }
3316
3317
    if($memory_limit && str_replace('M','',$memory_limit)){
3318
        if(str_replace('M','',$memory_limit)<256){
3319
            ini_set('memory_limit', '256M');
3320
        }
3321
    }
3322
3323
    $json = array();
3324
3325
    if ( !current_user_can( 'manage_options' ) ) {
3326
        wp_send_json( $json );
3327
    }
3328
3329
    $task = isset( $_REQUEST['task'] ) ? $_REQUEST['task'] : NULL;
3330
    $nonce = isset( $_REQUEST['_nonce'] ) ? $_REQUEST['_nonce'] : NULL;
3331
    $stat = isset( $_REQUEST['_st'] ) ? $_REQUEST['_st'] : false;
0 ignored issues
show
Unused Code introduced by
$stat is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3332
3333
    if ( !wp_verify_nonce( $nonce, 'geodir_import_export_nonce' ) ) {
3334
        wp_send_json( $json );
3335
    }
3336
3337
    $post_type = isset( $_REQUEST['_pt'] ) ? $_REQUEST['_pt'] : NULL;
3338
    $chunk_per_page = isset( $_REQUEST['_n'] ) ? absint($_REQUEST['_n']) : NULL;
3339
    $chunk_per_page = $chunk_per_page < 50 || $chunk_per_page > 100000 ? 5000 : $chunk_per_page;
3340
    $chunk_page_no = isset( $_REQUEST['_p'] ) ? absint($_REQUEST['_p']) : 1;
3341
3342
    $wp_filesystem = geodir_init_filesystem();
3343
    if (!$wp_filesystem) {
3344
        $json['error'] = __( 'Filesystem ERROR: Could not access filesystem.', 'geodirectory' );
3345
        wp_send_json( $json );
3346
    }
3347
3348
    if (!empty($wp_filesystem) && isset($wp_filesystem->errors) && is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
3349
        $json['error'] = __( 'Filesystem ERROR: ' . $wp_filesystem->errors->get_error_message(), 'geodirectory' );
3350
        wp_send_json( $json );
3351
    }
3352
3353
    $csv_file_dir = geodir_path_import_export( false );
3354
    if ( !$wp_filesystem->is_dir( $csv_file_dir ) ) {
0 ignored issues
show
Bug introduced by
The method is_dir cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3355
        if ( !$wp_filesystem->mkdir( $csv_file_dir, FS_CHMOD_DIR ) ) {
0 ignored issues
show
Bug introduced by
The method mkdir cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3356
            $json['error'] = __( 'ERROR: Could not create cache directory. This is usually due to inconsistent file permissions.', 'geodirectory' );
3357
            wp_send_json( $json );
3358
        }
3359
    }
3360
    
3361
    $location_manager = function_exists('geodir_location_plugin_activated') ? true : false; // Check location manager installed & active.
3362
    $neighbourhood_active = $location_manager && get_option('location_neighbourhoods') ? true : false;
3363
3364
    switch ( $task ) {
3365
        case 'export_posts': {
3366
            // WPML
3367
            $is_wpml = geodir_is_wpml();
3368
            if ($is_wpml) {
3369
                global $sitepress;
3370
                $active_lang = ICL_LANGUAGE_CODE;
3371
                
3372
                $sitepress->switch_lang('all', true);
3373
            }
3374
            // WPML
3375
            if ( $post_type == 'gd_event' ) {
3376
                add_filter( 'geodir_imex_export_posts_query', 'geodir_imex_get_events_query', 10, 2 );
3377
            }
3378
            $filters = !empty( $_REQUEST['gd_imex'] ) && is_array( $_REQUEST['gd_imex'] ) ? $_REQUEST['gd_imex'] : NULL;
3379
            
3380
            $file_name = $post_type . '_' . date( 'dmyHi' );
3381
            if ( $filters && isset( $filters['start_date'] ) && isset( $filters['end_date'] ) ) {
3382
                $file_name = $post_type . '_' . date_i18n( 'dmy', strtotime( $filters['start_date'] ) ) . '_' . date_i18n( 'dmy', strtotime( $filters['end_date'] ) );
3383
            }
3384
            $posts_count = geodir_get_posts_count( $post_type );
3385
            $file_url_base = geodir_path_import_export() . '/';
3386
            $file_url = $file_url_base . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3387
            $file_path = $csv_file_dir . '/' . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3388
            $file_path_temp = $csv_file_dir . '/' . $post_type . '_' . $nonce . '.csv';
3389
            
3390
            $chunk_file_paths = array();
3391
3392
            if ( isset( $_REQUEST['_c'] ) ) {
3393
                $json['total'] = $posts_count;
3394
                // WPML
3395
                if ($is_wpml) {
3396
                    $sitepress->switch_lang($active_lang, true);
0 ignored issues
show
Bug introduced by
The variable $sitepress does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $active_lang does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
3397
                }
3398
                // WPML
3399
                wp_send_json( $json );
3400
                gd_die();
3401
            } else if ( isset( $_REQUEST['_st'] ) ) {
3402
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3403
                $percentage = count( $posts_count ) > 0 && $line_count > 0 ? ceil( $line_count / $posts_count ) * 100 : 0;
3404
                $percentage = min( $percentage, 100 );
3405
                
3406
                $json['percentage'] = $percentage;
3407
                // WPML
3408
                if ($is_wpml) {
3409
                    $sitepress->switch_lang($active_lang, true);
3410
                }
3411
                // WPML
3412
                wp_send_json( $json );
3413
                gd_die();
3414
            } else {
3415
                if ( !$posts_count > 0 ) {
3416
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3417
                } else {
3418
                    $total_posts = $posts_count;
3419
                    if ($chunk_per_page > $total_posts) {
3420
                        $chunk_per_page = $total_posts;
3421
                    }
3422
                    $chunk_total_pages = ceil( $total_posts / $chunk_per_page );
3423
                    
3424
                    $j = $chunk_page_no;
3425
                    $chunk_save_posts = geodir_imex_get_posts( $post_type, $chunk_per_page, $j );
3426
                    
3427
                    $per_page = 500;
3428
                    if ($per_page > $chunk_per_page) {
3429
                        $per_page = $chunk_per_page;
3430
                    }
3431
                    $total_pages = ceil( $chunk_per_page / $per_page );
3432
                    
3433
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3434
                        $save_posts = array_slice( $chunk_save_posts , ( $i * $per_page ), $per_page );
3435
                        
3436
                        $clear = $i == 0 ? true : false;
3437
                        geodir_save_csv_data( $file_path_temp, $save_posts, $clear );
3438
                    }
3439
                        
3440
                    if ( $wp_filesystem->exists( $file_path_temp ) ) {
0 ignored issues
show
Bug introduced by
The method exists cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3441
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3442
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3443
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3444
                        $wp_filesystem->move( $file_path_temp, $file_path, true );
0 ignored issues
show
Bug introduced by
The method move cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3445
                        
3446
                        $file_url = $file_url_base . $chunk_file_name;
3447
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3448
                    }
3449
                    
3450
                    if ( !empty($chunk_file_paths) ) {
3451
                        $json['total'] = $posts_count;
3452
                        $json['files'] = $chunk_file_paths;
3453
                    } else {
3454
                        if ($j > 1) {
3455
                            $json['total'] = $posts_count;
3456
                            $json['files'] = array();
3457
                        } else {
3458
                            $json['error'] = __( 'ERROR: Could not create csv file. This is usually due to inconsistent file permissions.', 'geodirectory' );
3459
                        }
3460
                    }
3461
                }
3462
                // WPML
3463
                if ($is_wpml) {
3464
                    $sitepress->switch_lang($active_lang, true);
3465
                }
3466
                // WPML
3467
                wp_send_json( $json );
3468
            }
3469
        }
3470
        break;
3471
        case 'export_cats': {
3472
            // WPML
3473
            $is_wpml = geodir_is_wpml();
3474
            if ($is_wpml) {
3475
                global $sitepress;
3476
                $active_lang = ICL_LANGUAGE_CODE;
3477
                
3478
                $sitepress->switch_lang('all', true);
3479
            }
3480
            // WPML
3481
            $file_name = $post_type . 'category_' . date( 'dmyHi' );
3482
            
3483
            $terms_count = geodir_get_terms_count( $post_type );
3484
            $file_url_base = geodir_path_import_export() . '/';
3485
            $file_url = $file_url_base . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3486
            $file_path = $csv_file_dir . '/' . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3487
            $file_path_temp = $csv_file_dir . '/' . $post_type . 'category_' . $nonce . '.csv';
3488
            
3489
            $chunk_file_paths = array();
3490
            
3491
            if ( isset( $_REQUEST['_st'] ) ) {
3492
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3493
                $percentage = count( $terms_count ) > 0 && $line_count > 0 ? ceil( $line_count / $terms_count ) * 100 : 0;
3494
                $percentage = min( $percentage, 100 );
3495
                
3496
                $json['percentage'] = $percentage;
3497
                // WPML
3498
                if ($is_wpml) {
3499
                    $sitepress->switch_lang($active_lang, true);
3500
                }
3501
                // WPML
3502
                wp_send_json( $json );
3503
            } else {
3504
                if ( !$terms_count > 0 ) {
3505
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3506
                } else {
3507
                    $total_terms = $terms_count;
3508
                    if ($chunk_per_page > $terms_count) {
3509
                        $chunk_per_page = $terms_count;
3510
                    }
3511
                    $chunk_total_pages = ceil( $total_terms / $chunk_per_page );
3512
                    
3513
                    $j = $chunk_page_no;
3514
                    $chunk_save_terms = geodir_imex_get_terms( $post_type, $chunk_per_page, $j );
3515
                    
3516
                    $per_page = 500;
3517
                    if ($per_page > $chunk_per_page) {
3518
                        $per_page = $chunk_per_page;
3519
                    }
3520
                    $total_pages = ceil( $chunk_per_page / $per_page );
3521
                    
3522
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3523
                        $save_terms = array_slice( $chunk_save_terms , ( $i * $per_page ), $per_page );
3524
                        
3525
                        $clear = $i == 0 ? true : false;
3526
                        geodir_save_csv_data( $file_path_temp, $save_terms, $clear );
3527
                    }
3528
                    
3529
                    if ( $wp_filesystem->exists( $file_path_temp ) ) {
0 ignored issues
show
Bug introduced by
The method exists cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3530
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3531
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3532
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3533
                        $wp_filesystem->move( $file_path_temp, $file_path, true );
0 ignored issues
show
Bug introduced by
The method move cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3534
                        
3535
                        $file_url = $file_url_base . $chunk_file_name;
3536
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3537
                    }
3538
                    
3539
                    if ( !empty($chunk_file_paths) ) {
3540
                        $json['total'] = $terms_count;
3541
                        $json['files'] = $chunk_file_paths;
3542
                    } else {
3543
                        $json['error'] = __( 'ERROR: Could not create csv file. This is usually due to inconsistent file permissions.', 'geodirectory' );
3544
                    }
3545
                }
3546
                // WPML
3547
                if ($is_wpml) {
3548
                    $sitepress->switch_lang($active_lang, true);
3549
                }
3550
                // WPML
3551
                wp_send_json( $json );
3552
            }
3553
        }
3554
        break;
3555 View Code Duplication
        case 'export_locations': {
3556
            $file_url_base = geodir_path_import_export() . '/';
3557
            $file_name = 'gd_locations_' . date( 'dmyHi' );
3558
            $file_url = $file_url_base . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3559
            $file_path = $csv_file_dir . '/' . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3560 1
            $file_path_temp = $csv_file_dir . '/gd_locations_' . $nonce . '.csv';
3561
            
3562
            $items_count = (int)geodir_location_imex_count_locations();
3563
            
3564
            if ( isset( $_REQUEST['_st'] ) ) {
3565
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3566
                $percentage = count( $items_count ) > 0 && $line_count > 0 ? ceil( $line_count / $items_count ) * 100 : 0;
3567
                $percentage = min( $percentage, 100 );
3568
                
3569
                $json['percentage'] = $percentage;
3570
                wp_send_json( $json );
3571
            } else {
3572
                $chunk_file_paths = array();
3573
                
3574
                if ( !$items_count > 0 ) {
3575
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3576
                } else {
3577
                    $chunk_per_page = min( $chunk_per_page, $items_count );
3578
                    $chunk_total_pages = ceil( $items_count / $chunk_per_page );
3579
                    
3580
                    $j = $chunk_page_no;
3581
                    $chunk_save_items = geodir_location_imex_locations_data( $chunk_per_page, $j );
3582
                    
3583
                    $per_page = 500;
3584
                    $per_page = min( $per_page, $chunk_per_page );
3585
                    $total_pages = ceil( $chunk_per_page / $per_page );
3586
                    
3587
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3588
                        $save_items = array_slice( $chunk_save_items , ( $i * $per_page ), $per_page );
3589
                        
3590
                        $clear = $i == 0 ? true : false;
3591
                        geodir_save_csv_data( $file_path_temp, $save_items, $clear );
3592
                    }
3593
                    
3594
                    if ( $wp_filesystem->exists( $file_path_temp ) ) {
0 ignored issues
show
Bug introduced by
The method exists cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3595
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3596
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3597
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3598
                        $wp_filesystem->move( $file_path_temp, $file_path, true );
0 ignored issues
show
Bug introduced by
The method move cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3599
                        
3600
                        $file_url = $file_url_base . $chunk_file_name;
3601
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3602
                    }
3603
                    
3604
                    if ( !empty($chunk_file_paths) ) {
3605
                        $json['total'] = $items_count;
3606
                        $json['files'] = $chunk_file_paths;
3607
                    } else {
3608
                        $json['error'] = __( 'Fail, something wrong to create csv file.', 'geodirectory' );
3609
                    }
3610
                }
3611
                wp_send_json( $json );
3612
            }
3613
        }
3614
        break;
3615 View Code Duplication
        case 'export_hoods': {
3616
            $file_url_base = geodir_path_import_export() . '/';
3617
            $file_name = 'gd_neighbourhoods_' . date( 'dmyHi' );
3618
            $file_url = $file_url_base . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3619
            $file_path = $csv_file_dir . '/' . $file_name . '.csv';
0 ignored issues
show
Unused Code introduced by
$file_path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3620
            $file_path_temp = $csv_file_dir . '/gd_neighbourhoods_' . $nonce . '.csv';
3621
            
3622
            $items_count = (int)geodir_location_imex_count_neighbourhoods();
3623
            
3624
            if ( isset( $_REQUEST['_st'] ) ) {
3625
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3626 1
                $percentage = count( $items_count ) > 0 && $line_count > 0 ? ceil( $line_count / $items_count ) * 100 : 0;
3627
                $percentage = min( $percentage, 100 );
3628
                
3629
                $json['percentage'] = $percentage;
3630
                wp_send_json( $json );
3631
            } else {
3632
                $chunk_file_paths = array();
3633
                
3634
                if ( !$items_count > 0 ) {
3635
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3636
                } else {
3637
                    $chunk_per_page = min( $chunk_per_page, $items_count );
3638
                    $chunk_total_pages = ceil( $items_count / $chunk_per_page );
3639
                    
3640
                    $j = $chunk_page_no;
3641
                    $chunk_save_items = geodir_location_imex_neighbourhoods_data( $chunk_per_page, $j );
3642
                    
3643
                    $per_page = 500;
3644
                    $per_page = min( $per_page, $chunk_per_page );
3645
                    $total_pages = ceil( $chunk_per_page / $per_page );
3646
                    
3647
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3648
                        $save_items = array_slice( $chunk_save_items , ( $i * $per_page ), $per_page );
3649
                        
3650
                        $clear = $i == 0 ? true : false;
3651
                        geodir_save_csv_data( $file_path_temp, $save_items, $clear );
3652
                    }
3653
                    
3654
                    if ( $wp_filesystem->exists( $file_path_temp ) ) {
0 ignored issues
show
Bug introduced by
The method exists cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3655
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3656
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3657
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3658
                        $wp_filesystem->move( $file_path_temp, $file_path, true );
0 ignored issues
show
Bug introduced by
The method move cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3659
                        
3660
                        $file_url = $file_url_base . $chunk_file_name;
3661
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3662
                    }
3663
                    
3664
                    if ( !empty($chunk_file_paths) ) {
3665
                        $json['total'] = $items_count;
3666
                        $json['files'] = $chunk_file_paths;
3667
                    } else {
3668
                        $json['error'] = __( 'Fail, something wrong to create csv file.', 'geodirectory' );
3669
                    }
3670
                }
3671
                wp_send_json( $json );
3672
            }
3673
        }
3674
        break;
3675
        case 'prepare_import':
3676
        case 'import_cat':
3677
        case 'import_post':
3678
        case 'import_loc':
3679
        case 'import_hood': {
3680
            // WPML
3681
            $is_wpml = geodir_is_wpml();
3682
            if ($is_wpml) {
3683
                global $sitepress;
3684
                $active_lang = ICL_LANGUAGE_CODE;
3685
            }
3686
            // WPML
3687
            
3688
            ini_set( 'auto_detect_line_endings', true );
3689
            
3690
            $uploads = wp_upload_dir();
3691
            $uploads_dir = $uploads['path'];
3692
            $uploads_subdir = $uploads['subdir'];
3693
            
3694
            $csv_file = isset( $_POST['_file'] ) ? $_POST['_file'] : NULL;
3695
            $import_choice = isset( $_REQUEST['_ch'] ) ? $_REQUEST['_ch'] : 'skip';
3696
            
3697
            $csv_file_arr = explode( '/', $csv_file );
3698
            $csv_filename = end( $csv_file_arr );
3699
            $target_path = $uploads_dir . '/temp_' . $current_user->data->ID . '/' . $csv_filename;
3700
            
3701
            $json['file'] = $csv_file;
3702
            $json['error'] = __( 'The uploaded file is not a valid csv file. Please try again.', 'geodirectory' );
3703
            $file = array();
3704
3705
            if ( $csv_file && $wp_filesystem->is_file( $target_path ) && $wp_filesystem->exists( $target_path ) ) {
0 ignored issues
show
Bug introduced by
The method is_file cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
The method exists cannot be called on $wp_filesystem (of type boolean|string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3706
                $wp_filetype = wp_check_filetype_and_ext( $target_path, $csv_filename );
3707
                
3708
                if (!empty($wp_filetype) && isset($wp_filetype['ext']) && geodir_strtolower($wp_filetype['ext']) == 'csv') {
3709
                    $json['error'] = NULL;
3710
                    $json['rows'] = 0;
3711
                    
3712
                    $lc_all = setlocale(LC_ALL, 0); // Fix issue of fgetcsv ignores special characters when they are at the beginning of line
3713
                    setlocale(LC_ALL, 'en_US.UTF-8');
3714
                    if ( ( $handle = fopen($target_path, "r" ) ) !== FALSE ) {
3715
                        while ( ( $data = fgetcsv( $handle, 100000, "," ) ) !== FALSE ) {
3716
                            if ( !empty( $data ) ) {
3717
                                $file[] = $data;
3718
                            }
3719
                        }
3720
                        fclose($handle);
3721
                    }
3722
                    setlocale(LC_ALL, $lc_all);
3723
3724
                    $json['rows'] = (!empty($file) && count($file) > 1) ? count($file) - 1 : 0;
3725
                    
3726
                    if (!$json['rows'] > 0) {
3727
                        $json['error'] = __('No data found in csv file.', 'geodirectory');
3728
                    }
3729
                } else {
3730
                    wp_send_json( $json );
3731
                }
3732
            } else {
3733
                wp_send_json( $json );
3734
            }
3735
            
3736
            if ( $task == 'prepare_import' || !empty( $json['error'] ) ) {
3737
                wp_send_json( $json );
3738
            }
3739
            
3740
            $total = $json['rows'];
3741
            $limit = isset($_POST['limit']) ? (int)$_POST['limit'] : 1;
3742
            $processed = isset($_POST['processed']) ? (int)$_POST['processed'] : 0;
3743
            
3744
            $count = $limit;
3745
            
3746
            if ($count < $total) {
3747
                $count = $processed + $count;
3748
                if ($count > $total) {
3749
                    $count = $total;
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3750
                }
3751
            } else {
3752
                $count = $total;
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3753
            }
3754
            
3755
            $created = 0;
3756
            $updated = 0;
3757
            $skipped = 0;
3758
            $invalid = 0;
3759
            $invalid_addr = 0;
3760
            $images = 0;
3761
            
3762
            $gd_post_info = array();
0 ignored issues
show
Unused Code introduced by
$gd_post_info is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3763
            $countpost = 0;
0 ignored issues
show
Unused Code introduced by
$countpost is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3764
            
3765
            $post_types = geodir_get_posttypes();
3766
3767
            if ( $task == 'import_cat' ) {
3768
                if (!empty($file)) {
3769
                    $columns = isset($file[0]) ? $file[0] : NULL;
3770
                    
3771 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
3772
                        $json['error'] = CSV_INVAILD_FILE;
3773
                        wp_send_json( $json );
3774
                        exit;
3775
                    }
3776
                    
3777
                    $gd_error_log = __('GD IMPORT CATEGORIES [ROW %d]:', 'geodirectory');
3778
                    
3779
                    for ($i = 1; $i <= $limit; $i++) {
3780
                        $index = $processed + $i;
3781
                        
3782
                        if (isset($file[$index])) {
3783
                            $row = $file[$index];
3784
                            $row = array_map( 'trim', $row );
3785
                            //$row = array_map( 'utf8_encode', $row );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3786
                            
3787
                            $cat_id = '';
3788
                            $cat_name = '';
3789
                            $cat_slug = '';
3790
                            $cat_posttype = '';
3791
                            $cat_parent = '';
3792
                            $cat_description = '';
3793
                            $cat_schema = '';
3794
                            $cat_top_description = '';
3795
                            $cat_image = '';
3796
                            $cat_icon = '';
3797
                            $cat_language = '';
3798
                            $cat_id_original = '';
3799
                            
3800
                            $c = 0;
3801
                            foreach ($columns as $column ) {
3802
                                if ( $column == 'cat_id' ) {
3803
                                    $cat_id = (int)$row[$c];
3804
                                } else if ( $column == 'cat_name' ) {
3805
                                    $cat_name = $row[$c];
3806
                                } else if ( $column == 'cat_slug' ) {
3807
                                    $cat_slug = $row[$c];
3808
                                } else if ( $column == 'cat_posttype' ) {
3809
                                    $cat_posttype = $row[$c];
3810
                                } else if ( $column == 'cat_parent' ) {
3811
                                    $cat_parent = trim($row[$c]);
3812
                                } else if ( $column == 'cat_schema' && $row[$c] != '' ) {
3813
                                    $cat_schema = $row[$c];
3814
                                } else if ( $column == 'cat_description' ) {
3815
                                    $cat_description = $row[$c];
3816
                                } else if ( $column == 'cat_top_description' ) {
3817
                                    $cat_top_description = $row[$c];
3818
                                } else if ( $column == 'cat_image' ) {
3819
                                    $cat_image = $row[$c];
3820
                                } else if ( $column == 'cat_icon' ) {
3821
                                    $cat_icon = $row[$c];
3822
                                }
3823
                                // WPML
3824 View Code Duplication
                                if ( $is_wpml ) {
3825
                                    if ( $column == 'cat_language' ) {
3826
                                        $cat_language = geodir_strtolower( trim( $row[$c] ) );
3827
                                    } else if ( $column == 'cat_id_original' ) {
3828
                                        $cat_id_original = (int)$row[$c];
3829
                                    }
3830
                                }
3831
                                // WPML
3832
                                $c++;
3833
                            }
3834
                            
3835
                            if ( $cat_name == '' || !in_array( $cat_posttype, $post_types ) ) {
3836
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to blank title/invalid post type', 'geodirectory' ) );
3837
                                
3838
                                $invalid++;
3839
                                continue;
3840
                            }
3841
                            
3842
                            // WPML
3843
                            if ($is_wpml && $cat_language != '') {
3844
                                $sitepress->switch_lang($cat_language, true);
3845
                            }
3846
                            // WPML
3847
                                                        
3848
                            $term_data = array();
3849
                            $term_data['name'] = $cat_name;
3850
                            $term_data['slug'] = $cat_slug;
3851
                            $term_data['description'] = $cat_description;
3852
                            $term_data['cat_schema'] = $cat_schema;
3853
                            $term_data['top_description'] = $cat_top_description;
3854
                            $term_data['image'] = $cat_image != '' ? basename( $cat_image ) : '';
3855
                            $term_data['icon'] = $cat_icon != '' ? basename( $cat_icon ) : '';
3856
                            
3857
                            //$term_data = array_map( 'utf8_encode', $term_data );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3858
                            
3859
                            $taxonomy = $cat_posttype . 'category';
3860
                            
3861
                            $term_data['taxonomy'] = $taxonomy;
3862
3863
                            $term_parent_id = 0;
3864
                            if ($cat_parent != "" || (int)$cat_parent > 0) {
3865
                                $term_parent = '';
0 ignored issues
show
Unused Code introduced by
$term_parent is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3866
                                
3867
                                if ( $term_parent = get_term_by( 'name', $cat_parent, $taxonomy ) ) {
3868
                                    //
3869
                                } else if ( $term_parent = get_term_by( 'slug', $cat_parent, $taxonomy ) ) {
3870
                                    //
3871
                                } else if ( $term_parent = get_term_by( 'id', $cat_parent, $taxonomy ) ) {
3872
                                    //
3873
                                } else {
3874
                                    $term_parent_data = array();
3875
                                    $term_parent_data['name'] = $cat_parent;
3876
                                    //$term_parent_data = array_map( 'utf8_encode', $term_parent_data );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3877
                                    $term_parent_data['taxonomy'] = $taxonomy;
3878
                                    
3879
                                    $term_parent_id = (int)geodir_imex_insert_term( $taxonomy, $term_parent_data );
3880
                                }
3881
                                
3882
                                if ( !empty( $term_parent ) && !is_wp_error( $term_parent ) ) {
3883
                                    $term_parent_id = (int)$term_parent->term_id;
3884
                                }
3885
                            }
3886
                            $term_data['parent'] = (int)$term_parent_id;
3887
3888
                            $term_id = NULL;
3889
                            if ( $import_choice == 'update' ) {
3890
                                if ( $cat_id > 0 && $term = (array)term_exists( $cat_id, $taxonomy ) ) {
3891
                                    $term_data['term_id'] = $term['term_id'];
3892
                                    
3893 View Code Duplication
                                    if ( $term_id = geodir_imex_update_term( $taxonomy, $term_data ) ) {
3894
                                        $updated++;
3895
                                    } else {
3896
                                        $invalid++;
3897
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be updated due to invalid data (check & remove if any invalid characters used in data)', 'geodirectory' ) );
3898
                                    }
3899
                                } else if ( $term_data['slug'] != '' && $term = (array)term_exists( $term_data['slug'], $taxonomy ) ) {
3900
                                    $term_data['term_id'] = $term['term_id'];
3901
                                    
3902 View Code Duplication
                                    if ( $term_id = geodir_imex_update_term( $taxonomy, $term_data ) ) {
3903
                                        $updated++;
3904
                                    } else {
3905
                                        $invalid++;
3906
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be updated due to invalid data (check & remove if any invalid characters used in data)', 'geodirectory' ) );
3907
                                    }
3908 View Code Duplication
                                } else {
3909
                                    if ( $term_id = geodir_imex_insert_term( $taxonomy, $term_data ) ) {
3910
                                        $created++;
3911
                                    } else {
3912
                                        $invalid++;
3913
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to invalid data (check & remove if any invalid characters used in data)', 'geodirectory' ) );
3914
                                    }
3915
                                }
3916
                            } else if ( $import_choice == 'skip' ) {
3917
                                if ( $cat_id > 0 && $term = (array)term_exists( $cat_id, $taxonomy ) ) {
3918
                                    $skipped++;
3919
                                } else if ( $term_data['slug'] != '' && $term = (array)term_exists( $term_data['slug'], $taxonomy ) ) {
3920
                                    $skipped++;
3921 View Code Duplication
                                } else {
3922
                                    if ( $term_id = geodir_imex_insert_term( $taxonomy, $term_data ) ) {
3923
                                        $created++;
3924
                                    } else {
3925
                                        $invalid++;
3926
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be updated due to invalid data (check & remove if any invalid characters used in data)', 'geodirectory' ) );
3927
                                    }
3928
                                }
3929
                            } else {
3930
                                $invalid++;
3931
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to invalid data (check & remove if any invalid characters used in data)', 'geodirectory' ) );
3932
                            }
3933
                            
3934
                            if ( $term_id ) {
3935
                                // WPML
3936 View Code Duplication
                                if ($is_wpml && $cat_id_original > 0 && $cat_language != '') {
3937
                                    $wpml_element_type = 'tax_' . $taxonomy;
3938
                                    $source_language = geodir_get_language_for_element( $cat_id_original, $wpml_element_type );
3939
                                    $source_language = $source_language != '' ? $source_language : $sitepress->get_default_language();
3940
3941
                                    $trid = $sitepress->get_element_trid( $cat_id_original, $wpml_element_type );
3942
                                    
3943
                                    $sitepress->set_element_language_details( $term_id, $wpml_element_type, $trid, $cat_language, $source_language );
3944
                                }
3945
                                // WPML
3946
                                
3947
                                if ( isset( $term_data['top_description'] ) ) {
3948
                                    update_tax_meta( $term_id, 'ct_cat_top_desc', $term_data['top_description'], $cat_posttype );
3949
                                }
3950
                                
3951
                                if ( isset( $term_data['cat_schema'] ) ) {
3952
                                    update_tax_meta( $term_id, 'ct_cat_schema', $term_data['cat_schema'], $cat_posttype );
3953
                                }
3954
            
3955
                                $attachment = false;
3956 View Code Duplication
                                if ( isset( $term_data['image'] ) && $term_data['image'] != '' ) {
3957
                                    $cat_image = geodir_get_default_catimage( $term_id, $cat_posttype );
3958
                                    $cat_image = !empty( $cat_image ) && isset( $cat_image['src'] ) ? $cat_image['src'] : '';
3959
                                    
3960
                                    if ( basename($cat_image) != $term_data['image'] ) {
3961
                                        $attachment = true;
3962
                                        update_tax_meta( $term_id, 'ct_cat_default_img', array( 'id' => 'image', 'src' => $uploads['url'] . '/' . $term_data['image'] ), $cat_posttype );
3963
                                    }
3964
                                }
3965
                                
3966 View Code Duplication
                                if ( isset( $term_data['icon'] ) && $term_data['icon'] != '' ) {
3967
                                    $cat_icon = get_tax_meta( $term_id, 'ct_cat_icon', false, $cat_posttype );
3968
                                    $cat_icon = !empty( $cat_icon ) && isset( $cat_icon['src'] ) ? $cat_icon['src'] : '';
3969
                                        
3970
                                    if ( basename($cat_icon) != $term_data['icon'] ) {
3971
                                        $attachment = true;
3972
                                        update_tax_meta( $term_id, 'ct_cat_icon', array( 'id' => 'icon', 'src' => $uploads['url'] . '/' . $term_data['icon'] ), $cat_posttype );
3973
                                    }
3974
                                }
3975
                                
3976
                                if ( $attachment ) {
3977
                                    $images++;
3978
                                }
3979
                            }
3980
                            
3981
                            // WPML
3982
                            if ($is_wpml && $cat_language != '') {
3983
                                $sitepress->switch_lang($active_lang, true);
3984
                            }
3985
                            // WPML
3986
                        }
3987
                    }
3988
                }
3989
                
3990
                $json = array();
3991
                $json['processed'] = $limit;
3992
                $json['created'] = $created;
3993
                $json['updated'] = $updated;
3994
                $json['skipped'] = $skipped;
3995
                $json['invalid'] = $invalid;
3996
                $json['images'] = $images;
3997
                
3998
                wp_send_json( $json );
3999
                exit;
4000
            } else if ( $task == 'import_post' ) {
4001
                //run some stuff to make the import quicker
4002
                wp_defer_term_counting( true );
4003
                wp_defer_comment_counting( true );
4004
                $wpdb->query( 'SET autocommit = 0;' );
4005
4006
                //remove_all_actions('publish_post');
4007
                //remove_all_actions('transition_post_status');
4008
                //remove_all_actions('publish_future_post');
4009
4010
                if (!empty($file)) {
4011
                    $is_claim_active = is_plugin_active( 'geodir_claim_listing/geodir_claim_listing.php' ) && get_option('geodir_claim_enable') === 'yes' ? true : false;
4012
                    $wp_post_statuses = get_post_statuses(); // All of the WordPress supported post statuses.
4013
                    $default_status = 'publish';
4014
                    $current_date = date_i18n( 'Y-m-d', time() );
4015
                    
4016
                    $columns = isset($file[0]) ? $file[0] : NULL;
4017
                    
4018 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4019
                        $json['error'] = CSV_INVAILD_FILE;
4020
                        wp_send_json( $json );
4021
                        exit;
4022
                    }
4023
4024
                    $gd_error_log = __('GD IMPORT LISTINGS [ROW %d]:', 'geodirectory');
4025
                    $wp_chars_error = __( '(check & remove if any invalid characters used in data)', 'geodirectory' );
4026
                    $processed_actual = 0;
4027
                    for ($i = 1; $i <= $limit; $i++) {
4028
                        $index = $processed + $i;
4029
                        $gd_post = array();
4030
                        
4031
                        if (isset($file[$index])) {
4032
                            $processed_actual++;
4033
                            $row = $file[$index];
4034
                            $row = array_map( 'trim', $row );
4035
                            //$row = array_map( 'utf8_encode', $row );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
4036
                            $row = array_map( 'addslashes_gpc', $row );
4037
                            
4038
                            $post_id = '';
4039
                            $post_title = '';
4040
                            $post_author = '';
4041
                            $post_content = '';
4042
                            $post_category_arr = array();
4043
                            $default_category = '';
4044
                            $post_tags = array();
4045
                            $post_type = '';
4046
                            $post_status = '';
4047
                            $geodir_video = '';
0 ignored issues
show
Unused Code introduced by
$geodir_video is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4048
                            $post_address = '';
4049
                            $post_city = '';
4050
                            $post_region = '';
4051
                            $post_country = '';
4052
                            $post_zip = '';
0 ignored issues
show
Unused Code introduced by
$post_zip is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4053
                            $post_latitude = '';
4054
                            $post_longitude = '';
4055
                            $post_neighbourhood = '';
4056
                            $neighbourhood_latitude = '';
4057
                            $neighbourhood_longitude = '';
4058
                            $geodir_timing = '';
0 ignored issues
show
Unused Code introduced by
$geodir_timing is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4059
                            $geodir_contact = '';
0 ignored issues
show
Unused Code introduced by
$geodir_contact is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4060
                            $geodir_email = '';
0 ignored issues
show
Unused Code introduced by
$geodir_email is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4061
                            $geodir_website = '';
0 ignored issues
show
Unused Code introduced by
$geodir_website is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4062
                            $geodir_twitter = '';
0 ignored issues
show
Unused Code introduced by
$geodir_twitter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4063
                            $geodir_facebook = '';
0 ignored issues
show
Unused Code introduced by
$geodir_facebook is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4064
                            $geodir_twitter = '';
0 ignored issues
show
Unused Code introduced by
$geodir_twitter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4065
                            $post_images = array();
4066
                            
4067
                            $expire_date = 'Never';
4068
                            
4069
                            $language = '';
4070
                            $original_post_id = '';
4071
                            
4072
                            $c = 0;
4073
                            foreach ($columns as $column ) {
4074
                                $gd_post[$column] = $row[$c];
4075
                                
4076
                                if ( $column == 'post_id' ) {
4077
                                    $post_id = $row[$c];
4078
                                } else if ( $column == 'post_title' ) {
4079
                                    $post_title = sanitize_text_field($row[$c]);
4080
                                } else if ( $column == 'post_author' ) {
4081
                                    $post_author = $row[$c];
4082
                                } else if ( $column == 'post_content' ) {
4083
                                    $post_content = $row[$c];
4084
                                } else if ( $column == 'post_category' && $row[$c] != '' ) {
4085
                                    $post_category_arr = explode( ',', $row[$c] );
4086
                                } else if ( $column == 'default_category' ) {
4087
                                    $default_category = wp_kses_normalize_entities($row[$c]);
4088
                                } else if ( $column == 'post_tags' && $row[$c] != '' ) {
4089
                                    $post_tags = explode( ',', sanitize_text_field($row[$c]) );
4090
                                } else if ( $column == 'post_type' ) {
4091
                                    $post_type = $row[$c];
4092
                                } else if ( $column == 'post_status' ) {
4093
                                    $post_status = sanitize_key( $row[$c] );
4094
                                } else if ( $column == 'is_featured' ) {
4095
                                    $is_featured = (int)$row[$c];
4096
                                } else if ( $column == 'geodir_video' ) {
4097
                                    $geodir_video = $row[$c];
0 ignored issues
show
Unused Code introduced by
$geodir_video is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4098
                                } else if ( $column == 'post_address' ) {
4099
                                    $post_address = sanitize_text_field($row[$c]);
4100
                                } else if ( $column == 'post_city' ) {
4101
                                    $post_city = sanitize_text_field($row[$c]);
4102
                                } else if ( $column == 'post_region' ) {
4103
                                    $post_region = sanitize_text_field($row[$c]);
4104
                                } else if ( $column == 'post_country' ) {
4105
                                    $post_country = sanitize_text_field($row[$c]);
4106
                                } else if ( $column == 'post_zip' ) {
4107
                                    $post_zip = sanitize_text_field($row[$c]);
0 ignored issues
show
Unused Code introduced by
$post_zip is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4108
                                } else if ( $column == 'post_latitude' ) {
4109
                                    $post_latitude = sanitize_text_field($row[$c]);
4110
                                } else if ( $column == 'post_longitude' ) {
4111
                                    $post_longitude = sanitize_text_field($row[$c]);
4112
                                } else if ( $column == 'post_neighbourhood' ) {
4113
                                    $post_neighbourhood = sanitize_text_field($row[$c]);
4114
                                    unset($gd_post[$column]);
4115
                                } else if ( $column == 'neighbourhood_latitude' ) {
4116
                                    $neighbourhood_latitude = sanitize_text_field($row[$c]);
4117
                                } else if ( $column == 'neighbourhood_longitude' ) {
4118
                                    $neighbourhood_longitude = sanitize_text_field($row[$c]);
4119
                                } else if ( $column == 'geodir_timing' ) {
4120
                                    $geodir_timing = sanitize_text_field($row[$c]);
0 ignored issues
show
Unused Code introduced by
$geodir_timing is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4121
                                } else if ( $column == 'geodir_contact' ) {
4122
                                    $geodir_contact = sanitize_text_field($row[$c]);
0 ignored issues
show
Unused Code introduced by
$geodir_contact is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4123
                                } else if ( $column == 'geodir_email' ) {
4124
                                    $geodir_email = sanitize_email($row[$c]);
0 ignored issues
show
Unused Code introduced by
$geodir_email is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4125
                                } else if ( $column == 'geodir_website' ) {
4126
                                    $geodir_website = sanitize_text_field($row[$c]);
0 ignored issues
show
Unused Code introduced by
$geodir_website is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4127
                                } else if ( $column == 'geodir_twitter' ) {
4128
                                    $geodir_twitter = sanitize_text_field($row[$c]);
0 ignored issues
show
Unused Code introduced by
$geodir_twitter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4129
                                } else if ( $column == 'geodir_facebook' ) {
4130
                                    $geodir_facebook = sanitize_text_field($row[$c]);
0 ignored issues
show
Unused Code introduced by
$geodir_facebook is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4131
                                } else if ( $column == 'IMAGE' && !empty( $row[$c] ) && $row[$c] != '' ) {
4132
                                    $post_images[] = $row[$c];
4133
                                } else if ( $column == 'alive_days' && (int)$row[$c] > 0 ) {
4134
                                    $expire_date = date_i18n( 'Y-m-d', strtotime( $current_date . '+' . (int)$row[$c] . ' days' ) );
4135
                                } else if ( $column == 'expire_date' && $row[$c] != '' && geodir_strtolower($row[$c]) != 'never' ) {
4136
                                    $row[$c] = str_replace('/', '-', $row[$c]);
4137
                                    $expire_date = date_i18n( 'Y-m-d', strtotime( $row[$c] ) );
4138
                                }
4139
                                // WPML
4140
                                if ($is_wpml) {
4141 View Code Duplication
                                    if ($column == 'language') {
4142
                                        $language = geodir_strtolower(trim($row[$c]));
4143
                                    } else if ($column == 'original_post_id') {
4144
                                        $original_post_id = (int)$row[$c];
4145
                                    }
4146
                                }
4147
                                // WPML
4148
                                $c++;
4149
                            }
4150
                            // listing claimed or not
4151
                            if ($is_claim_active && isset($gd_post['claimed'])) {
4152
                                $gd_post['claimed'] = (int)$gd_post['claimed'] == 1 ? 1 : 0;
4153
                            }
4154
                            
4155
                            // WPML
4156
                            if ($is_wpml && $language != '') {
4157
                                $sitepress->switch_lang($language, true);
4158
                            }
4159
                            // WPML
4160
4161
                            $gd_post['IMAGE'] = $post_images;
4162
                            
4163
                            $post_status = !empty( $post_status ) ? sanitize_key( $post_status ) : $default_status;
4164
                            $post_status = !empty( $wp_post_statuses ) && !isset( $wp_post_statuses[$post_status] ) ? $default_status : $post_status;
4165
                                                                                                                
4166
                            $valid = true;
4167
                            
4168
                            if ( $post_title == '' || !in_array( $post_type, $post_types ) ) {
4169
                                $invalid++;
4170
                                $valid = false;
4171
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to blank title/invalid post type', 'geodirectory' ) );
4172
                            }
4173
                            
4174
                            $location_allowed = function_exists( 'geodir_cpt_no_location' ) && geodir_cpt_no_location( $post_type ) ? false : true;
4175
                            if ( $location_allowed ) {
4176
                                $location_result = geodir_get_default_location();
4177
                                if ( $post_address == '' || $post_city == '' || $post_region == '' || $post_country == '' || $post_latitude == '' || $post_longitude == '' ) {
4178
                                    $invalid_addr++;
4179
                                    $valid = false;
4180
                                    geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to blank/invalid address(city, region, country, latitude, longitude).', 'geodirectory' ) );
4181
                                } else if ( !empty( $location_result ) && $location_result->location_id == 0 ) {
4182
                                    if ( ( geodir_strtolower( $post_city ) != geodir_strtolower( $location_result->city ) ) || ( geodir_strtolower( $post_region ) != geodir_strtolower( $location_result->region ) ) || (geodir_strtolower( $post_country ) != geodir_strtolower( $location_result->country ) ) ) {
4183
                                        $invalid_addr++;
4184
                                        $valid = false;
4185
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to blank/invalid address(city, region, country, latitude, longitude).', 'geodirectory' ) );
4186
                                    } else {
4187
                                        if (!$location_manager) {
4188
                                            $gd_post['post_locations'] = '[' . $location_result->city_slug . '],[' . $location_result->region_slug . '],[' . $location_result->country_slug . ']'; // Set the default location when location manager not activated.
4189
                                        }
4190
                                    }
4191
                                }
4192
                            }
4193
                            
4194
                            if ( !$valid ) {
4195
                                continue;
4196
                            }
4197
4198
                            $cat_taxonomy = $post_type . 'category';
4199
                            $tags_taxonomy = $post_type . '_tags';
4200
                            
4201
                            if ($default_category != '' && !in_array($default_category, $post_category_arr)) {
4202
                                $post_category_arr = array_merge(array($default_category), $post_category_arr);
4203
                            }
4204
4205
                            $post_category = array();
4206
                            $default_category_id = NULL;
4207
                            if ( !empty( $post_category_arr ) ) {
4208
                                foreach ( $post_category_arr as $value ) {
4209
                                    $category_name = wp_kses_normalize_entities( trim( $value ) );
4210
                                    
4211
                                    if ( $category_name != '' ) {
4212
                                        $term_category = array();
4213
                                        
4214
                                        if ( $term = get_term_by( 'name', $category_name, $cat_taxonomy ) ) {
4215
                                            $term_category = $term;
4216
                                        } else if ( $term = get_term_by( 'slug', $category_name, $cat_taxonomy ) ) {
4217
                                            $term_category = $term;
4218
                                        } else {
4219
                                            $term_data = array();
4220
                                            $term_data['name'] = $category_name;
4221
                                            $term_data['taxonomy'] = $cat_taxonomy;
4222
                                            
4223
                                            $term_id = geodir_imex_insert_term( $cat_taxonomy, $term_data );
4224
                                            if ( $term_id ) {
4225
                                                $term_category = get_term( $term_id, $cat_taxonomy );
4226
                                            }
4227
                                        }
4228
                                        
4229
                                        if ( !empty( $term_category ) && !is_wp_error( $term_category ) ) {
4230
                                            $post_category[] = intval($term_category->term_id);
4231
                                            
4232
                                            if ($category_name == $default_category) {
4233
                                                $default_category_id = intval($term_category->term_id);
4234
                                            }
4235
                                        }
4236
                                    }
4237
                                }
4238
                            }
4239
4240
                            $save_post = array();
4241
                            $save_post['post_title'] = $post_title;
4242
                            $save_post['post_content'] = $post_content;
4243
                            $save_post['post_type'] = $post_type;
4244
                            $save_post['post_author'] = $post_author;
4245
                            $save_post['post_status'] = $post_status;
4246
                            $save_post['post_category'] = $post_category;
4247
                            $save_post['post_tags'] = $post_tags;
4248
4249
                            $saved_post_id = NULL;
4250
                            if ( $import_choice == 'update' ) {
4251
                                $gd_wp_error = __( 'Unable to add listing, please check the listing data.', 'geodirectory' );
4252
                                
4253
                                if ( $post_id > 0 && get_post( $post_id ) ) {
4254
                                    $save_post['ID'] = $post_id;
4255
                                    
4256 View Code Duplication
                                    if ( $saved_post_id = wp_update_post( $save_post, true ) ) {
4257
                                        if ( is_wp_error( $saved_post_id ) ) {
4258
                                            $gd_wp_error = $saved_post_id->get_error_message() . ' ' . $wp_chars_error;
4259
                                            $saved_post_id = 0;
4260
                                        } else {
4261
                                            $saved_post_id = $post_id;
4262
                                            $updated++;
4263
                                        }
4264
                                    }
4265 View Code Duplication
                                } else {
4266
                                    if ( $saved_post_id = wp_insert_post( $save_post, true ) ) {
4267
                                        if ( is_wp_error( $saved_post_id ) ) {
4268
                                            $gd_wp_error = $saved_post_id->get_error_message() . ' ' . $wp_chars_error;
4269
                                            $saved_post_id = 0;
4270
                                        } else {
4271
                                            $created++;
4272
                                        }
4273
                                    }
4274
                                }
4275
                                
4276
                                if ( !$saved_post_id > 0 ) {
4277
                                    $invalid++;
4278
                                    geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_wp_error );
4279
                                }
4280
                            } else if ( $import_choice == 'skip' ) {
4281
                                if ( $post_id > 0 && get_post( $post_id ) ) {
4282
                                    $skipped++;	
4283
                                } else {
4284
                                    if ( $saved_post_id = wp_insert_post( $save_post, true ) ) {
4285
                                        if ( is_wp_error( $saved_post_id ) ) {
4286
                                            $invalid++;
4287
                                            
4288
                                            geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $saved_post_id->get_error_message() . ' ' . $wp_chars_error );
4289
                                            $saved_post_id = 0;
4290
                                        } else {
4291
                                            $created++;
4292
                                        }
4293
                                    } else {
4294
                                        $invalid++;
4295
                                        
4296
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $wp_chars_error );
4297
                                    }
4298
                                }
4299
                            } else {
4300
                                $invalid++;
4301
                                
4302
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $wp_chars_error );
4303
                            }
4304
4305
                            if ( (int)$saved_post_id > 0 ) {
4306
                                // WPML
4307 View Code Duplication
                                if ($is_wpml && $original_post_id > 0 && $language != '') {
4308
                                    $wpml_post_type = 'post_' . $post_type;
4309
                                    $source_language = geodir_get_language_for_element( $original_post_id, $wpml_post_type );
4310
                                    $source_language = $source_language != '' ? $source_language : $sitepress->get_default_language();
4311
4312
                                    $trid = $sitepress->get_element_trid( $original_post_id, $wpml_post_type );
4313
                                    
4314
                                    $sitepress->set_element_language_details( $saved_post_id, $wpml_post_type, $trid, $language, $source_language );
4315
                                }
4316
                                // WPML
4317
                                $gd_post_info = geodir_get_post_info( $saved_post_id );
4318
                                
4319
                                $gd_post['post_id'] = $saved_post_id;
4320
                                $gd_post['ID'] = $saved_post_id;
4321
                                $gd_post['post_tags'] = $post_tags;
4322
                                $gd_post['post_title'] = $post_title;
4323
                                $gd_post['post_status'] = $post_status;
4324
                                $gd_post['submit_time'] = time();
4325
                                $gd_post['submit_ip'] = $_SERVER['REMOTE_ADDR'];
4326
                                                    
4327
                                // post location
4328
                                $post_location_id = 0;
4329
                                if ( $location_allowed && !empty( $location_result ) && $location_result->location_id > 0 ) {
4330
                                    $gd_post['post_neighbourhood'] = '';
4331
                                    
4332
                                    $post_location_info = array(
4333
                                                                'city' => $post_city,
4334
                                                                'region' => $post_region,
4335
                                                                'country' => $post_country,
4336
                                                                'geo_lat' => $post_latitude,
4337
                                                                'geo_lng' => $post_longitude
4338
                                                            );
4339
                                    if ( $location_id = (int)geodir_add_new_location( $post_location_info ) ) {
4340
                                        $post_location_id = $location_id;
4341
                                    }
4342
                                    
4343
                                    if ($post_location_id > 0 && $neighbourhood_active && !empty($post_neighbourhood)) {
4344
                                        $neighbourhood_info = geodir_location_neighbourhood_by_name_loc_id($post_neighbourhood, $post_location_id);
4345
4346
                                        $hood_data = array();
4347
                                        $hood_data['hood_location_id'] = $post_location_id;
4348
                                        $hood_data['hood_name'] = $post_neighbourhood;
4349
                                        
4350
                                        if (!empty($neighbourhood_info)) {
4351
                                            $hood_data['hood_id'] = $neighbourhood_info->hood_id;
4352
                                            $hood_data['hood_slug'] = $neighbourhood_info->hood_slug;
4353
                                            
4354
                                            if (empty($neighbourhood_latitude) || empty($neighbourhood_longitude)) {
4355
                                                $neighbourhood_latitude = $neighbourhood_info->hood_latitude;
4356
                                                $neighbourhood_longitude = $neighbourhood_info->hood_longitude;
4357
                                            }
4358
                                        }
4359
                                        
4360
                                        if (empty($neighbourhood_latitude) || empty($neighbourhood_longitude)) {
4361
                                            $neighbourhood_latitude = $neighbourhood_info->hood_latitude;
0 ignored issues
show
Unused Code introduced by
$neighbourhood_latitude is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4362
                                            $neighbourhood_longitude = $neighbourhood_info->hood_longitude;
0 ignored issues
show
Unused Code introduced by
$neighbourhood_longitude is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4363
                                        }
4364
                                        
4365
                                        $hood_data['hood_latitude'] = $post_latitude;
4366
                                        $hood_data['hood_longitude'] = $post_longitude;
4367
4368
                                        $neighbourhood_info = geodir_location_insert_update_neighbourhood($hood_data);
4369
                                        if (!empty($neighbourhood_info) && isset($neighbourhood_info->hood_slug)) {
4370
                                            $gd_post['post_neighbourhood'] = $neighbourhood_info->hood_slug;
4371
                                        }
4372
                                    }
4373
                                }
4374
                                $gd_post['post_location_id'] = $post_location_id;
4375
                                
4376
                                // post package info
4377
                                $package_id = isset( $gd_post['package_id'] ) && !empty( $gd_post['package_id'] ) ? (int)$gd_post['package_id'] : 0;
4378
                                if (!$package_id && !empty($gd_post_info) && isset($gd_post_info->package_id) && $gd_post_info->package_id) {
4379
                                    $package_id = $gd_post_info->package_id;
4380
                                }
4381
                                
4382
                                $package_info = array();
4383
                                if ($package_id && function_exists('geodir_get_package_info_by_id')) {
4384
                                    $package_info = (array)geodir_get_package_info_by_id($package_id);
4385
                                    
4386
                                    if (!(!empty($package_info) && isset($package_info['post_type']) && $package_info['post_type'] == $post_type)) {
4387
                                        $package_info = array();
4388
                                    }
4389
                                }
4390
                                
4391
                                if (empty($package_info)) {
4392
                                    $package_info = (array)geodir_post_package_info( array(), '', $post_type );
4393
                                }
4394
                                 
4395
                                if (!empty($package_info))	 {
4396
                                    $package_id = $package_info['pid'];
4397
                                    
4398
                                    if (isset($gd_post['alive_days']) || isset($gd_post['expire_date'])) {
4399
                                        $gd_post['expire_date'] = $expire_date;
4400
                                    } else {
4401
                                        if ( isset( $package_info['days'] ) && (int)$package_info['days'] > 0 ) {
4402
                                            $gd_post['alive_days'] = (int)$package_info['days'];
4403
                                            $gd_post['expire_date'] = date_i18n( 'Y-m-d', strtotime( $current_date . '+' . (int)$package_info['days'] . ' days' ) );
4404
                                        } else {
4405
                                            $gd_post['expire_date'] = 'Never';
4406
                                        }
4407
                                    }
4408
                                    
4409
                                    $gd_post['package_id'] = $package_id;
4410
                                }
4411
4412
                                $table = $plugin_prefix . $post_type . '_detail';
0 ignored issues
show
Unused Code introduced by
$table is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4413
                                
4414
                                if ($post_type == 'gd_event') {
4415
                                    $gd_post = geodir_imex_process_event_data($gd_post);
4416
                                }
4417
                                
4418
                                if (isset($gd_post['post_id'])) {
4419
                                    unset($gd_post['post_id']);
4420
                                }
4421
4422
                                // Export franchise fields
4423
                                $is_franchise_active = is_plugin_active( 'geodir_franchise/geodir_franchise.php' ) && geodir_franchise_enabled( $post_type ) ? true : false;
4424
                                if ($is_franchise_active) {
4425
                                    if ( isset( $gd_post['gd_is_franchise'] ) && (int)$gd_post['gd_is_franchise'] == 1 ) {
4426
                                        $gd_franchise_lock = array();
4427
                                        
4428
                                        if ( isset( $gd_post['gd_franchise_lock'] ) ) {
4429
                                            $gd_franchise_lock = str_replace(" ", "", $gd_post['gd_franchise_lock'] );
4430
                                            $gd_franchise_lock = trim( $gd_franchise_lock );
4431
                                            $gd_franchise_lock = explode( ",", $gd_franchise_lock );
4432
                                        }
4433
                                        
4434
                                        update_post_meta( $saved_post_id, 'gd_is_franchise', 1 );
4435
                                        update_post_meta( $saved_post_id, 'gd_franchise_lock', $gd_franchise_lock );
4436
                                    } else {
4437
                                        if ( isset( $gd_post['franchise'] ) && (int)$gd_post['franchise'] > 0 && geodir_franchise_check( (int)$gd_post['franchise'] ) ) {
4438
                                            geodir_save_post_meta( $saved_post_id, 'franchise', (int)$gd_post['franchise'] );
4439
                                        }
4440
                                    }
4441
                                }
4442
                                
4443
                                if (!empty($save_post['post_category']) && is_array($save_post['post_category'])) {
4444
                                    $save_post['post_category'] = array_unique( array_map( 'intval', $save_post['post_category'] ) );
4445
                                    if ($default_category_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $default_category_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
4446
                                        $save_post['post_default_category'] = $default_category_id;
4447
                                        $gd_post['default_category'] = $default_category_id;
4448
                                    }
4449
                                    $gd_post[$cat_taxonomy] = $save_post['post_category'];
4450
                                }
4451
                                
4452
                                // Save post info
4453
                                geodir_save_post_info( $saved_post_id, $gd_post );
4454
                                // post taxonomies
4455
                                if ( !empty( $save_post['post_category'] ) ) {
4456
                                    wp_set_object_terms( $saved_post_id, $save_post['post_category'], $cat_taxonomy );
4457
                                    
4458
                                    $post_default_category = isset( $save_post['post_default_category'] ) ? $save_post['post_default_category'] : '';
4459
                                    if ($default_category_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $default_category_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
4460
                                        $post_default_category = $default_category_id;
4461
                                    }
4462
                                    $post_cat_ids = geodir_get_post_meta($saved_post_id, $cat_taxonomy);
4463
                                    $save_post['post_category'] = !empty($post_cat_ids) ? explode(",", trim($post_cat_ids, ",")) : $save_post['post_category'];
4464
                                    $post_category_str = !empty($save_post['post_category']) ? implode(",y:#", $save_post['post_category']) . ',y:' : '';
4465
                                    
4466
                                    if ($post_category_str != '' && $post_default_category) {
4467
                                        $post_category_str = str_replace($post_default_category . ',y:', $post_default_category . ',y,d:', $post_category_str);
4468
                                    }
4469
                                    
4470
                                    $post_category_str = $post_category_str != '' ? array($cat_taxonomy => $post_category_str) : '';
4471
                                    
4472
                                    geodir_set_postcat_structure( $saved_post_id, $cat_taxonomy, $post_default_category, $post_category_str );
4473
                                }
4474
4475
                                if ( !empty( $save_post['post_tags'] ) ) {
4476
                                    wp_set_object_terms( $saved_post_id, $save_post['post_tags'], $tags_taxonomy );
4477
                                }
4478
4479
                                // Post images
4480
                                if ( !empty( $post_images ) ) {
4481
                                    $post_images = array_unique($post_images);
4482
                                    
4483
                                    $old_post_images_arr = array();
4484
                                    $saved_post_images_arr = array();
4485
                                    
4486
                                    $order = 1;
4487
                                    
4488
                                    $old_post_images = geodir_get_images( $saved_post_id );
4489
                                    if (!empty($old_post_images)) {
4490
                                        foreach( $old_post_images as $old_post_image ) {
0 ignored issues
show
Bug introduced by
The expression $old_post_images of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4491
                                            if (!empty($old_post_image) && isset($old_post_image->file) && $old_post_image->file != '') {
4492
                                                $old_post_images_arr[] = $old_post_image->file;
4493
                                            }
4494
                                        }
4495
                                    }
4496
4497
                                    foreach ( $post_images as $post_image ) {
4498
                                        $image_name = basename( $post_image );
4499
                                        $saved_post_images_arr[] = $image_name;
4500
                                        
4501
                                        if (!empty($old_post_images_arr) && in_array( $image_name, $old_post_images_arr) ) {
4502
                                            continue; // Skip if image already exists.
4503
                                        }
4504
                                        
4505
                                        $image_name_parts = explode( '.', $image_name );
4506
                                        array_pop( $image_name_parts );
4507
                                        $proper_image_name = implode( '.', $image_name_parts );
4508
                                        
4509
                                        $arr_file_type = wp_check_filetype( $image_name );
4510
                                        
4511
                                        if ( !empty( $arr_file_type ) ) {
4512
                                            $uploaded_file_type = $arr_file_type['type'];
4513
                                            
4514
                                            $attachment = array();
4515
                                            $attachment['post_id'] = $saved_post_id;
4516
                                            $attachment['title'] = $proper_image_name;
4517
                                            $attachment['content'] = '';
4518
                                            $attachment['file'] = $uploads_subdir . '/' . $image_name;
4519
                                            $attachment['mime_type'] = $uploaded_file_type;
4520
                                            $attachment['menu_order'] = $order;
4521
                                            $attachment['is_featured'] = 0;
4522
4523
                                            $attachment_set = '';
4524
                                            foreach ( $attachment as $key => $val ) {
4525
                                                if ( $val != '' ) {
4526
                                                    $attachment_set .= $key . " = '" . $val . "', ";
4527
                                                }
4528
                                            }
4529
                                            $attachment_set = trim( $attachment_set, ", " );
4530
                                                                                        
4531
                                            // Add new attachment
4532
                                            $wpdb->query( "INSERT INTO " . GEODIR_ATTACHMENT_TABLE . " SET " . $attachment_set );
4533
                                                                                        
4534
                                            $order++;
4535
                                        }
4536
                                    }
4537
4538
                                    $saved_post_images_sql = !empty($saved_post_images_arr) ? " AND ( file NOT LIKE '%/" . implode("' AND file NOT LIKE '%/",  $saved_post_images_arr) . "' )" : '';
4539
                                    // Remove previous attachment
4540
                                    $wpdb->query( "DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id = " . (int)$saved_post_id . " " . $saved_post_images_sql );
4541
                                    
4542
                                    if ( !empty( $saved_post_images_arr ) ) {
4543
                                        geodir_set_wp_featured_image($saved_post_id);
4544
                                        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
4545
                                        $menu_order = 1;
4546
                                        
4547
                                        foreach ( $saved_post_images_arr as $img_name ) {
4548
                                            $wpdb->query( $wpdb->prepare( "UPDATE " . GEODIR_ATTACHMENT_TABLE . " SET menu_order = %d WHERE post_id =%d AND file LIKE %s", array( $menu_order, $saved_post_id, '%/' . $img_name ) ) );
4549
                                            
4550
                                            if( $menu_order == 1 ) {
4551
                                                if ( $featured_image = $wpdb->get_var( $wpdb->prepare( "SELECT file FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id =%d AND file LIKE %s", array( $saved_post_id, '%/' . $img_name ) ) ) ) {
4552
                                                    $wpdb->query( $wpdb->prepare( "UPDATE " . $table . " SET featured_image = %s WHERE post_id =%d", array( $featured_image, $saved_post_id ) ) );
4553
                                                }
4554
                                            }
4555
                                            $menu_order++;
4556
                                        }*/
4557
                                    }
4558
                                    
4559
                                    if ( $order > 1 ) {
4560
                                        $images++;
4561
                                    }
4562
                                }
4563
4564
                                /** This action is documented in geodirectory-functions/post-functions.php */
4565
                                do_action( 'geodir_after_save_listing', $saved_post_id, $gd_post );
4566
                                
4567
                                if (isset($is_featured)) {
4568
                                    geodir_save_post_meta($saved_post_id, 'is_featured', $is_featured);
4569
                                }
4570
                                if (isset($gd_post['expire_date'])) {
4571
                                    geodir_save_post_meta($saved_post_id, 'expire_date', $gd_post['expire_date']);
4572
                                }
4573
                            }
4574
                            
4575
                            // WPML
4576
                            if ($is_wpml && $language != '') {
4577
                                $sitepress->switch_lang($active_lang, true);
4578
                            }
4579
                            // WPML
4580
                        }
4581
                    }
4582
                }
4583
4584
                //undo some stuff to make the import quicker
4585
                wp_defer_term_counting( false );
4586
                wp_defer_comment_counting( false );
4587
                $wpdb->query( 'COMMIT;' );
4588
                $wpdb->query( 'SET autocommit = 1;' );
4589
4590
                $json = array();
4591
                $json['processed'] = $processed_actual;
0 ignored issues
show
Bug introduced by
The variable $processed_actual does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4592
                $json['created'] = $created;
4593
                $json['updated'] = $updated;
4594
                $json['skipped'] = $skipped;
4595
                $json['invalid'] = $invalid;
4596
                $json['invalid_addr'] = $invalid_addr;
4597
                $json['images'] = $images;
4598
                
4599
                wp_send_json( $json );
4600
                exit;
4601
            } else if ( $task == 'import_loc' ) {
4602
                global $gd_post_types;
4603
                $gd_post_types = $post_types;
4604
                
4605
                if (!empty($file)) {
4606
                    $columns = isset($file[0]) ? $file[0] : NULL;
4607
                    
4608 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4609
                        $json['error'] = __('File you are uploading is not valid. Columns does not matching.', 'geodirectory');
4610
                        wp_send_json( $json );
4611
                    }
4612
                    
4613
                    $gd_error_log = __('GD IMPORT LOCATIONS [ROW %d]:', 'geodirectory');
4614
                    $gd_error_location = __( 'Could not be saved due to blank/invalid address(city, region, country, latitude, longitude)', 'geodirectory' );
4615
                    for ($i = 1; $i <= $limit; $i++) {
4616
                        $index = $processed + $i;
4617
                        
4618
                        if (isset($file[$index])) {
4619
                            $row = $file[$index];
4620
                            $row = array_map( 'trim', $row );
4621
                            $data = array();
4622
                            
4623
                            foreach ($columns as $c => $column ) {
4624
                                if (in_array($column, array('location_id', 'latitude', 'longitude', 'city', 'city_slug', 'region', 'country', 'city_meta_title', 'city_meta_desc', 'city_desc', 'region_meta_title', 'region_meta_desc', 'region_desc', 'country_meta_title', 'country_meta_desc', 'country_desc'))) {
4625
                                    $data[$column] = $row[$c];
4626
                                }
4627
                            }
4628
4629
                            if ( empty($data['city']) || empty($data['region']) || empty($data['country']) || empty($data['latitude']) || empty($data['longitude']) ) {
4630
                                $invalid++;
4631
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4632
                                continue;
4633
                            }
4634
                            
4635
                            $data['location_id'] = isset($data['location_id']) ? absint($data['location_id']) : 0;
4636
                            
4637
                            if ( $import_choice == 'update' ) {
4638
                                if ( (int)$data['location_id'] > 0 && $location = geodir_get_location_by_id( '', (int)$data['location_id'] ) ) {
4639
                                    if ( $location_id = geodir_location_update_city( $data, true, $location ) ) {
0 ignored issues
show
Unused Code introduced by
$location_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4640
                                        $updated++;
4641
                                    } else {
4642
                                        $invalid++;
4643
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4644
                                    }
4645
                                } else if ( !empty( $data['city_slug'] ) && $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'] ) ) ) {
4646
                                    $data['location_id'] = (int)$location->location_id;
4647
                                    
4648
                                    if ( $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'], 'country' => $data['country'], 'region' => $data['region'] ) ) ) {
4649
                                        $data['location_id'] = (int)$location->location_id;
4650
                                    } else if ( $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'], 'region' => $data['region'] ) ) ) {
4651
                                        $data['location_id'] = (int)$location->location_id;
4652
                                    } else if ( $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'], 'country' => $data['country'] ) ) ) {
4653
                                        $data['location_id'] = (int)$location->location_id;
4654
                                    }
4655
                                    
4656
                                    if ( $location_id = geodir_location_update_city( $data, true, $location ) ) {
0 ignored issues
show
Unused Code introduced by
$location_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4657
                                        $updated++;
4658
                                    } else {
4659
                                        $invalid++;
4660
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4661
                                    }
4662
                                } else {
4663
                                    if ( $location_id = geodir_location_insert_city( $data, true ) ) {
0 ignored issues
show
Unused Code introduced by
$location_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4664
                                        $created++;
4665
                                    } else {
4666
                                        $invalid++;
4667
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4668
                                    }
4669
                                }
4670 View Code Duplication
                            } elseif ( $import_choice == 'skip' ) {
4671
                                if ( (int)$data['location_id'] > 0 && $location = geodir_get_location_by_id( '', (int)$data['location_id'] ) ) {
4672
                                    $skipped++;
4673
                                } else if ( !empty( $data['city_slug'] ) && $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'] ) ) ) {
4674
                                    $skipped++;
4675
                                } else {
4676
                                    if ( $location_id = geodir_location_insert_city( $data, true ) ) {
0 ignored issues
show
Unused Code introduced by
$location_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4677
                                        $created++;
4678
                                    } else {
4679
                                        $invalid++;
4680
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4681
                                    }
4682
                                }
4683
                            } else {
4684
                                $invalid++;
4685
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4686
                            }
4687
                        }
4688
                    }
4689
                }
4690
                
4691
                $json = array();
4692
                $json['processed'] = $limit;
4693
                $json['created'] = $created;
4694
                $json['updated'] = $updated;
4695
                $json['skipped'] = $skipped;
4696
                $json['invalid'] = $invalid;
4697
                $json['images'] = $images;
4698
                
4699
                wp_send_json( $json );
4700
            } else if ( $task == 'import_hood' ) {               
4701
                if (!empty($file)) {
4702
                    $columns = isset($file[0]) ? $file[0] : NULL;
4703
                    
4704 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4705
                        $json['error'] = __('File you are uploading is not valid. Columns does not matching.', 'geodirectory');
4706
                        wp_send_json( $json );
4707
                    }
4708
                    
4709
                    $gd_error_log = __('GD IMPORT NEIGHBOURHOODS [ROW %d]:', 'geodirectory');
4710
                    $gd_error_hood = __( 'Could not be saved due to invalid neighbourhood data(name, latitude, longitude) or invalid location data(either location_id or city/region/country is empty)', 'geodirectory' );
4711
                    for ($i = 1; $i <= $limit; $i++) {
4712
                        $index = $processed + $i;
4713
                        
4714
                        if (isset($file[$index])) {
4715
                            $row = $file[$index];
4716
                            $row = array_map( 'trim', $row );
4717
                            $data = array();
4718
                            
4719
                            foreach ($columns as $c => $column) {
4720
                                if (in_array($column, array('neighbourhood_id', 'neighbourhood_name', 'neighbourhood_slug', 'latitude', 'longitude', 'location_id', 'city', 'region', 'country'))) {
4721
                                    $data[$column] = sanitize_text_field($row[$c]);
4722
                                }
4723
                            }
4724
4725
                            if (empty($data['neighbourhood_name']) || empty($data['latitude']) || empty($data['longitude'])) {
4726
                                $invalid++;
4727
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4728
                                continue;
4729
                            }
4730
                            
4731
                            $location_info = array();
4732
                            if (!empty($data['location_id']) && (int)$data['location_id'] > 0) {
4733
                                $location_info = geodir_get_location_by_id('', (int)$data['location_id']);
4734
                            } else if (!empty($data['city']) && !empty($data['region']) && !empty($data['country'])) {
4735
                                $location_info = geodir_get_location_by_slug('city', array('fields' => 'location_id', 'city' => $data['city'], 'country' => $data['country'], 'region' => $data['region']));
4736
                            }
4737
4738
                            if (empty($location_info)) {
4739
                                $invalid++;
4740
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4741
                                continue;
4742
                            }
4743
                            
4744
                            $location_id = $location_info->location_id;
4745
4746
                            $data['neighbourhood_id'] = isset($data['neighbourhood_id']) ? absint($data['neighbourhood_id']) : 0;
4747
                            
4748
                            $hood_data = array();
4749
                            $hood_data['hood_name'] = $data['neighbourhood_name'];
4750
                            $hood_data['hood_slug'] = $data['neighbourhood_slug'];
4751
                            $hood_data['hood_latitude'] = $data['latitude'];
4752
                            $hood_data['hood_longitude'] = $data['longitude'];
4753
                            $hood_data['hood_location_id'] = $location_id;
4754
                                    
4755
                            if ( $import_choice == 'update' ) {
4756
                                if ((int)$data['neighbourhood_id'] > 0 && ($neighbourhood = geodir_location_get_neighbourhood_by_id((int)$data['neighbourhood_id']))) {
4757
                                    $hood_data['hood_id'] = (int)$data['neighbourhood_id'];
4758
                                    
4759
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
4760
                                        $updated++;
4761
                                    } else {
4762
                                        $invalid++;
4763
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4764
                                    }
4765
                                } else if (!empty($data['neighbourhood_slug']) && ($neighbourhood = geodir_location_get_neighbourhood_by_id($data['neighbourhood_slug'], true))) {
4766
                                    $hood_data['hood_id'] = (int)$neighbourhood->hood_id;
4767
                                    
4768
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
4769
                                        $updated++;
4770
                                    } else {
4771
                                        $invalid++;
4772
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4773
                                    }
4774
                                } else {
4775
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
4776
                                        $created++;
4777
                                    } else {
4778
                                        $invalid++;
4779
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4780
                                    }
4781
                                }
4782 View Code Duplication
                            } elseif ( $import_choice == 'skip' ) {
4783
                                if ((int)$data['neighbourhood_id'] > 0 && ($neighbourhood = geodir_location_get_neighbourhood_by_id((int)$data['neighbourhood_id']))) {
4784
                                    $skipped++;
4785
                                } else if (!empty($data['neighbourhood_slug']) && ($neighbourhood = geodir_location_get_neighbourhood_by_id($data['neighbourhood_slug'], true))) {
4786
                                    $skipped++;
4787
                                } else {
4788
                                    
4789
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
4790
                                        $created++;
4791
                                    } else {
4792
                                        $invalid++;
4793
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4794
                                    }
4795
                                }
4796
                            } else {
4797
                                $invalid++;
4798
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4799
                            }
4800
                        }
4801
                    }
4802
                }
4803
                
4804
                $json = array();
4805
                $json['processed'] = $limit;
4806
                $json['created'] = $created;
4807
                $json['updated'] = $updated;
4808
                $json['skipped'] = $skipped;
4809
                $json['invalid'] = $invalid;
4810
                $json['images'] = $images;
4811
                
4812
                wp_send_json( $json );
4813
            }
4814
        }
4815
        break;
4816
        case 'import_finish':{
4817
            /**
4818
             * Run an action when an import finishes.
4819
             *
4820
             * This action can be used to fire functions after an import ends.
4821
             *
4822
             * @since 1.5.3
4823
             * @package GeoDirectory
4824
             */
4825
            do_action('geodir_import_finished');
4826
        }
4827
        break;
4828
4829
    }
4830
    echo '0';
4831
    gd_die();
4832
}
4833
4834
/**
4835
 * Create new the post term.
4836
 *
4837
 * @since 1.4.6
4838
 * @package GeoDirectory
4839
 *
4840
 * @param string $taxonomy Post taxonomy.
4841
 * @param array $term_data {
4842
 *    Attributes of term data.
4843
 *
4844
 *    @type string $name Term name.
4845
 *    @type string $slug Term slug.
4846
 *    @type string $description Term description.
4847
 *    @type string $top_description Term top description.
4848
 *    @type string $image Default Term image.
4849
 *    @type string $icon Default Term icon.
4850
 *    @type string $taxonomy Term taxonomy.
4851
 *    @type int $parent Term parent ID.
4852
 *
4853
 * }
4854
 * @return int|bool Term id when success, false when fail.
4855
 */
4856
function geodir_imex_insert_term( $taxonomy, $term_data ) {
4857
	if ( empty( $taxonomy ) || empty( $term_data ) ) {
4858
		return false;
4859
	}
4860
	
4861
	$term = isset( $term_data['name'] ) && !empty( $term_data['name'] ) ? $term_data['name'] : '';
4862
	$args = array();
4863
	$args['description'] = isset( $term_data['description'] ) ? $term_data['description'] : '';
4864
	$args['slug'] = isset( $term_data['slug'] ) ? $term_data['slug'] : '';
4865
	$args['parent'] = isset( $term_data['parent'] ) ? (int)$term_data['parent'] : '';
4866
	
4867
	if ( ( !empty( $args['slug'] ) && term_exists( $args['slug'], $taxonomy ) ) || empty( $args['slug'] ) ) {
4868
		$term_args = array_merge( $term_data, $args );
4869
		$defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
4870
		$term_args = wp_parse_args( $term_args, $defaults );
4871
		$term_args = sanitize_term( $term_args, $taxonomy, 'db' );
4872
		$args['slug'] = wp_unique_term_slug( $args['slug'], (object)$term_args );
4873
	}
4874
	
4875
    if( !empty( $term ) ) {
4876
		$result = wp_insert_term( $term, $taxonomy, $args );
4877
        if( !is_wp_error( $result ) ) {
4878
            return isset( $result['term_id'] ) ? $result['term_id'] : 0;
4879
        }
4880
    }
4881
	
4882
	return false;
4883
}
4884
4885
/**
4886
 * Update the post term.
4887
 *
4888
 * @since 1.4.6
4889
 * @package GeoDirectory
4890
 *
4891
 * @param string $taxonomy Post taxonomy.
4892
 * @param array $term_data {
4893
 *    Attributes of term data.
4894
 *
4895
 *    @type string $term_id Term ID.
4896
 *    @type string $name Term name.
4897
 *    @type string $slug Term slug.
4898
 *    @type string $description Term description.
4899
 *    @type string $top_description Term top description.
4900
 *    @type string $image Default Term image.
4901
 *    @type string $icon Default Term icon.
4902
 *    @type string $taxonomy Term taxonomy.
4903
 *    @type int $parent Term parent ID.
4904
 *
4905
 * }
4906
 * @return int|bool Term id when success, false when fail.
4907
 */
4908
function geodir_imex_update_term( $taxonomy, $term_data ) {
4909
	if ( empty( $taxonomy ) || empty( $term_data ) ) {
4910
		return false;
4911
	}
4912
	
4913
	$term_id = isset( $term_data['term_id'] ) && !empty( $term_data['term_id'] ) ? $term_data['term_id'] : 0;
4914
	
4915
	$args = array();
4916
	$args['description'] = isset( $term_data['description'] ) ? $term_data['description'] : '';
4917
	$args['slug'] = isset( $term_data['slug'] ) ? $term_data['slug'] : '';
4918
	$args['parent'] = isset( $term_data['parent'] ) ? (int)$term_data['parent'] : '';
4919
	
4920
	if ( $term_id > 0 && $term_info = (array)get_term( $term_id, $taxonomy ) ) {
4921
		$term_data['term_id'] = $term_info['term_id'];
4922
		
4923
		$result = wp_update_term( $term_data['term_id'], $taxonomy, $term_data );
4924
		
4925
		if( !is_wp_error( $result ) ) {
4926
            return isset( $result['term_id'] ) ? $result['term_id'] : 0;
4927
        }
4928
	} else if ( $term_data['slug'] != '' && $term_info = (array)term_exists( $term_data['slug'], $taxonomy ) ) {
4929
		$term_data['term_id'] = $term_info['term_id'];
4930
		
4931
		$result = wp_update_term( $term_data['term_id'], $taxonomy, $term_data );
4932
		
4933
		if( !is_wp_error( $result ) ) {
4934
            return isset( $result['term_id'] ) ? $result['term_id'] : 0;
4935
        }
4936
	} else {
4937
		return geodir_imex_insert_term( $taxonomy, $term_data );
4938
	}
4939
	
4940
	return false;
4941
}
4942
4943
/**
4944
 * Get the posts counts for the current post type.
4945
 *
4946
 * @since 1.4.6
4947
 * @since 1.6.4 Updated to filter posts.
4948
 * @package GeoDirectory
4949
 *
4950
 * @global object $wpdb WordPress Database object.
4951
 * @global string $plugin_prefix Geodirectory plugin table prefix.
4952
 *
4953
 * @param string $post_type Post type.
4954
 * @return int Posts count.
4955
 */
4956
function geodir_get_posts_count( $post_type ) {
4957
    global $wpdb, $plugin_prefix;
4958
4959
    if ( !post_type_exists( $post_type ) ) {
4960
        return 0;
4961
    }
4962
        
4963
    $table = $plugin_prefix . $post_type . '_detail';
4964
4965
    // Skip listing with statuses trash, auto-draft etc...
4966
    $skip_statuses = geodir_imex_export_skip_statuses();
4967
    $where_statuses = '';
4968 View Code Duplication
    if ( !empty( $skip_statuses ) && is_array( $skip_statuses ) ) {
4969
        $where_statuses = "AND `" . $wpdb->posts . "`.`post_status` NOT IN('" . implode( "','", $skip_statuses ) . "')";
4970
    }
4971
    
4972
    /**
4973
     * Filter the SQL where clause part to filter posts count in import/export.
4974
     *
4975
     * @since 1.6.4
4976
     * @package GeoDirectory
4977
     *
4978
     * @param string $where SQL where clause part.
4979
     */
4980
    $where_statuses = apply_filters( 'geodir_get_posts_count', $where_statuses, $post_type );
4981
4982
    $query = $wpdb->prepare( "SELECT COUNT({$wpdb->posts}.ID) FROM {$wpdb->posts} INNER JOIN {$table} ON {$table}.post_id = {$wpdb->posts}.ID WHERE {$wpdb->posts}.post_type = %s " . $where_statuses, $post_type );
4983
4984
    $posts_count = (int)$wpdb->get_var( $query );
4985
    
4986
    /**
4987
     * Modify returned post counts for the current post type.
4988
     *
4989
     * @since 1.4.6
4990
     * @package GeoDirectory
4991
     *
4992
     * @param int $posts_count Post counts.
4993
     * @param string $post_type Post type.
4994
     */
4995
    $posts_count = apply_filters( 'geodir_imex_count_posts', $posts_count, $post_type );
4996
4997
    return $posts_count;
4998
}
4999
5000
/**
5001
 * Retrieves the posts for the current post type.
5002
 *
5003
 * @since 1.4.6
5004
 * @since 1.5.1 Updated to import & export recurring events.
5005
 * @since 1.5.3 Fixed to get wpml original post id.
5006
 * @since 1.5.7 $per_page & $page_no parameters added.
5007
 * @package GeoDirectory
5008
 *
5009
 * @global object $wp_filesystem WordPress FileSystem object.
5010
 *
5011
 * @param string $post_type Post type.
5012
 * @param int $per_page Per page limit. Default 0.
5013
 * @param int $page_no Page number. Default 0.
5014
 * @return array Array of posts data.
5015
 */
5016
function geodir_imex_get_posts( $post_type, $per_page = 0, $page_no = 0 ) {	
5017
	global $wp_filesystem;
5018
5019
	$posts = geodir_get_export_posts( $post_type, $per_page, $page_no );
5020
5021
	$csv_rows = array();
5022
	
5023
	if ( !empty( $posts ) ) {
5024
		$is_payment_plugin = is_plugin_active( 'geodir_payment_manager/geodir_payment_manager.php' );
5025
        $location_manager = function_exists('geodir_location_plugin_activated') ? true : false; // Check location manager installed & active.
5026
        $location_allowed = function_exists( 'geodir_cpt_no_location' ) && geodir_cpt_no_location( $post_type ) ? false : true;
5027
        $neighbourhood_active = $location_manager && $location_allowed && get_option('location_neighbourhoods') ? true : false;
5028
        $is_claim_active = is_plugin_active( 'geodir_claim_listing/geodir_claim_listing.php' ) && get_option('geodir_claim_enable') === 'yes' ? true : false;
5029
		
5030
		$csv_row = array();
5031
		$csv_row[] = 'post_id';
5032
		$csv_row[] = 'post_title';
5033
		$csv_row[] = 'post_author';
5034
		$csv_row[] = 'post_content';
5035
		$csv_row[] = 'post_category';
5036
		$csv_row[] = 'default_category';
5037
		$csv_row[] = 'post_tags';
5038
		$csv_row[] = 'post_type';
5039
		if ( $post_type == 'gd_event' ) {
5040
			$csv_row[] = 'event_date';
5041
			$csv_row[] = 'event_enddate';
5042
			$csv_row[] = 'starttime';
5043
			$csv_row[] = 'endtime';
5044
			
5045
			$csv_row[] = 'is_recurring_event';
5046
			$csv_row[] = 'event_duration_days';
5047
			$csv_row[] = 'recurring_dates';
5048
			$csv_row[] = 'is_whole_day_event';
5049
			$csv_row[] = 'event_starttimes';
5050
			$csv_row[] = 'event_endtimes';
5051
			$csv_row[] = 'recurring_type';
5052
			$csv_row[] = 'recurring_interval';
5053
			$csv_row[] = 'recurring_week_days';
5054
			$csv_row[] = 'recurring_week_nos';
5055
			$csv_row[] = 'max_recurring_count';
5056
			$csv_row[] = 'recurring_end_date';
5057
		}
5058
		$csv_row[] = 'post_status';
5059
		$csv_row[] = 'is_featured';
5060
        // Export claim listing field
5061
		if ($is_claim_active) {
5062
			$csv_row[] = 'claimed';
5063
		}
5064
		if ($is_payment_plugin) {
5065
			$csv_row[] = 'package_id';
5066
			$csv_row[] = 'expire_date';
5067
		}
5068
        $csv_row[] = 'post_date';
5069
		$csv_row[] = 'post_address';
5070
		$csv_row[] = 'post_city';
5071
		$csv_row[] = 'post_region';
5072
		$csv_row[] = 'post_country';
5073
		$csv_row[] = 'post_zip';
5074
		$csv_row[] = 'post_latitude';
5075
		$csv_row[] = 'post_longitude';
5076
        if ($neighbourhood_active) {
5077
            $csv_row[] = 'post_neighbourhood';
5078
            $csv_row[] = 'neighbourhood_latitude';
5079
            $csv_row[] = 'neighbourhood_longitude';
5080
        }
5081
		$csv_row[] = 'geodir_timing';
5082
		$csv_row[] = 'geodir_contact';
5083
		$csv_row[] = 'geodir_email';
5084
		$csv_row[] = 'geodir_website';
5085
		$csv_row[] = 'geodir_twitter';
5086
		$csv_row[] = 'geodir_facebook';
5087
		$csv_row[] = 'geodir_video';
5088
		$csv_row[] = 'geodir_special_offers';
5089
		// WPML
5090
		$is_wpml = geodir_is_wpml();
5091
		if ($is_wpml) {
5092
			$csv_row[] = 'language';
5093
			$csv_row[] = 'original_post_id';
5094
		}
5095
		// WPML
5096
5097
		$custom_fields = geodir_imex_get_custom_fields( $post_type );
5098
		if ( !empty( $custom_fields ) ) {
5099
			foreach ( $custom_fields as $custom_field ) {
5100
				$csv_row[] = $custom_field->htmlvar_name;
5101
			}
5102
		}
5103
5104
		// Export franchise fields
5105
		$is_franchise_active = is_plugin_active( 'geodir_franchise/geodir_franchise.php' ) && geodir_franchise_enabled( $post_type ) ? true : false;
5106
		if ($is_franchise_active) {
5107
			$csv_row[] = 'gd_is_franchise';
5108
			$csv_row[] = 'gd_franchise_lock';
5109
			$csv_row[] = 'franchise';
5110
		}
5111
        
5112
        /**
5113
         * Filter columns field names of gd export listings csv.
5114
         *
5115
         * @since 1.6.5
5116
         * @package GeoDirectory
5117
         *
5118
         * @param array $csv_row Column names being exported in csv.
5119
         * @param string $post_type The post type.
5120
         */
5121
        $csv_row = apply_filters('geodir_export_listing_csv_column_names', $csv_row, $post_type);
5122
		
5123
		$csv_rows[] = $csv_row;
5124
5125
		$images_count = 5;
5126
        $xx=0;
5127
		foreach ( $posts as $post ) {$xx++;
5128
			$post_id = $post['ID'];
5129
			
5130
			$gd_post_info = geodir_get_post_info( $post_id );
5131
			$post_info = (array)$gd_post_info;
5132
						
5133
			$taxonomy_category = $post_type . 'category';
5134
			$taxonomy_tags = $post_type . '_tags';
5135
			
5136
			$post_category = '';
5137
			$default_category_id = $gd_post_info->default_category;
5138
			$default_category = '';
5139
			$post_tags = '';
5140
			$terms = wp_get_post_terms( $post_id, array( $taxonomy_category, $taxonomy_tags ) );
5141
			
5142
			if ( !empty( $terms ) && !is_wp_error( $terms ) ) {
5143
				$post_category = array();
5144
				$post_tags = array();
5145
			
5146
				foreach ( $terms as $term ) {
5147
					if ( $term->taxonomy == $taxonomy_category ) {
5148
						$post_category[] = $term->name;
5149
						
5150
						if ($default_category_id == $term->term_id) {
5151
							$default_category = $term->name; // Default category.
5152
						}
5153
					}
5154
					
5155
					if ( $term->taxonomy == $taxonomy_tags ) {
5156
						$post_tags[] = $term->name;
5157
					}
5158
				}
5159
				
5160
				if (empty($default_category) && !empty($post_category)) {
5161
					$default_category = $post_category[0]; // Set first one as default category.
5162
				}
5163
				$post_category = !empty( $post_category ) ? implode( ',', $post_category ) : '';
5164
				$post_tags = !empty( $post_tags ) ? implode( ',', $post_tags ) : '';
5165
			}
5166
5167
			// Franchise data
5168
			if ($is_franchise_active && isset($post_info['franchise']) && (int)$post_info['franchise'] > 0 && geodir_franchise_check((int)$post_info['franchise'])) {
5169
				$franchise_id = $post_info['franchise'];
5170
				$gd_franchise_info = geodir_get_post_info($franchise_id);
5171
5172
				if (geodir_franchise_pkg_is_active($gd_franchise_info)) {
5173
					$franchise_info = (array)$gd_franchise_info;
5174
					$locked_fields = geodir_franchise_get_locked_fields($franchise_id, true);
5175
					
5176
					if (!empty($locked_fields)) {
5177
						foreach( $locked_fields as $locked_field) {
5178
							if (isset($post_info[$locked_field]) && isset($franchise_info[$locked_field])) {
5179
								$post_info[$locked_field] = $franchise_info[$locked_field];
5180
							}
5181
							
5182
							if (in_array($taxonomy_category, $locked_fields) || in_array('post_tags', $locked_fields)) {
5183
								$franchise_terms = wp_get_post_terms( $franchise_id, array( $taxonomy_category, $taxonomy_tags ) );
5184
			
5185
								if ( !empty( $franchise_terms ) && !is_wp_error( $franchise_terms ) ) {
5186
									$franchise_post_category = array();
5187
									$franchise_post_tags = array();
5188
								
5189
									foreach ( $franchise_terms as $franchise_term ) {
5190
										if ( $franchise_term->taxonomy == $taxonomy_category ) {
5191
											$franchise_post_category[] = $franchise_term->name;
5192
										}
5193
										
5194
										if ( $franchise_term->taxonomy == $taxonomy_tags ) {
5195
											$franchise_post_tags[] = $franchise_term->name;
5196
										}
5197
									}
5198
									
5199
									if (in_array($taxonomy_category, $locked_fields)) {
5200
										$post_category = !empty( $franchise_post_category ) ? implode( ',', $franchise_post_category ) : '';
5201
									}
5202
									if (in_array('post_tags', $locked_fields)) {
5203
										$post_tags = !empty( $franchise_post_tags ) ? implode( ',', $franchise_post_tags ) : '';
5204
									}
5205
								}
5206
							}
5207
						}
5208
					}
5209
				}
5210
			}
5211
						
5212
			$post_images = geodir_get_images( $post_id );
5213
			$current_images = array();
5214
			if ( !empty( $post_images ) ) {
5215
				foreach ( $post_images as $post_image ) {
0 ignored issues
show
Bug introduced by
The expression $post_images of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5216
					$post_image = (array)$post_image;
5217
					$image = !empty( $post_image ) && isset( $post_image['path'] ) && $wp_filesystem->is_file( $post_image['path'] ) && $wp_filesystem->exists( $post_image['path'] ) ? $post_image['src'] : '';
5218
					if ( $image ) {
5219
						$current_images[] = $image;
5220
					}
5221
				}
5222
				
5223
				$images_count = max( $images_count, count( $current_images ) );
5224
			}
5225
5226
			$csv_row = array();
5227
			$csv_row[] = $post_id; // post_id
5228
			$csv_row[] = $post_info['post_title']; // post_title
5229
			$csv_row[] = $post_info['post_author']; // post_author
5230
			$csv_row[] = $post_info['post_content']; // post_content
5231
			$csv_row[] = $post_category; // post_category
5232
			$csv_row[] = $default_category; // default_category
5233
			$csv_row[] = $post_tags; // post_tags
5234
			$csv_row[] = $post_type; // post_type
5235
			if ( $post_type == 'gd_event' ) {
5236
				$event_data = geodir_imex_get_event_data($post, $gd_post_info);
0 ignored issues
show
Bug introduced by
It seems like $gd_post_info defined by geodir_get_post_info($post_id) on line 5130 can also be of type boolean; however, geodir_imex_get_event_data() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
5237
				$csv_row[] = $event_data['event_date']; // event_date
5238
				$csv_row[] = $event_data['event_enddate']; // enddate
5239
				$csv_row[] = $event_data['starttime']; // starttime
5240
				$csv_row[] = $event_data['endtime']; // endtime
5241
				
5242
				$csv_row[] = $event_data['is_recurring_event']; // is_recurring
5243
				$csv_row[] = $event_data['event_duration_days']; // duration_x
5244
				$csv_row[] = $event_data['recurring_dates']; // recurring_dates
5245
				$csv_row[] = $event_data['is_whole_day_event']; // all_day
5246
				$csv_row[] = $event_data['event_starttimes']; // starttimes
5247
				$csv_row[] = $event_data['event_endtimes']; // endtimes
5248
				$csv_row[] = $event_data['recurring_type']; // repeat_type
5249
				$csv_row[] = $event_data['recurring_interval']; // repeat_x
5250
				$csv_row[] = $event_data['recurring_week_days']; // repeat_days
5251
				$csv_row[] = $event_data['recurring_week_nos']; // repeat_weeks
5252
				$csv_row[] = $event_data['max_recurring_count']; // max_repeat
5253
				$csv_row[] = $event_data['recurring_end_date']; // repeat_end
5254
			}
5255
			$csv_row[] = $post_info['post_status']; // post_status
5256
			$csv_row[] = (int)$post_info['is_featured'] == 1 ? 1 : ''; // is_featured
5257
            if ($is_claim_active) {
5258
                $csv_row[] = !empty($post_info['claimed']) && (int)$post_info['claimed'] == 1 ? 1 : ''; // claimed
5259
            }
5260
			if ($is_payment_plugin) {
5261
				$csv_row[] = (int)$post_info['package_id']; // package_id
5262
				$csv_row[] = $post_info['expire_date'] != '' && geodir_strtolower($post_info['expire_date']) != 'never' ? date_i18n('Y-m-d', strtotime($post_info['expire_date'])) : 'Never'; // expire_date
5263
			}
5264
            $csv_row[] = $post_info['post_date']; // post_date
5265
			$csv_row[] = $post_info['post_address']; // post_address
5266
			$csv_row[] = $post_info['post_city']; // post_city
5267
			$csv_row[] = $post_info['post_region']; // post_region
5268
			$csv_row[] = $post_info['post_country']; // post_country
5269
			$csv_row[] = $post_info['post_zip']; // post_zip
5270
			$csv_row[] = $post_info['post_latitude']; // post_latitude
5271
			$csv_row[] = $post_info['post_longitude']; // post_longitude
5272
            if ($neighbourhood_active) {
5273
                $post_neighbourhood = '';
5274
                $neighbourhood_latitude = '';
5275
                $neighbourhood_longitude = '';
5276
                if (!empty($post_info['post_neighbourhood']) && ($hood_info = geodir_location_get_neighbourhood_by_id($post_info['post_neighbourhood'], true, $post_info['post_location_id']))) {
5277
                    if (!empty($hood_info)) {
5278
                        $post_neighbourhood = $hood_info->hood_name;
5279
                        $neighbourhood_latitude = $hood_info->hood_latitude;
5280
                        $neighbourhood_longitude = $hood_info->hood_longitude;
5281
                    }
5282
                }
5283
                $csv_row[] = $post_neighbourhood; // post_neighbourhood
5284
                $csv_row[] = $neighbourhood_latitude; // neighbourhood_latitude
5285
                $csv_row[] = $neighbourhood_longitude; // neighbourhood_longitude
5286
            }
5287
			$csv_row[] = $post_info['geodir_timing']; // geodir_timing
5288
			$csv_row[] = $post_info['geodir_contact']; // geodir_contact
5289
			$csv_row[] = $post_info['geodir_email']; // geodir_email
5290
			$csv_row[] = $post_info['geodir_website']; // geodir_website
5291
			$csv_row[] = $post_info['geodir_twitter']; // geodir_twitter
5292
			$csv_row[] = $post_info['geodir_facebook']; // geodir_facebook
5293
			$csv_row[] = $post_info['geodir_video']; // geodir_video
5294
			$csv_row[] = $post_info['geodir_special_offers']; // geodir_special_offers
5295
			// WPML
5296
			if ($is_wpml) {
5297
				$csv_row[] = geodir_get_language_for_element( $post_id, 'post_' . $post_type );
5298
				$csv_row[] = geodir_imex_original_post_id( $post_id, 'post_' . $post_type );
5299
			}
5300
			// WPML
5301
			
5302
			if ( !empty( $custom_fields ) ) {
5303
				foreach ( $custom_fields as $custom_field ) {
5304
					$csv_row[] = isset( $post_info[$custom_field->htmlvar_name] ) ? $post_info[$custom_field->htmlvar_name] : '';
5305
				}
5306
			}
5307
			
5308
			// Franchise data
5309
			if ($is_franchise_active) {
5310
				$gd_is_franchise = '';
5311
				$locaked_fields = '';
5312
				$franchise = '';
5313 1
					
5314
				if (geodir_franchise_pkg_is_active($gd_post_info)) {
5315 1
					$gd_is_franchise = (int)get_post_meta( $post_id, 'gd_is_franchise', true );
5316
					$locaked_fields = $gd_is_franchise ? get_post_meta( $post_id, 'gd_franchise_lock', true ) : '';
5317
					$locaked_fields = (is_array($locaked_fields) && !empty($locaked_fields) ? implode(",", $locaked_fields) : '');
5318
					$franchise = !$gd_is_franchise && isset($post_info['franchise']) && (int)$post_info['franchise'] > 0 ? (int)$post_info['franchise'] : 0; // franchise id
5319 1
				}
5320
				
5321
				$csv_row[] = (int)$gd_is_franchise; // gd_is_franchise
5322 1
				$csv_row[] = $locaked_fields; // gd_franchise_lock fields
5323 1
				$csv_row[] = (int)$franchise; // franchise id
5324 1
			}
5325 1
            
5326 1
            /**
5327
             * Filter columns values of gd export listings csv file
5328
             *
5329
             * @since 1.6.5
5330
             * @package GeoDirectory
5331
             *
5332
             * @param array $csv_row Field values being exported in csv.
5333
             * @param array $post_info The post info.
5334
             */
5335
            $csv_row = apply_filters('geodir_export_listing_csv_column_values', $csv_row, $post_info);
5336 1
			
5337
			for ( $c = 0; $c < $images_count; $c++ ) {
5338 1
				$csv_row[] = isset( $current_images[$c] ) ? $current_images[$c] : ''; // IMAGE
5339
			}
5340 1
			
5341
			$csv_rows[] = $csv_row;
5342
5343
		}
5344
5345
		for ( $c = 0; $c < $images_count; $c++ ) {
5346
			$csv_rows[0][] = 'IMAGE';
5347
		}
5348
	}
5349
	return $csv_rows;
5350
}
5351 1
5352
/**
5353 1
 * Retrieves the posts for the current post type.
5354
 *
5355
 * @since 1.4.6
5356
 * @since 1.5.7 $per_page & $page_no parameters added.
5357
 * @package GeoDirectory
5358
 *
5359
 * @global object $wpdb WordPress Database object.
5360
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5361
 *
5362
 * @param string $post_type Post type.
5363
 * @param int $per_page Per page limit. Default 0.
5364
 * @param int $page_no Page number. Default 0.
5365
 * @return array Array of posts data.
5366
 */
5367
function geodir_get_export_posts( $post_type, $per_page = 0, $page_no = 0 ) {
5368
    global $wpdb, $plugin_prefix;
5369
5370
    if ( ! post_type_exists( $post_type ) )
5371
        return new stdClass;
5372
        
5373
    $table = $plugin_prefix . $post_type . '_detail';
5374
5375
    $limit = '';
5376
    if ( $per_page > 0 && $page_no > 0 ) {
5377
        $offset = ( $page_no - 1 ) * $per_page;
5378
        
5379
        if ( $offset > 0 ) {
5380
            $limit = " LIMIT " . $offset . "," . $per_page;
5381
        } else {
5382
            $limit = " LIMIT " . $per_page;
5383
        }
5384
    }
5385
5386
    // Skip listing with statuses trash, auto-draft etc...
5387
    $skip_statuses = geodir_imex_export_skip_statuses();
5388
    $where_statuses = '';
5389 View Code Duplication
    if ( !empty( $skip_statuses ) && is_array( $skip_statuses ) ) {
5390
        $where_statuses = "AND `" . $wpdb->posts . "`.`post_status` NOT IN('" . implode( "','", $skip_statuses ) . "')";
5391
    }
5392
    
5393
    /**
5394
     * Filter the SQL where clause part to filter posts in import/export.
5395
     *
5396
     * @since 1.6.4
5397
     * @package GeoDirectory
5398
     *
5399
     * @param string $where SQL where clause part.
5400
     */
5401
    $where_statuses = apply_filters( 'geodir_get_export_posts', $where_statuses, $post_type );
5402
5403
    $query = $wpdb->prepare( "SELECT {$wpdb->posts}.ID FROM {$wpdb->posts} INNER JOIN {$table} ON {$table}.post_id = {$wpdb->posts}.ID WHERE {$wpdb->posts}.post_type = %s " . $where_statuses . " ORDER BY {$wpdb->posts}.ID ASC" . $limit, $post_type );
5404
    /**
5405
     * Modify returned posts SQL query for the current post type.
5406
     *
5407
     * @since 1.4.6
5408
     * @package GeoDirectory
5409
     *
5410
     * @param int $query The SQL query.
5411
     * @param string $post_type Post type.
5412
     */
5413
    $query = apply_filters( 'geodir_imex_export_posts_query', $query, $post_type );
5414
    $results = (array)$wpdb->get_results( $wpdb->prepare( $query, $post_type ), ARRAY_A );
5415
5416
    /**
5417
     * Modify returned post results for the current post type.
5418
     *
5419
     * @since 1.4.6
5420
     * @package GeoDirectory
5421
     *
5422
     * @param object $results An object containing all post ids.
5423
     * @param string $post_type Post type.
5424
     */
5425
    return apply_filters( 'geodir_export_posts', $results, $post_type );
5426
}
5427
5428
/**
5429
 * Get the posts SQL query for the current post type.
5430
 *
5431
 * @since 1.4.6
5432
 * @since 1.5.1 Query updated to get distinct posts. 
5433
 * @since 1.6.4 Updated to filter events.
5434
 * @package GeoDirectory
5435
 *
5436
 * @global object $wpdb WordPress Database object.
5437
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5438
 *
5439
 * @param string $query The SQL query.
5440
 * @param string $post_type Post type.
5441
 * @return string The SQL query.
5442
 */
5443
function geodir_imex_get_events_query( $query, $post_type ) {
5444
    if ( $post_type == 'gd_event' ) {
5445
        global $wpdb, $plugin_prefix;
5446
        
5447
        $table = $plugin_prefix . $post_type . '_detail';
5448
        $schedule_table = EVENT_SCHEDULE;
5449
        
5450
        // Skip listing with statuses trash, auto-draft etc...
5451
        $skip_statuses = geodir_imex_export_skip_statuses();
5452
        $where_statuses = '';
5453 View Code Duplication
        if ( !empty( $skip_statuses ) && is_array( $skip_statuses ) ) {
5454
            $where_statuses = "AND `" . $wpdb->posts . "`.`post_status` NOT IN('" . implode( "','", $skip_statuses ) . "')";
5455
        }
5456
        
5457
        /** This action is documented in geodirectory-functions/geodirectory-admin/admin_functions.php */
5458
        $where_statuses = apply_filters( 'geodir_get_export_posts', $where_statuses, $post_type );
5459
5460
        $query = $wpdb->prepare( "SELECT {$wpdb->posts}.ID, {$schedule_table}.event_date, {$schedule_table}.event_enddate AS enddate, {$schedule_table}.event_starttime AS starttime, {$schedule_table}.event_endtime AS endtime FROM {$wpdb->posts} INNER JOIN {$table} ON ({$table}.post_id = {$wpdb->posts}.ID) INNER JOIN {$schedule_table} ON ({$schedule_table}.event_id = {$wpdb->posts}.ID) WHERE {$wpdb->posts}.post_type = %s " . $where_statuses . " GROUP BY {$table}.post_id ORDER BY {$wpdb->posts}.ID ASC, {$schedule_table}.schedule_id ASC", $post_type );
5461
    }
5462
5463
    return $query;
5464
}
5465
5466
/**
5467
 * Retrieve terms count for given post type.
5468
 *
5469
 * @since 1.4.6
5470
 * @package GeoDirectory
5471
 *
5472
 * @param  string $post_type Post type.
5473
 * @return int Total terms count.
5474
 */
5475
/**
5476
 * Retrieve terms count for given post type.
5477
 *
5478
 * @since 1.4.6
5479
 * @package GeoDirectory
5480
 *
5481
 * @param  string $post_type Post type.
5482
 * @return int Total terms count.
5483
 */
5484
function geodir_get_terms_count( $post_type ) {
5485
    $args = array( 'hide_empty' => 0 );
5486
5487
    remove_all_filters( 'get_terms' );
5488
5489
    $taxonomy = $post_type . 'category';
5490
5491
    // WPML
5492
    $is_wpml = geodir_is_wpml();
5493
    $active_lang = 'all';
5494
    if ( $is_wpml ) {
5495
        global $sitepress;
5496
        $active_lang = $sitepress->get_current_language();
5497
        
5498
        if ( $active_lang != 'all' ) {
5499
            $sitepress->switch_lang( 'all', true );
5500
        }
5501
    }
5502
    // WPML
5503
            
5504
    $count_terms = wp_count_terms( $taxonomy, $args );
5505
5506
    // WPML
5507
    if ( $is_wpml && $active_lang !== 'all' ) {
5508
        global $sitepress;
5509
        $sitepress->switch_lang( $active_lang, true );
5510
    }
5511
    // WPML
5512
    $count_terms = !is_wp_error( $count_terms ) ? $count_terms : 0;
5513
     
5514
    return $count_terms;
5515
}
5516
5517
/**
5518
 * Retrieve terms for given post type.
5519
 *
5520
 * @since 1.4.6
5521
 * @since 1.5.7 $per_page & $page_no parameters added.
5522
 * @package GeoDirectory
5523
 *
5524
 * @param  string $post_type The post type.
5525
 * @param int $per_page Per page limit. Default 0.
5526
 * @param int $page_no Page number. Default 0.
5527
 * @return array Array of terms data.
5528
 */
5529
function geodir_imex_get_terms( $post_type, $per_page = 0, $page_no = 0 ) {
5530
	$args = array( 'hide_empty' => 0, 'orderby' => 'id' );
5531
	
5532
	remove_all_filters( 'get_terms' );
5533
	
5534
	$taxonomy = $post_type . 'category';
5535
	
5536
	if ( $per_page > 0 && $page_no > 0 ) {
5537
		$args['offset'] = ( $page_no - 1 ) * $per_page;
5538
		$args['number'] = $per_page;
5539
	}
5540
	
5541
	$terms = get_terms( $taxonomy, $args );
5542
5543
	$csv_rows = array();
5544
	
5545
	if ( !empty( $terms ) ) {
5546
		$csv_row = array();
5547
		$csv_row[] = 'cat_id';
5548
		$csv_row[] = 'cat_name';
5549
		$csv_row[] = 'cat_slug';
5550
		$csv_row[] = 'cat_posttype';
5551
		$csv_row[] = 'cat_parent';
5552
		$csv_row[] = 'cat_schema';
5553
        // WPML
5554
		$is_wpml = geodir_is_wpml();
5555
		if ($is_wpml) {
5556
			$csv_row[] = 'cat_language';
5557
            $csv_row[] = 'cat_id_original';
5558
		}
5559
		// WPML
5560
		$csv_row[] = 'cat_description';
5561
		$csv_row[] = 'cat_top_description';
5562
		$csv_row[] = 'cat_image';
5563
		$csv_row[] = 'cat_icon';
5564
		
5565
		$csv_rows[] = $csv_row;
5566
		
5567
		foreach ( $terms as $term ) {
5568
			$cat_icon = get_tax_meta( $term->term_id, 'ct_cat_icon', false, $post_type );
5569
			$cat_icon = !empty( $cat_icon ) && isset( $cat_icon['src'] ) ? $cat_icon['src'] : '';
5570
			
5571
			$cat_image = geodir_get_default_catimage( $term->term_id, $post_type );
5572
			$cat_image = !empty( $cat_image ) && isset( $cat_image['src'] ) ? $cat_image['src'] : ''; 
5573
			
5574
			$cat_parent = '';
5575
			if (isset($term->parent) && (int)$term->parent > 0 && term_exists((int)$term->parent, $taxonomy)) {
5576
				$parent_term = (array)get_term_by( 'id', (int)$term->parent, $taxonomy );
5577
				$cat_parent = !empty($parent_term) && isset($parent_term['name']) ? $parent_term['name'] : '';
5578
			}
5579
			
5580
			$csv_row = array();
5581
			$csv_row[] = $term->term_id;
5582
			$csv_row[] = $term->name;
5583
			$csv_row[] = $term->slug;
5584
			$csv_row[] = $post_type;
5585
			$csv_row[] = $cat_parent;
5586
			$csv_row[] = get_tax_meta( $term->term_id, 'ct_cat_schema', false, $post_type );
5587
            // WPML
5588
			if ($is_wpml) {
5589
				$csv_row[] = geodir_get_language_for_element( $term->term_id, 'tax_' . $taxonomy );
5590
                $csv_row[] = geodir_imex_original_post_id( $term->term_id, 'tax_' . $taxonomy );
5591
			}
5592
			// WPML
5593
			$csv_row[] = $term->description;
5594
			$csv_row[] = get_tax_meta( $term->term_id, 'ct_cat_top_desc', false, $post_type );
5595
			$csv_row[] = $cat_image;
5596
			$csv_row[] = $cat_icon;
5597
			
5598
			$csv_rows[] = $csv_row;
5599
		}
5600
	}
5601
	return $csv_rows;
5602
}
5603
5604
/**
5605
 * Get the path of cache directory.
5606
 *
5607
 * @since 1.4.6
5608
 * @package GeoDirectory
5609
 *
5610
 * @param  bool $relative True for relative path & False for absolute path.
5611
 * @return string Path to the cache directory.
5612
 */
5613
function geodir_path_import_export( $relative = true ) {
5614
	$upload_dir = wp_upload_dir();
5615
	
5616
	return $relative ? $upload_dir['baseurl'] . '/cache' : $upload_dir['basedir'] . '/cache';
5617
}
5618
5619
/**
5620
 * Save the data in CSV file to export.
5621
 *
5622
 * @since 1.4.6
5623
 * @package GeoDirectory
5624
 *
5625
 * @global null|object $wp_filesystem WP_Filesystem object.
5626
 *
5627
 * @param  string $file_path Full path to file.
5628
 * @param  array $csv_data Array of csv data.
5629
 * @param  bool $clear If true then it overwrite data otherwise add rows at the end of file.
5630
 * @return bool true if success otherwise false.
5631
 */
5632
function geodir_save_csv_data( $file_path, $csv_data = array(), $clear = true ) {
5633
	if ( empty( $csv_data ) ) {
5634
		return false;
5635
	}
5636
	
5637
	global $wp_filesystem;
5638
	
5639
	$mode = $clear ? 'w+' : 'a+';
5640
	
5641
	if ( function_exists( 'fputcsv' ) ) {
5642
		$file = fopen( $file_path, $mode );
5643
		foreach( $csv_data as $csv_row ) {
5644
			//$csv_row = array_map( 'utf8_decode', $csv_row );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
5645
			$write_successful = fputcsv( $file, $csv_row, ",", $enclosure = '"' );
0 ignored issues
show
Unused Code introduced by
$write_successful is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
5646
		}
5647
		fclose( $file );
5648
	} else {
5649
		foreach( $csv_data as $csv_row ) {
5650
			//$csv_row = array_map( 'utf8_decode', $csv_row );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
5651
			$wp_filesystem->put_contents( $file_path, $csv_row );
5652
		}
5653
	}
5654
		
5655
	return true;
5656
}
5657
5658
/**
5659
 * Count the number of line from file.
5660
 *
5661
 * @since 1.4.6
5662
 * @package GeoDirectory
5663
 *
5664
 * @global null|object $wp_filesystem WP_Filesystem object.
5665
 *
5666
 * @param  string $file Full path to file.
5667
 * @return int No of file rows.
5668
 */
5669
function geodir_import_export_line_count( $file ) {
5670
	global $wp_filesystem;
5671
	
5672
	if ( $wp_filesystem->is_file( $file ) && $wp_filesystem->exists( $file ) ) {
5673
		$contents = $wp_filesystem->get_contents_array( $file );
5674
		
5675
		if ( !empty( $contents ) && is_array( $contents ) ) {
5676
			return count( $contents ) - 1;
5677
		}
5678
	}
5679
	
5680
	return NULL;
5681
}
5682
5683
/**
5684
 * Returns queried data from custom fields table.
5685
 *
5686
 * @since 1.0.0
5687
 * @since 1.5.4 Modified to fix empty columns in export csv file.
5688
 * @package GeoDirectory
5689
 * @global object $wpdb WordPress Database object.
5690
 * @param string $post_type The post type.
5691
 * @return object Queried object.
5692
 */
5693
function geodir_imex_get_custom_fields( $post_type ) {
5694
	global $wpdb;
5695
	 
5696
	$sql = $wpdb->prepare("SELECT htmlvar_name FROM " . GEODIR_CUSTOM_FIELDS_TABLE . " WHERE post_type=%s AND is_active='1' AND is_admin!='1' AND field_type != 'fieldset' AND htmlvar_name != '' ORDER BY id ASC", array( $post_type ) );
5697
	$rows = $wpdb->get_results( $sql );
5698
	 
5699
	return $rows;
5700
}
5701
5702
/**
5703
 * Check wpml active or not.
5704
 *
5705
 * @since 1.5.0
5706
 *
5707
 * @return True if WPML is active else False.
5708
 */
5709
function geodir_is_wpml() {
5710
	if (function_exists('icl_object_id')) {
5711
		return true;
5712
	}
5713
	
5714
	return false;
5715
}
5716
5717
/**
5718
 * Get WPML language code for current term.
5719
 *
5720
 * @since 1.5.0
5721
 *
5722
 * @global object $sitepress Sitepress WPML object.
5723
 *
5724
 * @param int $element_id Post ID or Term id.
5725
 * @param string $element_type Element type. Ex: post_gd_place or tax_gd_placecategory.
5726
 * @return Language code.
5727
 */
5728
function geodir_get_language_for_element($element_id, $element_type) {
5729
	global $sitepress;
5730
	
5731
	return $sitepress->get_language_for_element($element_id, $element_type);
5732
}
5733
5734
/**
5735
 * Duplicate post details for WPML translation post.
5736
 *
5737
 * @since 1.5.0
5738
 *
5739
 * @param int $master_post_id Original Post ID.
5740
 * @param string $lang Language code for translating post.
5741
 * @param array $postarr Array of post data.
5742
 * @param int $tr_post_id Translation Post ID.
5743
 */
5744
function geodir_icl_make_duplicate($master_post_id, $lang, $postarr, $tr_post_id) {
0 ignored issues
show
Unused Code introduced by
The parameter $postarr is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
5745
	$post_type = get_post_type($master_post_id);
5746
5747
	if (in_array($post_type, geodir_get_posttypes())) {				
5748
		// Duplicate post details
5749
		geodir_icl_duplicate_post_details($master_post_id, $tr_post_id, $lang);
5750
		
5751
		// Duplicate taxonomies
5752
		geodir_icl_duplicate_taxonomies($master_post_id, $tr_post_id, $lang);
5753
		
5754
		// Duplicate post images
5755
		geodir_icl_duplicate_post_images($master_post_id, $tr_post_id, $lang);
5756
	}
5757
}
5758
5759
/**
5760
 * Duplicate post general details for WPML translation post.
5761
 *
5762
 * @since 1.5.0
5763
 *
5764
 * @global object $wpdb WordPress Database object.
5765
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5766
 *
5767
 * @param int $master_post_id Original Post ID.
5768
 * @param int $tr_post_id Translation Post ID.
5769
 * @param string $lang Language code for translating post.
5770
 * @return bool True for success, False for fail.
5771
 */
5772
function geodir_icl_duplicate_post_details($master_post_id, $tr_post_id, $lang) {
0 ignored issues
show
Unused Code introduced by
The parameter $lang is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
5773
	global $wpdb, $plugin_prefix;
5774
	
5775
	$post_type = get_post_type($master_post_id);
5776
	$post_table = $plugin_prefix . $post_type . '_detail';
5777
	
5778
	$query = $wpdb->prepare("SELECT * FROM " . $post_table . " WHERE post_id = %d", array($master_post_id));
5779
	$data = (array)$wpdb->get_row($query);
5780
	
5781
	if ( !empty( $data ) ) {
5782
		$data['post_id'] = $tr_post_id;
5783
		unset($data['default_category'], $data['marker_json'], $data['featured_image'], $data[$post_type . 'category'], $data['overall_rating'], $data['rating_count'], $data['ratings']);
5784
		
5785
		$wpdb->update($post_table, $data, array('post_id' => $tr_post_id));		
5786
		return true;
5787
	}
5788
	
5789
	return false;
5790
}
5791
5792
/**
5793
 * Duplicate post taxonomies for WPML translation post.
5794
 *
5795
 * @since 1.5.0
5796
 *
5797
 * @global object $sitepress Sitepress WPML object.
5798
 * @global object $wpdb WordPress Database object.
5799
 *
5800
 * @param int $master_post_id Original Post ID.
5801
 * @param int $tr_post_id Translation Post ID.
5802
 * @param string $lang Language code for translating post.
5803
 * @return bool True for success, False for fail.
5804
 */
5805
function geodir_icl_duplicate_taxonomies($master_post_id, $tr_post_id, $lang) {
5806
	global $sitepress, $wpdb;
5807
	$post_type = get_post_type($master_post_id);
5808
	
5809
	remove_filter('get_term', array($sitepress,'get_term_adjust_id')); // AVOID filtering to current language
5810
5811
	$taxonomies = get_object_taxonomies($post_type);
5812
	foreach ($taxonomies as $taxonomy) {
5813
		$terms = get_the_terms($master_post_id, $taxonomy);
5814
		$terms_array = array();
5815
		
5816
		if ($terms) {
5817
			foreach ($terms as $term) {
5818
				$tr_id = apply_filters( 'translate_object_id',$term->term_id, $taxonomy, false, $lang);
5819
				
5820
				if (!is_null($tr_id)){
5821
					// not using get_term - unfiltered get_term
5822
					$translated_term = $wpdb->get_row($wpdb->prepare("
5823
						SELECT * FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} x ON x.term_id = t.term_id WHERE t.term_id = %d AND x.taxonomy = %s", $tr_id, $taxonomy));
5824
5825
					$terms_array[] = $translated_term->term_id;
5826
				}
5827
			}
5828
5829
			if (!is_taxonomy_hierarchical($taxonomy)){
5830
				$terms_array = array_unique( array_map( 'intval', $terms_array ) );
5831
			}
5832
5833
			wp_set_post_terms($tr_post_id, $terms_array, $taxonomy);
5834
			
5835
			if ($taxonomy == $post_type . 'category') {
5836
				geodir_set_postcat_structure($tr_post_id, $post_type . 'category');
5837
			}
5838
		}
5839
	}
5840
}
5841 1
5842
/**
5843 1
 * Duplicate post images for WPML translation post.
5844
 *
5845 1
 * @since 1.5.0
5846
 *
5847
 * @global object $wpdb WordPress Database object.
5848 1
 *
5849 1
 * @param int $master_post_id Original Post ID.
5850 1
 * @param int $tr_post_id Translation Post ID.
5851
 * @param string $lang Language code for translating post.
5852
 * @return bool True for success, False for fail.
5853
 */
5854
function geodir_icl_duplicate_post_images($master_post_id, $tr_post_id, $lang) {
0 ignored issues
show
Unused Code introduced by
The parameter $lang is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
5855
	global $wpdb;
5856
	
5857
	$query = $wpdb->prepare("DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE mime_type like %s AND post_id = %d", array('%image%', $tr_post_id));
5858
	$wpdb->query($query);
5859
	
5860 1
	$query = $wpdb->prepare("SELECT * FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE mime_type like %s AND post_id = %d ORDER BY menu_order ASC", array('%image%', $master_post_id));
5861
	$post_images = $wpdb->get_results($query);
5862
	
5863 1
	if ( !empty( $post_images ) ) {
5864
		foreach ( $post_images as $post_image) {
5865
			$image_data = (array)$post_image;
5866
			unset($image_data['ID']);
5867
			$image_data['post_id'] = $tr_post_id;
5868 1
			
5869
			$wpdb->insert(GEODIR_ATTACHMENT_TABLE, $image_data);
5870 1
			
5871
			geodir_set_wp_featured_image($tr_post_id);
5872
		}
5873
		
5874
		return true;
5875
	}
5876
	
5877
	return false;
5878
}
5879
5880
/**
5881
 * Retrieves the event data to export.
5882
 *
5883
 * @since 1.5.1
5884
 * @package GeoDirectory
5885
 *
5886
 * @param array $post Post array.
5887
 * @param object $gd_post_info Geodirectory Post object.
5888
 * @return array Event data array.
5889
 */
5890
function geodir_imex_get_event_data($post, $gd_post_info) {
5891
	$event_date = isset( $post['event_date'] ) && $post['event_date'] != '' && $post['event_date'] != '0000-00-00 00:00:00' ? date_i18n( 'd/m/Y', strtotime( $post['event_date'] ) ) : '';
5892
	$event_enddate = $event_date;
5893
	$starttime = isset( $post['starttime'] ) && $post['starttime'] != '' && $post['starttime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $post['starttime'] ) ) : '';
5894
	$endtime = isset( $post['endtime'] ) && $post['endtime'] != '' && $post['endtime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $post['endtime'] ) ) : '';
5895
	
5896
	$is_recurring_event = '';
5897
	$event_duration_days = '';
5898
	$is_whole_day_event = '';
5899
	$recurring_dates = '';
5900
	$event_starttimes = '';
5901
	$event_endtimes = '';
5902
	$recurring_type = '';
5903
	$recurring_interval = '';
5904
	$recurring_week_days = '';
5905
	$recurring_week_nos = '';
5906
	$max_recurring_count = '';
5907
	$recurring_end_date = '';
5908
		
5909
	$recurring_data = isset($gd_post_info->recurring_dates) ? maybe_unserialize($gd_post_info->recurring_dates) : array();
5910
	if (!empty($recurring_data)) {
5911
		$event_date = isset( $recurring_data['event_start'] ) && $recurring_data['event_start'] != '' && $recurring_data['event_start'] != '0000-00-00 00:00:00' ? date_i18n( 'd/m/Y', strtotime( $recurring_data['event_start'] ) ) : $event_date;
5912
		$event_enddate = isset( $recurring_data['event_end'] ) && $recurring_data['event_end'] != '' && $recurring_data['event_end'] != '0000-00-00 00:00:00' ? date_i18n( 'd/m/Y', strtotime( $recurring_data['event_end'] ) ) : $event_date;
5913
		$starttime = isset( $recurring_data['starttime'] ) && $recurring_data['starttime'] != '' && $recurring_data['starttime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $recurring_data['starttime'] ) ) : $starttime;
5914
		$endtime = isset( $recurring_data['endtime'] ) && $recurring_data['endtime'] != '' && $recurring_data['endtime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $recurring_data['endtime'] ) ) : $endtime;
5915
		$is_whole_day_event = !empty($recurring_data['all_day']) ? 1 : '';
5916
		$different_times = !empty($recurring_data['different_times']) ? true : false;
5917
	
5918
		$recurring_pkg = geodir_event_recurring_pkg( $gd_post_info );
5919
		$is_recurring = isset( $gd_post_info->is_recurring ) && (int)$gd_post_info->is_recurring == 0 ? false : true;
5920
			
5921
		if ($recurring_pkg && $is_recurring) {
5922
			$recurring_dates = $event_date;
5923
			$event_enddate = '';
5924
			$is_recurring_event = 1;
5925
						
5926
			$recurring_type = !empty($recurring_data['repeat_type']) && in_array($recurring_data['repeat_type'], array('day', 'week', 'month', 'year', 'custom')) ? $recurring_data['repeat_type'] : 'custom';
5927
			
5928
			if (!empty($recurring_data['event_recurring_dates'])) {
5929
				$event_recurring_dates = explode( ',', $recurring_data['event_recurring_dates'] );
5930
				
5931
				if (!empty($event_recurring_dates)) {
5932
					$recurring_dates = array();
5933
					
5934
					foreach ($event_recurring_dates as $date) {
5935
						$recurring_dates[] = date_i18n( 'd/m/Y', strtotime( $date ) );
5936
					}
5937
					
5938
					$recurring_dates = implode(",", $recurring_dates);
5939
				}
5940
			}
5941
			
5942
			if ($recurring_type == 'custom') {
5943
				if (!$is_whole_day_event) {
5944
					$event_starttimes = $starttime;
5945
					$event_endtimes = $endtime;
5946
			
5947 View Code Duplication
					if (!empty($recurring_data['starttimes'])) {
5948
						$times = array();
5949
						
5950
						foreach ($recurring_data['starttimes'] as $time) {
5951
							$times[] = $time != '00:00:00' ? date_i18n( 'H:i', strtotime( $time ) ) : '00:00';
5952
						}
5953
						
5954
						$event_starttimes = implode(",", $times);
5955
					}
5956
					
5957 View Code Duplication
					if (!empty($recurring_data['endtimes'])) {
5958
						$times = array();
5959
						
5960
						foreach ($recurring_data['endtimes'] as $time) {
5961
							$times[] = $time != '00:00:00' ? date_i18n( 'H:i', strtotime( $time ) ) : '00:00';
5962
						}
5963
						
5964
						$event_endtimes = implode(",", $times);
5965
					}
5966
					
5967
					if (!$different_times) {
5968
						$event_starttimes = '';
5969
						$event_endtimes = '';
5970
					}
5971
				}
5972
			} else {
5973
				$event_duration_days = isset($recurring_data['duration_x']) ? (int)$recurring_data['duration_x'] : 1;
5974
				$recurring_interval = !empty($recurring_data['repeat_x']) && (int)$recurring_data['repeat_x'] > 0 ? $recurring_data['repeat_x'] : 1;
5975
				
5976
				if (($recurring_type == 'week' || $recurring_type == 'month') && !empty($recurring_data['repeat_days'])) {
5977
					$week_days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
5978
					
5979
					$days = array();
5980
					foreach ($recurring_data['repeat_days'] as $day) {
5981
						if (isset($week_days[$day])) {
5982
							$days[] = $week_days[$day];
5983
						}
5984
					}
5985
					
5986
					$recurring_week_days = implode(",", array_unique($days));
5987
				}
5988
				
5989
				$recurring_week_nos = $recurring_type == 'month' && !empty($recurring_data['repeat_weeks']) ? implode(",", $recurring_data['repeat_weeks']) : $recurring_week_nos;
5990
				if (!empty($recurring_data['repeat_end_type']) && (int)$recurring_data['repeat_end_type'] == 1) {
5991
					$recurring_end_date = isset($recurring_data['repeat_end']) && $recurring_data['repeat_end'] != '' && $recurring_data['repeat_end'] != '0000-00-00 00:00:00' ? date_i18n( 'd/m/Y', strtotime( $recurring_data['repeat_end'] ) ) : '';
5992
					$max_recurring_count = empty($recurring_end_date) ? 1 : '';
5993
				} else {
5994
					$max_recurring_count = (!empty($recurring_data['max_repeat']) && (int)$recurring_data['max_repeat'] > 0 ? (int)$recurring_data['max_repeat'] : 1);
5995
				}
5996
			}
5997
		}
5998
	}
5999
	if ($is_whole_day_event) {
6000
		$starttime = '';
6001
		$endtime = '';
6002
		$event_starttimes = '';
6003
		$event_endtimes = '';
6004
	}
6005
	
6006
	$data = array();
6007
	$data['event_date'] = $event_date;
6008
	$data['event_enddate'] = $event_enddate;
6009
	$data['starttime'] = $starttime;
6010
	$data['endtime'] = $endtime;
6011
	$data['is_recurring_event'] = $is_recurring_event;
6012
	$data['recurring_dates'] = $recurring_dates;
6013
	$data['event_duration_days'] = $event_duration_days;
6014
	$data['is_whole_day_event'] = $is_whole_day_event;
6015
	$data['event_starttimes'] = $event_starttimes;
6016
	$data['event_endtimes'] = $event_endtimes;
6017
	$data['recurring_type'] = $recurring_type;
6018
	$data['recurring_interval'] = $recurring_interval;
6019
	$data['recurring_week_days'] = $recurring_week_days;
6020
	$data['recurring_week_nos'] = $recurring_week_nos;
6021
	$data['max_recurring_count'] = $max_recurring_count;
6022
	$data['recurring_end_date'] = $recurring_end_date;
6023
	
6024
	return $data;
6025
}
6026
6027
/**
6028
 * Convert date format to store in database.
6029
 *
6030
 * PHP date() function doesn't work well with d/m/Y format
6031
 * so this function validate and convert date to store in db.
6032
 *
6033
 * @since 1.5.1
6034
 * @package GeoDirectory
6035
 *
6036
 * @param string $date Date in Y-m-d or d/m/Y format.
6037
 * @return string Date in Y-m-d format.
6038
 */
6039
function geodir_imex_get_date_ymd($date) {
6040
	if (strpos($date, '/') !== false) {
6041
		$date = str_replace('/', '-', $date); // PHP doesn't work well with dd/mm/yyyy format.
6042
	}
6043
	
6044
	$date = date_i18n('Y-m-d', strtotime($date));
6045
	return $date;
6046
}
6047
6048
/**
6049
 * Validate the event data.
6050
 *
6051
 * @since 1.5.1
6052
 * @package GeoDirectory
6053
 *
6054
 * @param array $gd_post Post array.
6055
 * @return array Event data array.
6056
 */
6057
function geodir_imex_process_event_data($gd_post) {
6058
	$recurring_pkg = geodir_event_recurring_pkg( (object)$gd_post );
6059
6060
	$is_recurring = isset( $gd_post['is_recurring_event'] ) && (int)$gd_post['is_recurring_event'] == 0 ? false : true;
6061
	$event_date = isset($gd_post['event_date']) && $gd_post['event_date'] != '' ? geodir_imex_get_date_ymd($gd_post['event_date']) : '';
6062
	$event_enddate = isset($gd_post['event_enddate']) && $gd_post['event_enddate'] != '' ? geodir_imex_get_date_ymd($gd_post['event_enddate']) : $event_date;
6063
	$all_day = isset($gd_post['is_whole_day_event']) && !empty($gd_post['is_whole_day_event']) ? true : false;
6064
	$starttime = isset($gd_post['starttime']) && !$all_day ? $gd_post['starttime'] : '';
6065
	$endtime = isset($gd_post['endtime']) && !$all_day ? $gd_post['endtime'] : '';
6066 1
	
6067
	$repeat_type = '';
6068
	$different_times = '';
6069
	$starttimes = '';
6070 1
	$endtimes = '';
6071
	$repeat_days = '';
6072
	$repeat_weeks = '';
6073
	$event_recurring_dates = '';
6074
	$repeat_x = '';
6075
	$duration_x = '';
6076
	$repeat_end_type = '';
6077
	$max_repeat = '';
6078
	$repeat_end = '';
6079
	
6080
	if ($recurring_pkg && $is_recurring) {
6081
		$repeat_type = $gd_post['recurring_type'];
6082
		
6083
		if ($repeat_type == 'custom') {
6084
			$starttimes = !$all_day && !empty($gd_post['event_starttimes']) ? explode(",", $gd_post['event_starttimes']) : array();
6085
			$endtimes = !$all_day && !empty($gd_post['event_endtimes']) ? explode(",", $gd_post['event_endtimes']) : array();
6086
			
6087
			if (!empty($starttimes) || !empty($endtimes)) {
6088
				$different_times = true;
6089
			}
6090
			
6091
			$recurring_dates = isset($gd_post['recurring_dates']) && $gd_post['recurring_dates'] != '' ? explode(",", $gd_post['recurring_dates']) : array();
6092
			if (!empty($recurring_dates)) {
6093
				$event_recurring_dates = array();
6094
				
6095
				foreach ($recurring_dates as $recurring_date) {
6096
					$recurring_date = trim($recurring_date);
6097
					
6098
					if ($recurring_date != '') {
6099
						$event_recurring_dates[] = geodir_imex_get_date_ymd($recurring_date);
6100
					}
6101
				}
6102
				
6103
				$event_recurring_dates = array_unique($event_recurring_dates);
6104
				$event_recurring_dates = implode(",", $event_recurring_dates);
6105
			}
6106
		} else {
6107
			$duration_x = !empty( $gd_post['event_duration_days'] ) ? (int)$gd_post['event_duration_days'] : 1;
6108
			$repeat_x = !empty( $gd_post['recurring_interval'] ) ? (int)$gd_post['recurring_interval'] : 1;
6109
			$max_repeat = !empty( $gd_post['max_recurring_count'] ) ? (int)$gd_post['max_recurring_count'] : 1;
6110
			$repeat_end = !empty( $gd_post['recurring_end_date'] ) ? geodir_imex_get_date_ymd($gd_post['recurring_end_date']) : '';
6111
			
6112
			$repeat_end_type = $repeat_end != '' ? 1 : 0;
6113
			$max_repeat = $repeat_end != '' ? '' : $max_repeat;
6114
			
6115
			$week_days = array_flip(array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'));
6116
			
6117
			$a_repeat_days = isset($gd_post['recurring_week_days']) && trim($gd_post['recurring_week_days'])!='' ? explode(',', trim($gd_post['recurring_week_days'])) : array();
6118
			$repeat_days = array();
6119
			if (!empty($a_repeat_days)) {
6120
				foreach ($a_repeat_days as $repeat_day) {
6121
					$repeat_day = geodir_strtolower(trim($repeat_day));
6122
					
6123
					if ($repeat_day != '' && isset($week_days[$repeat_day])) {
6124
						$repeat_days[] = $week_days[$repeat_day];
6125
					}
6126
				}
6127
				
6128
				$repeat_days = array_unique($repeat_days);
6129
			}
6130
			
6131
			$a_repeat_weeks = isset($gd_post['recurring_week_nos']) && trim($gd_post['recurring_week_nos']) != '' ? explode(",", trim($gd_post['recurring_week_nos'])) : array();
6132
			$repeat_weeks = array();
6133
			if (!empty($a_repeat_weeks)) {
6134
				foreach ($a_repeat_weeks as $repeat_week) {
6135
					$repeat_weeks[] = (int)$repeat_week;
6136
				}
6137
				
6138
				$repeat_weeks = array_unique($repeat_weeks);
6139
			}
6140
		}
6141
	}
6142
	
6143
	if (isset($gd_post['recurring_dates'])) {
6144
		unset($gd_post['recurring_dates']);
6145
	}
6146
6147
	$gd_post['is_recurring'] = $is_recurring;
6148
	$gd_post['event_date'] = $event_date;
6149
	$gd_post['event_start'] = $event_date;
6150
	$gd_post['event_end'] = $event_enddate;
6151
	$gd_post['all_day'] = $all_day;
6152
	$gd_post['starttime'] = $starttime;
6153
	$gd_post['endtime'] = $endtime;
6154
	
6155
	$gd_post['repeat_type'] = $repeat_type;
6156
	$gd_post['different_times'] = $different_times;
6157
	$gd_post['starttimes'] = $starttimes;
6158
	$gd_post['endtimes'] = $endtimes;
6159
	$gd_post['repeat_days'] = $repeat_days;
6160
	$gd_post['repeat_weeks'] = $repeat_weeks;
6161
	$gd_post['event_recurring_dates'] = $event_recurring_dates;
6162
	$gd_post['repeat_x'] = $repeat_x;
6163
	$gd_post['duration_x'] = $duration_x;
6164
	$gd_post['repeat_end_type'] = $repeat_end_type;
6165
	$gd_post['max_repeat'] = $max_repeat;
6166
	$gd_post['repeat_end'] = $repeat_end;
6167
6168
	return $gd_post;
6169
}
6170
6171
/**
6172
 * Create a page.
6173
 *
6174
 * @since 1.0.0
6175
 * @package GeoDirectory
6176
 * @global object $wpdb WordPress Database object.
6177
 * @global object $current_user Current user object.
6178
 * @param string $slug The page slug.
6179
 * @param string $option The option meta key.
6180
 * @param string $page_title The page title.
6181
 * @param string $page_content The page description.
6182
 * @param int $post_parent Parent page ID.
6183
 * @param string $status Post status.
6184
 */
6185
function geodir_create_page($slug, $option, $page_title = '', $page_content = '', $post_parent = 0, $status = 'publish') {
6186
    global $wpdb, $current_user;
6187
6188
    $option_value = get_option($option);
6189
6190
    if ($option_value > 0) :
6191
        if (get_post($option_value)) :
6192
            // Page exists
6193
            return;
6194
        endif;
6195
    endif;
6196
6197
    $page_found = $wpdb->get_var(
6198
        $wpdb->prepare(
6199
            "SELECT ID FROM " . $wpdb->posts . " WHERE post_name = %s LIMIT 1;",
6200
            array($slug)
6201
        )
6202
    );
6203
6204
    if ($page_found) :
6205
        // Page exists
6206
        if (!$option_value) update_option($option, $page_found);
6207
        return;
6208
    endif;
6209
6210
    $page_data = array(
6211
        'post_status' => $status,
6212
        'post_type' => 'page',
6213
        'post_author' => $current_user->ID,
6214
        'post_name' => $slug,
6215
        'post_title' => $page_title,
6216
        'post_content' => $page_content,
6217
        'post_parent' => $post_parent,
6218
        'comment_status' => 'closed'
6219
    );
6220
    $page_id = wp_insert_post($page_data);
6221
6222
    add_option($option, $page_id);
6223
6224
}
6225
6226
/**
6227
 * Get WPML original translation element id.
6228
 *
6229
 * @since 1.5.3
6230
 *
6231
 * @global object $sitepress Sitepress WPML object.
6232
 *
6233
 * @param int $element_id Post ID or Term id.
6234
 * @param string $element_type Element type. Ex: post_gd_place or tax_gd_placecategory.
6235
 * @return Original element id.
6236
 */
6237
function geodir_imex_original_post_id($element_id, $element_type) {
6238
	global $sitepress;
6239
	
6240
	$original_element_id = $sitepress->get_original_element_id($element_id, $element_type);
6241
	$element_id = $element_id != $original_element_id ? $original_element_id : '';
6242
	
6243
	return $element_id;
6244
}
6245
6246
/*
6247
 * Show admin notice if core is out of date for the current addons.
6248
 *
6249
 * @since 1.5.4
6250
 * @package GeoDirectory
6251
 */
6252
function geodir_admin_upgrade_notice() {
6253
    $class = "error";
6254
    $message = __("Please update core GeoDirectory or some addons may not function correctly.","geodirectory");
6255
    echo"<div class=\"$class\"> <p>$message</p></div>";
6256
}
6257
6258
/**
6259
 * Displays an update message for plugin list screens.
6260
 * Shows only the version updates from the current until the newest version
6261
 *
6262
 * @param (array) $plugin_data
6263
 * @param (object) $r
6264
 * @return (string) $output
6265
 */
6266
function geodire_admin_upgrade_notice( $plugin_data, $r )
0 ignored issues
show
Unused Code introduced by
The parameter $plugin_data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $r is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
6267
{
6268
    // readme contents
6269
    $args = array(
6270
        'timeout'     => 15,
6271
        'redirection' => 5
6272
    );
6273
    $url = "http://plugins.svn.wordpress.org/geodirectory/trunk/readme.txt";
6274
    $data       = wp_remote_get( $url, $args );
6275
6276
    if (!is_wp_error($data) && $data['response']['code'] == 200) {
6277
6278
        geodir_in_plugin_update_message($data['body']);
6279
    }
6280
}
6281
6282
6283
/*
6284
* @param string $content http response body
6285
*/
6286
function geodir_in_plugin_update_message($content) {
6287
    // Output Upgrade Notice
6288
    $matches        = null;
6289
    $regexp         = '~==\s*Upgrade Notice\s*==\s*=\s*(.*)\s*=(.*)(=\s*' . preg_quote( GEODIRECTORY_VERSION ) . '\s*=|$)~Uis';
6290
    $upgrade_notice = '';
6291
    if ( preg_match( $regexp, $content, $matches ) ) {
6292
        if(empty($matches)){return;}
6293
6294
        $version = trim( $matches[1] );
6295
        if($version && $version>GEODIRECTORY_VERSION){
6296
6297
6298
        $notices = (array) preg_split('~[\r\n]+~', trim( $matches[2] ) );
6299
        if ( version_compare( GEODIRECTORY_VERSION, $version, '<' ) ) {
6300
            $upgrade_notice .= '<div class="geodir_plugin_upgrade_notice">';
6301
            foreach ( $notices as $index => $line ) {
6302
                $upgrade_notice .= wp_kses_post( preg_replace( '~\[([^\]]*)\]\(([^\)]*)\)~', '<a href="${2}">${1}</a>', $line ) );
6303
            }
6304
            $upgrade_notice .= '</div> ';
6305
        }
6306
        }
6307
    }
6308
    echo $upgrade_notice;
6309
}
6310
6311
/**
6312
 * Display notice on geodirectory permalink settings page to don't pages settings on a different language when wpml is active.
6313
 *
6314
 * @package GeoDirectory
6315
 * @since 1.5.7
6316
 *
6317
 * @global object $sitepress Sitepress WPML object.
6318
 */
6319
function geodir_wpml_permalink_setting_notice() {
6320
	if (geodir_is_wpml()) {
6321
		global $sitepress;
6322
		$current_language = $sitepress->get_current_language();
6323
		$default_language = $sitepress->get_default_language();
6324
		if ($current_language != 'all' && $current_language != $default_language) {
6325
	?>
6326
	<div class="updated error notice-success" id="message"><p style="color:red"><strong><?php _e('Saving GeoDirectory pages settings on a different language breaks pages settings. Try to save after switching to default language.', 'geodirectory');?></strong></p></div>
6327
	<?php
6328
		}
6329
	}
6330
}
6331
6332
/**
6333
 * Get the statuses to skip during GD export listings.
6334
 *
6335
 * @package GeoDirectory
6336
 * @since 1.6.0
6337
 *
6338
 * @param array Listing statuses to be skipped.
6339
 */
6340
function geodir_imex_export_skip_statuses() {
6341
    $statuses = array( 'trash', 'auto-draft' );
6342
    
6343
    /**
6344
     * Filter the statuses to skip during GD export listings.
6345
     *
6346
     * @since 1.6.0
6347
     * @package GeoDirectory
6348
     *
6349
     * @param array $statuses Listing statuses to be skipped.
6350
     */
6351
    $statuses = apply_filters( 'geodir_imex_export_skip_statuses', $statuses );
6352
     
6353
    return $statuses;
6354
}
6355
6356
/**
6357
 * Dequeue jQuery chosen javascript.
6358
 * 
6359
 * Fix conflicts between jQuery chosen javascripts.
6360
 *
6361
 * @package GeoDirectory
6362
 * @since 1.6.3
6363
 */
6364
function geodir_admin_dequeue_scripts() {
6365
    // EDD
6366
    if (wp_script_is('jquery-chosen', 'enqueued')) {
6367
        wp_dequeue_script('jquery-chosen');
6368
    }
6369
    
6370
    // Ultimate Addons for Visual Composer
6371
    if (wp_script_is('ultimate-vc-backend-script', 'enqueued')) {
6372
        wp_dequeue_script('ultimate-vc-backend-script');
6373
    }
6374
}
6375
6376
/**
6377
 * Get the SQL where clause part to filter posts in import/export.
6378
 *
6379
 * @package GeoDirectory
6380
 * @since 1.6.4
6381
 *
6382
 * @global object $wpdb WordPress Database object.
6383
 * 
6384
 * @param string $where The SQL where clause part. Default empty.
6385
 * @param string $post_type The post type.
6386
 * @return string SQL where clause part.
6387
 */
6388
function geodir_imex_get_filter_where($where = '', $post_type = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $post_type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
6389
    global $wpdb;
6390
    
6391
    $filters = !empty( $_REQUEST['gd_imex'] ) && is_array( $_REQUEST['gd_imex'] ) ? $_REQUEST['gd_imex'] : NULL;
6392
    
6393
    if ( !empty( $filters ) ) {
6394
        foreach ( $filters as $field => $value ) {
6395
            switch ($field) {
6396
                case 'start_date':
6397
                    $where .= " AND `" . $wpdb->posts . "`.`post_date` >= '" . sanitize_text_field( $value ) . " 00:00:00'";
6398
                break;
6399
                case 'end_date':
6400
                    $where .= " AND `" . $wpdb->posts . "`.`post_date` <= '" . sanitize_text_field( $value ) . " 23:59:59'";
6401
                break;
6402
            }
6403
        }
6404
    }
6405
    
6406
    return $where;
6407
}
6408
add_filter('geodir_get_posts_count', 'geodir_imex_get_filter_where', 10, 2);
6409
add_filter('geodir_get_export_posts', 'geodir_imex_get_filter_where', 10, 2);
6410
6411
6412
function geodir_fix_for_primer_theme(){
6413
    if(!defined( 'PRIMER_VERSION' )){return;}
6414
    global $pagenow;
6415
6416
    if ( ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) && (isset($_REQUEST['post_type']) || isset($_REQUEST['post']) )  ){
6417
6418
        $post_type = isset($_REQUEST['post_type']) ? esc_attr($_REQUEST['post_type']) : get_post_type( $_GET['post'] );
6419
6420
        $post_types = geodir_get_posttypes();
6421
        if ($post_type && in_array($post_type, $post_types) ) {
6422
            global $primer_customizer_layouts;
6423
            remove_action( 'add_meta_boxes', array( $primer_customizer_layouts, 'add_meta_box' ), 10);
6424
        }
6425
    }
6426
6427
}
6428
6429
if(is_admin()){
6430
    add_action('add_meta_boxes','geodir_fix_for_primer_theme',0);  
6431
}
6432
6433
6434
/*
6435
 * Look at doing menu items this way, must be customiser ready
6436
 * @todo research below
6437
 */
6438
// GeoDirectory Menu Items
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
6439
/*
6440
6441
function geodir_register_menu_metabox() {
6442
    $custom_param = array( 0 => 'This param will be passed to my_render_menu_metabox' );
6443
6444
    add_meta_box( 'geodir-menu-metabox', 'GeoDirectory Items', 'geodir_render_menu_metabox', 'nav-menus', 'side', 'default', $custom_param );
6445
}
6446
add_action( 'admin_head-nav-menus.php', 'geodir_register_menu_metabox' );
6447
if(is_admin()){
6448
6449
    //add_action( 'customize_register', 'geodir_register_menu_metabox' );
6450
}
6451
*/
6452
/**
6453
 * Displays a menu metabox
6454
 *
6455
 * @param string $object Not used.
6456
 * @param array $args Parameters and arguments. If you passed custom params to add_meta_box(),
6457
 * they will be in $args['args']
6458
 */
6459
/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
6460
function geodir_render_menu_metabox( $object, $args ) {
6461
    global $nav_menu_selected_id;
6462
6463
    // Create an array of objects that imitate Post objects
6464
    $my_items = array(
6465
        (object) array(
6466
            'ID' => 0,
6467
            'db_id' => 0,
6468
            'menu_item_parent' => 0,
6469
            'object_id' => 1,
6470
            'post_parent' => 0,
6471
            'type' => 'custom',
6472
            'object' => 'my-object-slug',
6473
            'type_label' => 'My Cool Plugin',
6474
            'title' => 'Custom Link 1',
6475
            'url' => home_url( '/jobs/' ),
6476
            'target' => '',
6477
            'attr_title' => '',
6478
            'description' => '123',
6479
            'classes' => array(),
6480
            'xfn' => '',
6481
        ),
6482
        (object) array(
6483
            'ID' => 2,
6484
            'db_id' => 0,
6485
            'menu_item_parent' => 0,
6486
            'object_id' => 1,
6487
            'post_parent' => 0,
6488
            'type' => 'custom',
6489
            'object' => 'my-object-slug',
6490
            'type_label' => 'My Cool Plugin',
6491
            'title' => 'Custom Link 2',
6492
            'url' => home_url( '/custom-link-2/' ),
6493
            'target' => '',
6494
            'attr_title' => '',
6495
            'description' => '123',
6496
            'classes' => array(),
6497
            'xfn' => '',
6498
        ),
6499
        (object) array(
6500
            'ID' => 3,
6501
            'db_id' => 0,
6502
            'menu_item_parent' => 0,
6503
            'object_id' => 1,
6504
            'post_parent' => 0,
6505
            'type' => 'custom',
6506
            'object' => 'my-object-slug',
6507
            'type_label' => 'My Cool Plugin',
6508
            'title' => 'Custom Link 3',
6509
            'url' => home_url( '/custom-link-3/' ),
6510
            'target' => '',
6511
            'attr_title' => '',
6512
            'description' => '123',
6513
            'classes' => array(),
6514
            'xfn' => '',
6515
        ),
6516
    );
6517
    $db_fields = false;
6518
    // If your links will be hierarchical, adjust the $db_fields array bellow
6519
    if ( false ) {
6520
        $db_fields = array( 'parent' => 'parent', 'id' => 'post_parent' );
6521
    }
6522
    $walker = new Walker_Nav_Menu_Checklist( $db_fields );
6523
6524
    $removed_args = array(
6525
        'action',
6526
        'customlink-tab',
6527
        'edit-menu-item',
6528
        'menu-item',
6529
        'page-tab',
6530
        '_wpnonce',
6531
    ); ?>
6532
    <div id="my-plugin-div">
6533
    <div id="tabs-panel-my-plugin-all" class="tabs-panel tabs-panel-active">
6534
        <ul id="my-plugin-checklist-pop" class="categorychecklist form-no-clear" >
6535
            <?php echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $my_items ), 0, (object) array( 'walker' => $walker ) ); ?>
6536
        </ul>
6537
6538
        <p class="button-controls">
6539
			<span class="list-controls">
6540
				<a href="<?php
6541
                echo esc_url(add_query_arg(
6542 1
                    array(
6543
                        'my-plugin-all' => 'all',
6544 1
                        'selectall' => 1,
6545
                    ),
6546 1
                    remove_query_arg( $removed_args )
6547
                ));
6548
                ?>#my-menu-test-metabox" class="select-all"><?php _e( 'Select All' ); ?></a>
6549
			</span>
6550
6551
			<span class="add-to-menu">
6552
				<input type="submit"<?php wp_nav_menu_disabled_check( $nav_menu_selected_id ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-my-plugin-menu-item" id="submit-my-plugin-div" />
6553 1
				<span class="spinner"></span>
6554 1
			</span>
6555 1
        </p>
6556 1
    </div>
6557 1
<?php
6558 1
}
6559
*/
6560 1
6561
function geodir_ga_activation_url() {
6562 1
6563 1
    return add_query_arg( array(
6564
        'next'          => admin_url("admin.php?page=geodirectory&active_tab=google_analytic_settings"),
6565
        'scope'         => GEODIR_GA_SCOPE,
6566
        'response_type' => 'code',
6567
        'redirect_uri'  => GEODIR_GA_REDIRECT,
6568
        'client_id'     => GEODIR_GA_CLIENTID,
6569
    ), 'https://accounts.google.com/o/oauth2/auth' );
6570
6571
    return $url;
0 ignored issues
show
Unused Code introduced by
return $url; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
6572
}
6573
6574
function geodir_gd_accounts(){
6575
    $accounts = array();
6576
    $useAuth = ( get_option( 'geodir_ga_auth_code' ) == '' ? false : true );
6577
    if($useAuth){
6578
        $accounts = geodir_ga_get_analytics_accounts();
6579
        if(is_array($accounts)){
6580
            $accounts = array_merge(array(__('Select Account','geodirectory')),$accounts);
6581
        }elseif(get_option('geodir_ga_account_id')){
6582
            $accounts = array();
6583
            $accounts[get_option('geodir_ga_account_id')] = __('Account re-authorization may be required','geodirectory').' ('.get_option('geodir_ga_account_id').')';
6584
        }
6585
    }
6586
    return $accounts;
6587
}
6588
6589
function geodir_ga_get_analytics_accounts()
6590
{
6591
    $accounts = array();
0 ignored issues
show
Unused Code introduced by
$accounts is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
6592
6593
    if(get_option('geodir_ga_auth_token')===false){update_option('geodir_ga_auth_token','');}
6594
6595
6596
    if(get_option('geodir_gd_uids') && !isset($_POST['geodir_ga_auth_code'])){
6597
        return get_option('geodir_gd_uids');
6598
    }
6599
6600
    
6601
    # Create a new Gdata call
6602
    if ( trim(get_option('geodir_ga_auth_code')) != '' )
6603
        $stats = new GDGoogleAnalyticsStats();
6604
    else
6605
        return false;
6606
6607
    # Check if Google sucessfully logged in
6608
    if ( ! $stats->checkLogin() )
6609
        return false;
6610
6611
    # Get a list of accounts
6612
    $accounts = $stats->getAllProfiles();
6613
6614
    natcasesort ($accounts);
6615
6616
    # Return the account array if there are accounts
6617
    if ( count($accounts) > 0 ){
6618
        update_option('geodir_gd_uids',$accounts);
6619
        return $accounts;
6620
    }
6621
    else
6622
        return false;
6623
}
6624
6625