Passed
Pull Request — master (#234)
by Kiran
13:23
created

admin_functions.php ➔ geodir_update_options()   F

Complexity

Conditions 49
Paths 583

Size

Total Lines 141
Code Lines 97

Duplication

Lines 34
Ratio 24.11 %

Code Coverage

Tests 38
CRAP Score 589.1711
Metric Value
cc 49
eloc 97
nc 583
nop 2
dl 34
loc 141
ccs 38
cts 97
cp 0.3918
crap 589.1711
rs 2.1629

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
{
17
18
    // Update installed variable
19
    update_option("geodir_installed", 0);
20
21
    // Remove rewrite rules and then recreate rewrite rules.
22
    flush_rewrite_rules();
23
}
24
25
26
/**
27
 * Deletes option value when GeoDirectory get uninstalled.
28
 *
29
 * @since 1.0.0
30
 * @package GeoDirectory
31
 */
32
function geodir_uninstall()
33
{
34
35
    delete_option('geodir_default_data_installed');
36
37
}
38
39
if (!function_exists('geodir_admin_styles')) {
40
    /**
41
     * Enqueue Admin Styles.
42
     *
43
     * @since 1.0.0
44
     * @package GeoDirectory
45
     */
46
    function geodir_admin_styles()
47
    {
48
49
        wp_register_style('geodirectory-admin-css', geodir_plugin_url() . '/geodirectory-assets/css/admin.css', array(), GEODIRECTORY_VERSION);
50
        wp_enqueue_style('geodirectory-admin-css');
51
52
        wp_register_style('geodirectory-frontend-style', geodir_plugin_url() . '/geodirectory-assets/css/style.css', array(), GEODIRECTORY_VERSION);
53
        wp_enqueue_style('geodirectory-frontend-style');
54
55
        wp_register_style('geodir-chosen-style', geodir_plugin_url() . '/geodirectory-assets/css/chosen.css', array(), GEODIRECTORY_VERSION);
56
        wp_enqueue_style('geodir-chosen-style');
57
58
        wp_register_style('geodirectory-jquery-ui-timepicker-css', geodir_plugin_url() . '/geodirectory-assets/css/jquery.ui.timepicker.css', array(), GEODIRECTORY_VERSION);
59
        wp_enqueue_style('geodirectory-jquery-ui-timepicker-css');
60
61
        wp_register_style('geodirectory-jquery-ui-css', geodir_plugin_url() . '/geodirectory-assets/css/jquery-ui.css', array(), GEODIRECTORY_VERSION);
62
        wp_enqueue_style('geodirectory-jquery-ui-css');
63
64
        wp_register_style('geodirectory-custom-fields-css', geodir_plugin_url() . '/geodirectory-assets/css/custom_field.css', array(), GEODIRECTORY_VERSION);
65
        wp_enqueue_style('geodirectory-custom-fields-css');
66
67
        wp_register_style('geodirectory-pluplodar-css', geodir_plugin_url() . '/geodirectory-assets/css/pluploader.css', array(), GEODIRECTORY_VERSION);
68
        wp_enqueue_style('geodirectory-pluplodar-css');
69
70
        wp_register_style('geodir-rating-style', geodir_plugin_url() . '/geodirectory-assets/css/jRating.jquery.css', array(), GEODIRECTORY_VERSION);
71
        wp_enqueue_style('geodir-rating-style');
72
73
        wp_register_style('geodir-rtl-style', geodir_plugin_url() . '/geodirectory-assets/css/rtl.css', array(), GEODIRECTORY_VERSION);
74
        wp_enqueue_style('geodir-rtl-style');
75
76
    }
77
}
78
79
if (!function_exists('geodir_admin_styles_req')) {
80
    /**
81
     * Loads stylesheets from CDN.
82
     *
83
     * @since 1.0.0
84
     * @package GeoDirectory
85
     */
86
    function geodir_admin_styles_req()
87
    {
88
89
        wp_register_style('geodirectory-font-awesome', '//netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css', array(), GEODIRECTORY_VERSION);
90
        wp_enqueue_style('geodirectory-font-awesome');
91
92
        wp_register_script('geodirectory-admin', geodir_plugin_url() . '/geodirectory-assets/js/admin-req.min.js', array('jquery'), GEODIRECTORY_VERSION);
93
        wp_enqueue_script('geodirectory-admin');
94
95
    }
96
}
97
98
if (!function_exists('geodir_admin_scripts')) {
99
    /**
100
     * Enqueue Admin Scripts.
101
     *
102
     * @since 1.0.0
103
     * @package GeoDirectory
104
     */
105
    function geodir_admin_scripts()
106
    {
107
108
        wp_enqueue_script('jquery');
109
110
        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);
111
112
        wp_register_script('chosen', geodir_plugin_url() . '/geodirectory-assets/js/chosen.jquery.js', array(), GEODIRECTORY_VERSION);
113
        wp_enqueue_script('chosen');
114
115
        wp_register_script('geodirectory-choose-ajax', geodir_plugin_url() . '/geodirectory-assets/js/ajax-chosen.js', array(), GEODIRECTORY_VERSION);
116
        wp_enqueue_script('geodirectory-choose-ajax');
117
118
        if (isset($_REQUEST['listing_type'])) {
119
            wp_register_script('geodirectory-custom-fields-script', geodir_plugin_url() . '/geodirectory-assets/js/custom_fields.js', array(), GEODIRECTORY_VERSION);
120
        }
121
122
        wp_enqueue_script('geodirectory-custom-fields-script');
123
        $plugin_path = geodir_plugin_url() . '/geodirectory-functions/cat-meta-functions';
124
125
        wp_enqueue_script('tax-meta-clss', $plugin_path . '/js/tax-meta-clss.js', array('jquery'), null, true);
126
127
        $map_lang = "&language=" . geodir_get_map_default_language();
128
        /** This filter is documented in geodirectory_template_tags.php */
129
        $map_extra = apply_filters('geodir_googlemap_script_extra', '');
130
        wp_enqueue_script('geodirectory-googlemap-script', '//maps.google.com/maps/api/js?' . $map_lang . $map_extra, '', NULL);
131
132
        wp_register_script('geodirectory-goMap-script', geodir_plugin_url() . '/geodirectory-assets/js/goMap.js', array(), GEODIRECTORY_VERSION);
133
        wp_enqueue_script('geodirectory-goMap-script');
134
135
		// font awesome rating script
136 View Code Duplication
		if (get_option('geodir_reviewrating_enable_font_awesome')) {
137
			wp_register_script('geodir-barrating-js', geodir_plugin_url() . '/geodirectory-assets/js/jquery.barrating.min.js', array(), GEODIRECTORY_VERSION);
138
			wp_enqueue_script('geodir-barrating-js');
139
		} else { // default rating script
140
			wp_register_script('geodir-jRating-js', geodir_plugin_url() . '/geodirectory-assets/js/jRating.jquery.js', array(), GEODIRECTORY_VERSION);
141
			wp_enqueue_script('geodir-jRating-js');
142
		}
143
144
        wp_register_script('geodir-on-document-load', geodir_plugin_url() . '/geodirectory-assets/js/on_document_load.js', array(), GEODIRECTORY_VERSION);
145
        wp_enqueue_script('geodir-on-document-load');
146
147
148
        // SCRIPT FOR UPLOAD
149
        wp_enqueue_script('plupload-all');
150
        wp_enqueue_script('jquery-ui-sortable');
151
152
        wp_register_script('geodirectory-plupload-script', geodir_plugin_url() . '/geodirectory-assets/js/geodirectory-plupload.js', array(), GEODIRECTORY_VERSION);
153
        wp_enqueue_script('geodirectory-plupload-script');
154
155
        // SCRIPT FOR UPLOAD END
156
157
158
        // place js config array for plupload
159
        $plupload_init = array(
160
            'runtimes' => 'html5,silverlight,flash,html4',
161
            'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
162
            'container' => 'plupload-upload-ui', // will be adjusted per uploader
163
            'drop_element' => 'dropbox', // will be adjusted per uploader
164
            'file_data_name' => 'async-upload', // will be adjusted per uploader
165
            'multiple_queues' => true,
166
            'max_file_size' => geodir_max_upload_size(),
167
            'url' => admin_url('admin-ajax.php'),
168
            'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
169
            'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
170
            'filters' => array(array('title' => __('Allowed Files', 'geodirectory'), 'extensions' => '*')),
171
            'multipart' => true,
172
            'urlstream_upload' => true,
173
            'multi_selection' => false, // will be added per uploader
174
            // additional post data to send to our ajax hook
175
            'multipart_params' => array(
176
                '_ajax_nonce' => "", // will be added per uploader
177
                'action' => 'plupload_action', // the ajax action name
178
                'imgid' => 0 // will be added per uploader
179
            )
180
        );
181
        $base_plupload_config = json_encode($plupload_init);
182
183
184
        $thumb_img_arr = array();
185
186
        if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '')
187
            $thumb_img_arr = geodir_get_images($_REQUEST['pid']);
188
189
        $totImg = '';
190
        $image_limit = '';
191
        if (!empty($thumb_img_arr)) {
192
            $totImg = count($thumb_img_arr);
193
        }
194
195
        $gd_plupload_init = array('base_plupload_config' => $base_plupload_config,
196
            'totalImg' => $totImg,
197
            'image_limit' => $image_limit,
198
            'upload_img_size' => geodir_max_upload_size());
199
200
        wp_localize_script('geodirectory-plupload-script', 'gd_plupload', $gd_plupload_init);
201
202
        $ajax_cons_data = array('url' => __(admin_url('admin-ajax.php')));
203
        wp_localize_script('geodirectory-custom-fields-script', 'geodir_admin_ajax', $ajax_cons_data);
204
205
206
        wp_register_script('geodirectory-admin-script', geodir_plugin_url() . '/geodirectory-assets/js/admin.js', array(), GEODIRECTORY_VERSION);
207
        wp_enqueue_script('geodirectory-admin-script');
208
209
        wp_enqueue_style('farbtastic');
210
        wp_enqueue_script('farbtastic');
211
212
        $screen = get_current_screen();
213
        if ($screen->base == 'post' && in_array($screen->post_type, geodir_get_posttypes())) {
214
            wp_enqueue_script('geodirectory-listing-validation-script', geodir_plugin_url() . '/geodirectory-assets/js/listing_validation_admin.js');
215
        }
216
217
        $ajax_cons_data = array('url' => __(get_option('siteurl') . '?geodir_ajax=true'));
218
        wp_localize_script('geodirectory-admin-script', 'geodir_ajax', $ajax_cons_data);
219
220
    }
221
}
222
223
if (!function_exists('geodir_admin_menu')) {
224
    /**
225
     * Admin Menus
226
     *
227
     * Sets up the admin menus in wordpress.
228
     *
229
     * @since 1.0.0
230
     * @package GeoDirectory
231
     * @global array $menu Menu array.
232
     * @global object $geodirectory GeoDirectory plugin object.
233
     */
234
    function geodir_admin_menu()
235
    {
236
        global $menu, $geodirectory;
237
238
        if (current_user_can('manage_options')) $menu[] = array('', 'read', 'separator-geodirectory', '', 'wp-menu-separator geodirectory');
239
240
        add_menu_page(__('Geodirectory', 'geodirectory'), __('Geodirectory', 'geodirectory'), 'manage_options', 'geodirectory', 'geodir_admin_panel', geodir_plugin_url() . '/geodirectory-assets/images/favicon.ico', '55.1984');
241
242
243
    }
244
}
245
246
if (!function_exists('geodir_admin_menu_order')) {
247
    /**
248
     * Order admin menus.
249
     *
250
     * @since 1.0.0
251
     * @package GeoDirectory
252
     * @param array $menu_order Menu order array.
253
     * @return array Modified menu order array.
254
     */
255
    function geodir_admin_menu_order($menu_order)
256
    {
257
258
        // Initialize our custom order array
259
        $geodir_menu_order = array();
260
261
        // Get the index of our custom separator
262
        $geodir_separator = array_search('separator-geodirectory', $menu_order);
263
264
        // Get index of posttype menu
265
        $post_types = geodir_get_posttypes();
266
267
        // Loop through menu order and do some rearranging
268
        foreach ($menu_order as $index => $item) :
269
270
            if ((('geodirectory') == $item)) :
271
                $geodir_menu_order[] = 'separator-geodirectory';
272
                if (!empty($post_types)) {
273
                    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...
274
                        $geodir_menu_order[] = 'edit.php?post_type=' . $post_type;
275
                    }
276
                }
277
                $geodir_menu_order[] = $item;
278
279
                unset($menu_order[$geodir_separator]);
280
            //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...
281
            elseif (!in_array($item, array('separator-geodirectory'))) :
282
                $geodir_menu_order[] = $item;
283
            endif;
284
285
        endforeach;
286
287
        // Return order
288
        return $geodir_menu_order;
289
    }
290
}
291
292
if (!function_exists('geodir_admin_custom_menu_order')) {
293
    /**
294
     * Enables custom menu order.
295
     *
296
     * @since 1.0.0
297
     * @package GeoDirectory
298
     * @return bool
299
     */
300
    function geodir_admin_custom_menu_order()
301
    {
302
        if (!current_user_can('manage_options')) return false;
303
        return true;
304
    }
305
}
306
307
/**
308
 * Function to show success or error message on admin option form submission.
309
 *
310
 * @since 1.0.0
311
 * @package GeoDirectory
312
 */
313
function geodir_before_admin_panel()
314
{
315 1
    if (isset($_REQUEST['installed']) && $_REQUEST['installed'] != '') {
316
        echo '<div id="message" class="updated fade">
317
                        <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>
318
                        <p><strong>' . __('Geodirectory has been installed and setup. Enjoy :)', 'geodirectory') . '</strong></p>
319
                </div>';
320
321
    }
322
323 1
    if (isset($_REQUEST['msg']) && $_REQUEST['msg'] != '') {
324
        switch ($_REQUEST['msg']) {
325
            case 'success':
326
                echo '<div id="message" class="updated fade"><p><strong>' . __('Your settings have been saved.', 'geodirectory') . '</strong></p></div>';
327
                flush_rewrite_rules(false);
328
329
                break;
330
			case 'fail':
331
				$gderr = isset($_REQUEST['gderr']) ? $_REQUEST['gderr'] : '';
332
				
333
				if ($gderr == 21)
334
			    	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>';
335
				else
336
					echo '<div id="message" class="error fade"><p><strong>' . __('Error: Your settings have not been saved, please try again.', 'geodirectory') . '</strong></p></div>';
337
                break;
338
        }
339
    }
340
341 1
    if (!geodir_is_default_location_set()) {
342
        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>';
343
344
    }
345
346 1
    if (!function_exists('curl_init')) {
347
        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>';
348
349
    }
350 1
}
351
352
/**
353
 * Handles data posted from GeoDirectory settings form.
354
 *
355
 * @since 1.0.0
356
 * @package GeoDirectory
357
 * @global array $geodir_settings Geodirectory settings array.
358
 * @param string $current_tab The current settings tab name.
359
 */
360
function geodir_handle_option_form_submit($current_tab)
361
{
362
    global $geodir_settings;
363
    if (file_exists(dirname(__FILE__) . '/option-pages/' . $current_tab . '_array.php')) {
364
        /**
365
         * Contains settings array for current tab.
366
         *
367
         * @since 1.0.0
368
         * @package GeoDirectory
369
         */
370
        include_once('option-pages/' . $current_tab . '_array.php');
371
    }
372
    if (isset($_POST) && $_POST && isset($_REQUEST['page']) && $_REQUEST['page'] == 'geodirectory') :
373
        if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'geodir-settings')) die(__('Action failed. Please refresh the page and retry.', 'geodirectory'));
374
        if (!wp_verify_nonce($_REQUEST['_wpnonce-' . $current_tab], 'geodir-settings-' . $current_tab)) die(__('Action failed. Please refresh the page and retry.', 'geodirectory'));
375
		
376
		/**
377
		 * Fires before updating geodirectory admin settings.
378
		 *
379
		 * @since 1.4.2
380
		 *
381
		 * @param string $current_tab Current tab in geodirectory settings.
382
		 * @param array  $geodir_settings Array of geodirectory settings.
383
		 */
384
		do_action('geodir_before_update_options', $current_tab, $geodir_settings);		
385
		
386
        if (!empty($geodir_settings[$current_tab]))
387
            geodir_update_options($geodir_settings[$current_tab]);
388
389
        /**
390
         * Called after GeoDirectory options settings are updated.
391
         *
392
         * @since 1.0.0
393
         * @param array $geodir_settings The array of GeoDirectory settings.
394
         * @see 'geodir_before_update_options'
395
         */
396
        do_action('geodir_update_options', $geodir_settings);
397
398
        /**
399
         * Called after GeoDirectory options settings are updated.
400
         *
401
         * Provides tab specific settings.
402
         *
403
         * @since 1.0.0
404
         * @param string $current_tab The current settings tab name.
405
         * @param array $geodir_settings[$current_tab] The array of settings for the current settings tab.
406
         */
407
        do_action('geodir_update_options_' . $current_tab, $geodir_settings[$current_tab]);
408
409
        flush_rewrite_rules(false);
410
411
        $current_tab = isset($_REQUEST['tab']) ? $_REQUEST['tab'] : '';
412
413
        $redirect_url = admin_url('admin.php?page=geodirectory&tab=' . $current_tab . '&active_tab=' . $_REQUEST['active_tab'] . '&msg=success');
414
415
        wp_redirect($redirect_url);
416
        exit();
417
    endif;
418
419
420
}
421
422
423
if (!function_exists('geodir_autoinstall_admin_header') && (get_option('geodir_installed') || defined( 'GD_TESTING_MODE' ))) {
424
    /**
425
     * GeoDirectory dummy data installation.
426
     *
427
     * @since 1.0.0
428
     * @package GeoDirectory
429
     * @global object $wpdb WordPress Database object.
430
     * @global string $plugin_prefix Geodirectory plugin table prefix.
431
     * @param string $post_type The post type.
432
     */
433
    function geodir_autoinstall_admin_header($post_type = 'gd_place')
434
    {
435
436 1
        global $wpdb, $plugin_prefix;
437
438 1
        if (!geodir_is_default_location_set()) {
439
            echo '<div class="updated fade"><p><strong>' . sprintf(__('Please %sclick here%s to set a default location, this will help to set location of all dummy data.', 'geodirectory'), '<a href=\'' . admin_url('admin.php?page=geodirectory&tab=default_location_settings') . '\'>', '</a>') . '</strong></p></div>';
440
        } else {
441
442 1
            $geodir_url = admin_url() . 'admin.php?page=geodirectory&tab=general_settings&active_tab=';
443
444 1
            $post_counts = $wpdb->get_var("SELECT count(post_id) FROM " . $plugin_prefix . $post_type . "_detail WHERE post_dummy='1'");
445
446 1
            if ($post_counts > 0) {
447 1
                $nonce = wp_create_nonce('geodir_dummy_posts_delete_noncename');
448
449 1
                $dummy_msg = '<div id="" class="geodir_auto_install updated highlight fade"><p><b>' . SAMPLE_DATA_SHOW_MSG . '</b><br /><a id="geodir_dummy_delete" class="button_delete" onclick="geodir_autoinstall(this,\'geodir_dummy_delete\',\'' . $nonce . '\',\'' . $post_type . '\')" href="javascript:void(0);" redirect_to="' . $geodir_url . '"  >' . DELETE_BTN_SAMPLE_MSG . '</a></p></div>';
450 1
                $dummy_msg .= '<div id="" style="display:none;" class="geodir_show_progress updated highlight fade"><p><b>' . GEODIR_SAMPLE_DATA_DELETE_MSG . '</b><br><img src="' . geodir_plugin_url() . '/geodirectory-assets/images/loadingAnimation.gif" /></p></div>';
451 1
            } else {
452
                $options_list = '';
453
                for ($option = 1; $option <= 30; $option++) {
454
                    $selected = '';
455
                    if ($option == 10)
456
                        $selected = 'selected="selected"';
457
458
                    $options_list .= '<option ' . $selected . ' value="' . $option . '">' . $option . '</option>';
459
                }
460
461
                $nonce = wp_create_nonce('geodir_dummy_posts_insert_noncename');
462
463
                $dummy_msg = '<div id="" class="geodir_auto_install updated highlight fade"><p><b>' . AUTO_INSATALL_MSG . '</b><br /><select class="selected_sample_data">' . $options_list . '</select><a id="geodir_dummy_insert" class="button_insert" href="javascript:void(0);" onclick="geodir_autoinstall(this,\'geodir_dummy_insert\',\'' . $nonce . '\',\'' . $post_type . '\')"   redirect_to="' . $geodir_url . '" >' . INSERT_BTN_SAMPLE_MSG . '</a></p></div>';
464
                $dummy_msg .= '<div id="" style="display:none;" class="geodir_show_progress updated highlight fade"><p><b>' . GEODIR_SAMPLE_DATA_IMPORT_MSG . '</b><br><img src="' . geodir_plugin_url() . '/geodirectory-assets/images/loadingAnimation.gif" /><br><span class="dummy_post_inserted"></span></div>';
465
466
            }
467 1
            echo $dummy_msg;
468
            ?>
469
            <script>
470
                <?php
471
472 1
                    $default_location = geodir_get_default_location();
473 1
                  $city =  isset($default_location->city) ? $default_location->city : '';
474 1
                  $region =isset($default_location->region) ? $default_location->region : '';
475 1
                  $country =isset($default_location->country) ? $default_location->country : '';
476 1
                  $city_latitude =isset($default_location->city_latitude) ? $default_location->city_latitude : '';
477 1
                  $city_longitude =isset($default_location->city_longitude) ? $default_location->city_longitude : '';
478
479
                ?>
480
                var geocoder = new google.maps.Geocoder();
481
                var CITY_ADDRESS = '<?php echo $city.','.$region.','.$country;?>';
482
                var bound_lat_lng;
483
                var lat = <?php echo $city_latitude; ?>;
484
                var lng = <?php echo $city_longitude; ?>;
485
                var latlng = new google.maps.LatLng(lat, lng);
486
                geocoder.geocode({'address': CITY_ADDRESS},
487
                    function (results, status) {
488
489
                        if (status == google.maps.GeocoderStatus.OK) {
490
                            // Bounds for North America
491
                            //	 alert((results[0].geometry.bounds==null))
492
                            if (results[0].geometry.bounds == null) {
493
494
                                bound_lat_lng1 = String(results[0].geometry.viewport.getSouthWest());
495
                                bound_lat_lng1 = bound_lat_lng1.replace(/[()]/g, "");
496
497
                                bound_lat_lng2 = String(results[0].geometry.viewport.getNorthEast());
498
                                bound_lat_lng2 = bound_lat_lng2.replace(/[()]/g, "");
499
                                bound_lat_lng2 = bound_lat_lng1 + "," + bound_lat_lng2;
500
                                bound_lat_lng = bound_lat_lng2.split(',');
501
                            }
502
                            else {
503
                                bound_lat_lng = String(results[0].geometry.bounds);
504
505
                                bound_lat_lng = bound_lat_lng.replace(/[()]/g, "");
506
507
                                bound_lat_lng = bound_lat_lng.split(',');
508
                            }
509
510
                            bound_lat_lng = bound_lat_lng.map(function(x){return x.replace(" ", '');});// remove spaces from lat/lon
511
512
                            strictBounds = new google.maps.LatLngBounds(
513
                                new google.maps.LatLng(bound_lat_lng[0], bound_lat_lng[1]),
514
                                new google.maps.LatLng(bound_lat_lng[2], bound_lat_lng[3])
515
                            );
516
517
                        } else {
518
                            alert("<?php _e('Geocode was not successful for the following reason:','geodirectory');?> " + status);
519
                        }
520
                    });
521
522
523
                var dummy_post_index = 1;
524
                function geodir_autoinstall(obj, id, nonce, posttype) {
525
526
                    var active_tab = jQuery(obj).closest('form').find('dl dd.gd-tab-active').attr('id');
527
528
                    var total_dummy_post_count = jQuery('#sub_' + active_tab).find('.selected_sample_data').val();
529
530
                    if (id == 'geodir_dummy_delete') {
531
                        if (confirm('<?php _e('Are you sure you want to delete dummy data?' , 'geodirectory'); ?>')) {
532
                            jQuery('#sub_' + active_tab).find('.geodir_auto_install').hide();
533
                            jQuery('#sub_' + active_tab).find('.geodir_show_progress').show();
534
                            jQuery.post('<?php echo geodir_get_ajax_url(); ?>&geodir_autofill=' + id + '&posttype=' + posttype + '&_wpnonce=' + nonce,
535
                                function (data) {
536
                                    window.location.href = jQuery('#' + id).attr('redirect_to') + active_tab;
537
                                });
538
                            return true;
539
                        } else {
540
                            return false;
541
                        }
542
                    }
543
                    else {
544
545
                        jQuery('#sub_' + active_tab).find('.geodir_auto_install').hide();
546
                        jQuery('#sub_' + active_tab).find('.geodir_show_progress').show();
547
                        jQuery.post('<?php echo geodir_get_ajax_url(); ?>&geodir_autofill=' + id + '&posttype=' + posttype + '&insert_dummy_post_index=' + dummy_post_index + '&city_bound_lat1=' + bound_lat_lng[0] + '&city_bound_lng1=' + bound_lat_lng[1] + '&city_bound_lat2=' + bound_lat_lng[2] + '&city_bound_lng2=' + bound_lat_lng[3] + '&_wpnonce=' + nonce,
548
                            function (data) {
549
550
                                jQuery(obj).closest('form').find('.dummy_post_inserted').html('<?php _e('Dummy post(s) inserted:','geodirectory');?> ' + dummy_post_index + ' <?php _e('of' ,'geodirectory'); ?> ' + total_dummy_post_count + '');
551
                                dummy_post_index++;
552
                                if (dummy_post_index <= total_dummy_post_count)
553
                                    geodir_autoinstall(obj, id, nonce, posttype);
554
                                else {
555
                                    window.location.href = jQuery('#' + id).attr('redirect_to') + active_tab;
556
                                }
557
558
                            });
559
                    }
560
561
                }
562
            </script>
563
        <?php
564
        }
565 1
    }
566
}
567
568
/**
569
 * Inserts GeoDirectory dummy posts.
570
 *
571
 * @since 1.0.0
572
 * @package GeoDirectory
573
 * @global object $wpdb WordPress Database object.
574
 * @global object $current_user Current user object.
575
 */
576
function geodir_insert_dummy_posts()
577
{
578
    geodir_default_taxonomies();
579
580
    ini_set('max_execution_time', 999999); //300 seconds = 5 minutes
581
582
    global $wpdb, $current_user;
583
584
    /**
585
     * Contains dummy post content.
586
     *
587
     * @since 1.0.0
588
     * @package GeoDirectory
589
     */
590
    include_once('place_dummy_post.php');
591
592
}
593
594
/**
595
 * Deletes GeoDirectory dummy data.
596
 *
597
 * @since 1.0.0
598
 * @package GeoDirectory
599
 * @global object $wpdb WordPress Database object.
600
 * @global string $plugin_prefix Geodirectory plugin table prefix.
601
 */
602
function geodir_delete_dummy_posts()
603
{
604 2
    global $wpdb, $plugin_prefix;
605
606
607 2
    $post_ids = $wpdb->get_results("SELECT post_id FROM " . $plugin_prefix . "gd_place_detail WHERE post_dummy='1'");
608
609
610 2
    foreach ($post_ids as $post_ids_obj) {
611 2
        wp_delete_post($post_ids_obj->post_id);
612 2
    }
613
614
    //double check posts are deleted
615 2
    $wpdb->get_results("DELETE FROM " . $plugin_prefix . "gd_place_detail WHERE post_dummy='1'");
616 2
}
617
618
/**
619
 * Default taxonomies
620
 *
621
 * Adds the default terms for taxonomies - placecategory. Modify at your own risk.
622
 * 
623
 * @since 1.0.0
624
 * @package GeoDirectory
625
 * @global object $wpdb WordPress Database object.
626
 * @global string $dummy_image_path The dummy image path.
627
 */
628
function geodir_default_taxonomies() {
629 1
    global $wpdb, $dummy_image_path;
630
631 1
    $category_array = array('Attractions', 'Hotels', 'Restaurants', 'Food Nightlife', 'Festival', 'Videos', 'Feature');
632
633 1
    $last_catid = '';
0 ignored issues
show
Unused Code introduced by
$last_catid 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...
634
635 1
    $uploads = wp_upload_dir(); // Array of key => value pairs
636
637 1
    for ($i = 0; $i < count($category_array); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
638 1
        $parent_catid = 0;
639 1
        if (is_array($category_array[$i])) {
640
            $cat_name_arr = $category_array[$i];
641
            for ($j = 0; $j < count($cat_name_arr); $j++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
642
                $catname = $cat_name_arr[$j];
643
644
                if (!term_exists($catname, 'gd_placecategory')) {
645
                    $last_catid = wp_insert_term($catname, 'gd_placecategory', $args = array('parent' => $parent_catid));
646
647
                    if ($j == 0) {
648
                        $parent_catid = $last_catid;
649
                    }
650
651
652
                    if (geodir_dummy_folder_exists())
653
                        $dummy_image_url = geodir_plugin_url() . "/geodirectory-admin/dummy/cat_icon";
654
                    else
655
                        $dummy_image_url = 'http://www.wpgeodirectory.com/dummy/cat_icon';
656
657
                    $dummy_image_url = apply_filters('place_dummy_cat_image_url', $dummy_image_url);
658
659
                    $catname = str_replace(' ', '_', $catname);
660
                    $uploaded = (array)fetch_remote_file("$dummy_image_url/" . $catname . ".png");
661
662
                    if (empty($uploaded['error'])) {
663
                        $new_path = $uploaded['file'];
664
                        $new_url = $uploaded['url'];
665
                    }
666
667
                    $wp_filetype = wp_check_filetype(basename($new_path), null);
0 ignored issues
show
Bug introduced by
The variable $new_path 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...
668
669
                    $attachment = array(
670
                        'guid' => $uploads['baseurl'] . '/' . basename($new_path),
671
                        'post_mime_type' => $wp_filetype['type'],
672
                        'post_title' => preg_replace('/\.[^.]+$/', '', basename($new_path)),
673
                        'post_content' => '',
674
                        'post_status' => 'inherit'
675
                    );
676
                    $attach_id = wp_insert_attachment($attachment, $new_path);
677
678
                    // you must first include the image.php file
679
                    // for the function wp_generate_attachment_metadata() to work
680
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
681
                    $attach_data = wp_generate_attachment_metadata($attach_id, $new_path);
682
                    wp_update_attachment_metadata($attach_id, $attach_data);
683
684 View Code Duplication
                    if (!get_tax_meta($last_catid['term_id'], 'ct_cat_icon', false, 'gd_place')) {
685
                        update_tax_meta($last_catid['term_id'], 'ct_cat_icon', array('id' => 'icon', 'src' => $new_url), 'gd_place');
0 ignored issues
show
Bug introduced by
The variable $new_url 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...
686
                    }
687
                }
688
            }
689
690
        } else {
691 1
            $catname = $category_array[$i];
692
693 1
            if (!term_exists($catname, 'gd_placecategory')) {
694
                $last_catid = wp_insert_term($catname, 'gd_placecategory');
695
696
                if (geodir_dummy_folder_exists())
697
                    $dummy_image_url = geodir_plugin_url() . "/geodirectory-admin/dummy/cat_icon";
698
                else
699
                    $dummy_image_url = 'http://www.wpgeodirectory.com/dummy/cat_icon';
700
701
                $dummy_image_url = apply_filters('place_dummy_cat_image_url', $dummy_image_url);
702
703
                $catname = str_replace(' ', '_', $catname);
704
                $uploaded = (array)fetch_remote_file("$dummy_image_url/" . $catname . ".png");
705
706
                if (empty($uploaded['error'])) {
707
                    $new_path = $uploaded['file'];
708
                    $new_url = $uploaded['url'];
709
                }
710
711
                $wp_filetype = wp_check_filetype(basename($new_path), null);
712
713
                $attachment = array(
714
                    'guid' => $uploads['baseurl'] . '/' . basename($new_path),
715
                    'post_mime_type' => $wp_filetype['type'],
716
                    'post_title' => preg_replace('/\.[^.]+$/', '', basename($new_path)),
717
                    'post_content' => '',
718
                    'post_status' => 'inherit'
719
                );
720
721
                $attach_id = wp_insert_attachment($attachment, $new_path);
722
723
724
                // you must first include the image.php file
725
                // for the function wp_generate_attachment_metadata() to work
726
                require_once(ABSPATH . 'wp-admin/includes/image.php');
727
                $attach_data = wp_generate_attachment_metadata($attach_id, $new_path);
728
                wp_update_attachment_metadata($attach_id, $attach_data);
729
730 View Code Duplication
                if (!get_tax_meta($last_catid['term_id'], 'ct_cat_icon', false, 'gd_place')) {
731
                    update_tax_meta($last_catid['term_id'], 'ct_cat_icon', array('id' => $attach_id, 'src' => $new_url), 'gd_place');
732
                }
733
            }
734
        }
735
736 1
    }
737 1
}
738
739
/**
740
 * Update options
741
 *
742
 * Updates the options on the geodirectory settings pages. Returns true if saved.
743
 *
744
 * @since 1.0.0
745
 * @package GeoDirectory
746
 * @param array $options The option array.
747
 * @param bool $dummy Is this dummy settings? Default: false.
748
 * @return bool Returns true if saved.
749
 */
750
function geodir_update_options($options, $dummy = false) {
751 1
    if ((!isset($_POST) || !$_POST) && !$dummy) return false;
752
753 1
    foreach ($options as $value) {
754 1
        if ($dummy && isset($value['std']))
755 1
            $_POST[$value['id']] = $value['std'];
756
757
758 1
        if (isset($value['type']) && $value['type'] == 'checkbox') :
759
760 1 View Code Duplication
            if (isset($value['id']) && isset($_POST[$value['id']])) {
761 1
                update_option($value['id'], $_POST[$value['id']]);
762 1
            } else {
763
                update_option($value['id'], 0);
764
            }
765
766 1
        elseif (isset($value['type']) && $value['type'] == 'image_width') :
767
768
            if (isset($value['id']) && isset($_POST[$value['id'] . '_width'])) {
769
                update_option($value['id'] . '_width', $_POST[$value['id'] . '_width']);
770
                update_option($value['id'] . '_height', $_POST[$value['id'] . '_height']);
771 View Code Duplication
                if (isset($_POST[$value['id'] . '_crop'])) :
772
                    update_option($value['id'] . '_crop', 1);
773
                else :
774
                    update_option($value['id'] . '_crop', 0);
775
                endif;
776 View Code Duplication
            } else {
777
                update_option($value['id'] . '_width', $value['std']);
778
                update_option($value['id'] . '_height', $value['std']);
779
                update_option($value['id'] . '_crop', 1);
780
            }
781
782 1
        elseif (isset($value['type']) && $value['type'] == 'map') :
783 1
            $post_types = array();
784 1
            $categories = array();
785
786 1
            if (!empty($_POST['home_map_post_types'])) :
787
                foreach ($_POST['home_map_post_types'] as $post_type) :
788
                    $post_types[] = $post_type;
789
                endforeach;
790
            endif;
791
792 1
            update_option('geodir_exclude_post_type_on_map', $post_types);
793
794 1
            if (!empty($_POST['post_category'])) :
795
                foreach ($_POST['post_category'] as $texonomy => $cat_arr) :
796
                    $categories[$texonomy] = array();
797
                    foreach ($cat_arr as $category) :
798
                        $categories[$texonomy][] = $category;
799
                    endforeach;
800
                    $categories[$texonomy] = !empty($categories[$texonomy]) ? array_unique($categories[$texonomy]) : array();
801
                endforeach;
802
            endif;
803 1
            update_option('geodir_exclude_cat_on_map', $categories);
804 1
            update_option('geodir_exclude_cat_on_map_upgrade', 1);
805 1
        elseif (isset($value['type']) && $value['type'] == 'map_default_settings') :
806
807
808 1
            if (!empty($_POST['geodir_default_map_language'])):
809
                update_option('geodir_default_map_language', $_POST['geodir_default_map_language']);
810
            endif;
811
812
813 1
            if (!empty($_POST['geodir_default_map_search_pt'])):
814
                update_option('geodir_default_map_search_pt', $_POST['geodir_default_map_search_pt']);
815
            endif;
816
817
818 1
        elseif (isset($value['type']) && $value['type'] == 'file') :
819
820
821 1
            if (isset($_POST[$value['id'] . '_remove']) && $_POST[$value['id'] . '_remove']) {// if remove is set then remove the file
822
823 View Code Duplication
                if (get_option($value['id'])) {
824
                    $image_name_arr = explode('/', get_option($value['id']));
825
                    $noimg_name = end($image_name_arr);
826
                    $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...
827
                    if (file_exists($img_path))
828
                        unlink($img_path);
829
                }
830
831
                update_option($value['id'], '');
832
            }
833
834 1
            $uploadedfile = isset($_FILES[$value['id']]) ? $_FILES[$value['id']] : '';
835 1
            $filename = isset($_FILES[$value['id']]['name']) ? $_FILES[$value['id']]['name'] : '';
836
837 1
            if (!empty($filename)):
838
                $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...
839
                $uplaods = array();
840
841
                foreach ($uploadedfile as $key => $uplaod):
842
                    if ($key == 'name'):
843
                        $uplaods[$key] = $filename;
844
                    else :
845
                        $uplaods[$key] = $uplaod;
846
                    endif;
847
                endforeach;
848
849
                $uploads = wp_upload_dir();
850
851 View Code Duplication
                if (get_option($value['id'])) {
852
                    $image_name_arr = explode('/', get_option($value['id']));
853
                    $noimg_name = end($image_name_arr);
854
                    $img_path = $uploads['path'] . '/' . $noimg_name;
855
                    if (file_exists($img_path))
856
                        unlink($img_path);
857
                }
858
859
                $upload_overrides = array('test_form' => false);
860
                $movefile = wp_handle_upload($uplaods, $upload_overrides);
861
862
                update_option($value['id'], $movefile['url']);
863
864
            endif;
865
866 1
            if (!get_option($value['id']) && isset($value['value'])):
867
                update_option($value['id'], $value['value']);
868
            endif;
869
870
871 1
        else :
872
            // same menu setting per theme.
873 1
            if (isset($value['id']) && $value['id'] == 'geodir_theme_location_nav' && isset($_POST[$value['id']])) {
874 1
                $theme = wp_get_theme();
875 1
                update_option('geodir_theme_location_nav_' . $theme->name, $_POST[$value['id']]);
876 1
            }
877
878 1 View Code Duplication
            if (isset($value['id']) && isset($_POST[$value['id']])) {
879 1
                update_option($value['id'], $_POST[$value['id']]);
880 1
            } else {
881 1
                delete_option($value['id']);
882
            }
883
884
        endif;
885 1
    }
886
    if ($dummy)
887 1
        $_POST = array();
888 1
    return true;
889
890
}
891
892
/**
893
 * create custom fields for place.
894
 *
895
 * @since 1.0.0
896
 * @package GeoDirectory
897
 * @param array $tabs {
898
 *    Attributes of the tabs array.
899
 *
900
 *    @type array $general_settings {
901
 *        Attributes of general settings.
902
 *
903
 *        @type string $label Default "General".
904
 *
905
 *    }
906
 *    @type array $design_settings {
907
 *        Attributes of design settings.
908
 *
909
 *        @type string $label Default "Design".
910
 *
911
 *    }
912
 *    @type array $permalink_settings {
913
 *        Attributes of permalink settings.
914
 *
915
 *        @type string $label Default "Permalinks".
916
 *
917
 *    }
918
 *    @type array $notifications_settings {
919
 *        Attributes of notifications settings.
920
 *
921
 *        @type string $label Default "Notifications".
922
 *
923
 *    }
924
 *    @type array $default_location_settings {
925
 *        Attributes of default location settings.
926
 *
927
 *        @type string $label Default "Set Default Location".
928
 *
929
 *    }
930
 *
931
 * }
932
 * @return array Modified tabs array.
933
 */
934
function places_custom_fields_tab($tabs)
935
{
936
937
    $geodir_post_types = get_option('geodir_post_types');
938
939
    if (!empty($geodir_post_types)) {
940
941
        foreach ($geodir_post_types as $geodir_post_type => $geodir_posttype_info):
942
943
            $listing_slug = $geodir_posttype_info['labels']['singular_name'];
944
945
            $tabs[$geodir_post_type . '_fields_settings'] = array(
946
                'label' => __(ucfirst($listing_slug) . ' Settings', 'geodirectory'),
947
                'subtabs' => array(
948
                    array('subtab' => 'custom_fields',
949
                        'label' => __('Custom Fields', 'geodirectory'),
950
                        'request' => array('listing_type' => $geodir_post_type)),
951
                    array('subtab' => 'sorting_options',
952
                        'label' => __('Sorting Options', 'geodirectory'),
953
                        'request' => array('listing_type' => $geodir_post_type)),
954
                ),
955
                'tab_index' => 9,
956
                'request' => array('listing_type' => $geodir_post_type)
957
            );
958
959
        endforeach;
960
961
    }
962
963
    return $tabs;
964
}
965
966
967
/**
968
 * Adds GD Tools settings menu to GeoDirectory settings.
969
 *
970
 * Can be found here. WP Admin -> Geodirectory -> GD Tools.
971
 *
972
 * @since 1.0.0
973
 * @package GeoDirectory
974
 * @param array $tabs Tab menu array {@see places_custom_fields_tab()}.
975
 * @return array Modified tab menu array.
976
 */
977
function geodir_tools_setting_tab($tabs)
978
{
979
    $tabs['tools_settings'] = array('label' => __('GD Tools', 'geodirectory'));
980
    return $tabs;
981
}
982
983
/**
984
 * Adds Theme Compatibility menu item to GeoDirectory settings page.
985
 *
986
 * Can be found here. WP Admin -> Geodirectory -> Theme Compatibility.
987
 *
988
 * @since 1.0.0
989
 * @package GeoDirectory
990
 * @param array $tabs Tab menu array {@see places_custom_fields_tab()}.
991
 * @return array Modified tab menu array.
992
 */
993
function geodir_compatibility_setting_tab($tabs)
994
{
995
    $tabs['compatibility_settings'] = array('label' => __('Theme Compatibility', 'geodirectory'));
996
    return $tabs;
997
}
998
999
1000
/**
1001
 * Adds Extend Geodirectory menu item to GeoDirectory settings page.
1002
 *
1003
 * Can be found here. WP Admin -> Geodirectory -> Extend Geodirectory.
1004
 *
1005
 * @since 1.0.0
1006
 * @package GeoDirectory
1007
 * @param array $tabs Tab menu array {@see places_custom_fields_tab()}.
1008
 * @return array Modified tab menu array.
1009
 */
1010
function geodir_extend_geodirectory_setting_tab($tabs)
1011
{
1012
    $tabs['extend_geodirectory_settings'] = array('label' => __('Extend Geodirectory', 'geodirectory'). ' <i class="fa fa-plug"></i>', 'url' => 'http://wpgeodirectory.com', 'target' => '_blank');
1013
    return $tabs;
1014
}
1015
1016
1017
if (!function_exists('geodir_edit_post_columns')) {
1018
    /**
1019
     * Modify admin post listing page columns.
1020
     *
1021
     * @since 1.0.0
1022
     * @package GeoDirectory
1023
     * @param array $columns The column array.
1024
     * @return array Altered column array.
1025
     */
1026
    function geodir_edit_post_columns($columns)
1027
    {
1028
1029
        $new_columns = array('location' => __('Location (ID)', 'geodirectory'),
1030
            'categorys' => __('Categories', 'geodirectory'));
1031
1032
        if (($offset = array_search('author', array_keys($columns))) === false) // if the key doesn't exist
1033
        {
1034
            $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...
1035
            $offset = count($columns); // or should we append $array with $data? lets pick this one...
1036
        }
1037
1038
        $columns = array_merge(array_slice($columns, 0, $offset), $new_columns, array_slice($columns, $offset));
1039
1040
        $columns = array_merge($columns, array('expire' => __('Expires', 'geodirectory')));
1041
1042
        return $columns;
1043
    }
1044
}
1045
1046
1047
if (!function_exists('geodir_manage_post_columns')) {
1048
    /**
1049
     * Adds content to our custom post listing page columns.
1050
     *
1051
     * @since 1.0.0
1052
     * @package GeoDirectory
1053
     * @global object $wpdb WordPress Database object.
1054
     * @global object $post WordPress Post object.
1055
     * @param string $column The column name.
1056
     * @param int $post_id The post ID.
1057
     */
1058
    function geodir_manage_post_columns($column, $post_id)
1059
    {
1060
        global $post, $wpdb;
1061
1062
        switch ($column):
1063
            /* If displaying the 'city' column. */
1064
            case 'location' :
1065
                $location_id = geodir_get_post_meta($post->ID, 'post_location_id', true);
1066
                $location = geodir_get_location($location_id);
1067
                /* If no city is found, output a default message. */
1068
                if (empty($location)) {
1069
                    _e('Unknown', 'geodirectory');
1070
                } else {
1071
                    /* If there is a city id, append 'city name' to the text string. */
1072
                    $add_location_id = $location_id > 0 ? ' (' . $location_id . ')' : '';
1073
                    echo(__($location->country, 'geodirectory') . '-' . $location->region . '-' . $location->city . $add_location_id);
1074
                }
1075
                break;
1076
1077
            /* If displaying the 'expire' column. */
1078
            case 'expire' :
1079
                $expire_date = geodir_get_post_meta($post->ID, 'expire_date', true);
1080
                $d1 = $expire_date; // get expire_date
1081
                $d2 = date('Y-m-d'); // get current date
1082
                $state = __('days left', 'geodirectory');
1083
                $date_diff_text = '';
1084
                $expire_class = 'expire_left';
1085
                if ($expire_date != 'Never') {
1086
                    if (strtotime($d1) < strtotime($d2)) {
1087
                        $state = __('days overdue', 'geodirectory');
1088
                        $expire_class = 'expire_over';
1089
                    }
1090
                    $date_diff = round(abs(strtotime($d1) - strtotime($d2)) / 86400); // get the difference in days
1091
                    $date_diff_text = '<br /><span class="' . $expire_class . '">(' . $date_diff . ' ' . $state . ')</span>';
1092
                }
1093
                /* If no expire_date is found, output a default message. */
1094
                if (empty($expire_date))
1095
                    echo __('Unknown', 'geodirectory');
1096
                /* If there is a expire_date, append 'days left' to the text string. */
1097
                else
1098
                    echo $expire_date . $date_diff_text;
1099
                break;
1100
1101
            /* If displaying the 'categorys' column. */
1102
            case 'categorys' :
1103
1104
                /* Get the categorys for the post. */
1105
1106
1107
                $terms = wp_get_object_terms($post_id, get_object_taxonomies($post));
1108
1109
                /* If terms were found. */
1110
                if (!empty($terms)) {
1111
                    $out = array();
1112
                    /* Loop through each term, linking to the 'edit posts' page for the specific term. */
1113
                    foreach ($terms as $term) {
1114
                        if (!strstr($term->taxonomy, 'tag')) {
1115
                            $out[] = sprintf('<a href="%s">%s</a>',
1116
                                esc_url(add_query_arg(array('post_type' => $post->post_type, $term->taxonomy => $term->slug), 'edit.php')),
1117
                                esc_html(sanitize_term_field('name', $term->name, $term->term_id, $term->taxonomy, 'display'))
1118
                            );
1119
                        }
1120
                    }
1121
                    /* Join the terms, separating them with a comma. */
1122
                    echo(join(', ', $out));
1123
                } /* If no terms were found, output a default message. */
1124
                else {
1125
                    _e('No Categories', 'geodirectory');
1126
                }
1127
                break;
1128
1129
        endswitch;
1130
    }
1131
}
1132
1133
1134
if (!function_exists('geodir_post_sortable_columns')) {
1135
    /**
1136
     * Makes admin post listing page columns sortable.
1137
     *
1138
     * @since 1.0.0
1139
     * @package GeoDirectory
1140
     * @param array $columns The column array.
1141
     * @return array Altered column array.
1142
     */
1143
    function geodir_post_sortable_columns($columns)
1144
    {
1145
1146
        $columns['expire'] = 'expire';
1147
1148
        return $columns;
1149
    }
1150
}
1151
1152
/**
1153
 * Saves listing data from request variable to database.
1154
 *
1155
 * @since 1.0.0
1156
 * @package GeoDirectory
1157
 * @global object $wpdb WordPress Database object.
1158
 * @global object $current_user Current user object.
1159
 * @global object $post WordPress Post object.
1160
 * @param int $post_id The post ID.
1161
 */
1162
function geodir_post_information_save($post_id, $post) {
1163 2
    global $wpdb, $current_user;
1164
1165 2 View Code Duplication
    if (isset($post->post_type) && ($post->post_type=='nav_menu_item' || $post->post_type=='page' || $post->post_type=='post')) {
1166 2
        return;
1167
    }
1168
1169
    $geodir_posttypes = geodir_get_posttypes();
1170
1171
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
1172
        return;
1173
1174
    if (!wp_is_post_revision($post_id) && isset($post->post_type) && in_array($post->post_type, $geodir_posttypes)) {
1175
        if (isset($_REQUEST['_status']))
1176
            geodir_change_post_status($post_id, $_REQUEST['_status']);
1177
1178
        if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'trash' || $_REQUEST['action'] == 'untrash'))
1179
            return;
1180
1181 View Code Duplication
        if (!isset($_POST['geodir_post_info_noncename']) || !wp_verify_nonce($_POST['geodir_post_info_noncename'], plugin_basename(__FILE__)))
1182
            return;
1183
1184 View Code Duplication
        if (!isset($_POST['geodir_post_attachments_noncename']) || !wp_verify_nonce($_POST['geodir_post_attachments_noncename'], plugin_basename(__FILE__)))
1185
            return;
1186
1187
        geodir_save_listing($_REQUEST);
1188
    }
1189
}
1190
1191
/**
1192
 * Admin fields
1193
 *
1194
 * Loops though the geodirectory options array and outputs each field.
1195
 *
1196
 * @since 1.0.0
1197
 * @package GeoDirectory
1198
 * @global object $geodirectory GeoDirectory plugin object.
1199
 * @global object $sitepress Sitepress WPML object.
1200
 * @param array $options The options array.
1201
 */
1202
function geodir_admin_fields($options)
1203
{
1204 1
    global $geodirectory;
1205
1206 1
    $first_title = true;
1207 1
    $tab_id = '';
1208 1
    $i = 0;
1209 1
    foreach ($options as $value) :
1210 1
        if (!isset($value['name'])) $value['name'] = '';
1211 1
        if (!isset($value['class'])) $value['class'] = '';
1212 1
        if (!isset($value['css'])) $value['css'] = '';
1213 1
        if (!isset($value['std'])) $value['std'] = '';
1214 1
        $desc = '';
1215 1
        switch ($value['type']) :
1216 1
            case 'dummy_installer':
1217 1
                $post_type = isset($value['post_type']) ? $value['post_type'] : 'gd_place';
1218 1
                geodir_autoinstall_admin_header($post_type);
1219 1
                break;
1220 1
            case 'title':
1221
1222 1
                if ($i == 0) {
1223 1
                    echo '<dl id="geodir_oiption_tabs" class="gd-tab-head"></dl>';
1224 1
                    echo '<div class="inner_content_tab_main">';
1225 1
                }
1226
1227 1
                $i++;
1228
1229 1
                if (isset($value['id']) && $value['id'])
1230 1
                    $tab_id = $value['id'];
1231
1232 1 View Code Duplication
                if (isset($value['desc']) && $value['desc'])
1233 1
                    $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...
1234
1235 1
                if (isset($value['name']) && $value['name']) {
1236 1
                    if ($first_title === true) {
1237 1
                        $first_title = false;
1238 1
                    } else {
1239 1
                        echo '</div>';
1240
                    }
1241 1
                    echo '<dd id="' . trim($tab_id) . '" class="geodir_option_tabs" ><a href="javascript:void(0);">' . $value['name'] . '</a></dd>';
1242
1243 1
                    echo '<div id="sub_' . trim($tab_id) . '" class="gd-content-heading" style=" margin-bottom:10px;" >';
1244 1
                }
1245
1246
                /**
1247
                 * Called after a GeoDirectory settings title is output in the GD settings page.
1248
                 *
1249
                 * The action is called dynamically geodir_settings_$value['id'].
1250
                 *
1251
                 * @since 1.0.0
1252
                 */
1253 1
                do_action('geodir_settings_' . sanitize_title($value['id']));
1254 1
                break;
1255
1256 1
            case 'no_tabs':
1257
1258 1
                echo '<div class="inner_content_tab_main">';
1259 1
                echo '<div id="sub_' . trim($tab_id) . '" class="gd-content-heading" style=" margin-bottom:10px;" >';
1260
1261 1
                break;
1262
1263 1
            case 'sectionstart':
1264 1 View Code Duplication
                if (isset($value['desc']) && $value['desc'])
1265 1
                    $desc = '<span style=" text-transform:none;"> - ' . $value['desc'] . '</span>';
1266 1 View Code Duplication
                if (isset($value['name']) && $value['name'])
1267 1
                    echo '<h3>' . $value['name'] . $desc . '</h3>';
1268
                /**
1269
                 * Called after a GeoDirectory settings sectionstart is output in the GD settings page.
1270
                 *
1271
                 * The action is called dynamically geodir_settings_$value['id']_start.
1272
                 *
1273
                 * @since 1.0.0
1274
                 */
1275 1 View Code Duplication
                if (isset($value['id']) && $value['id']) do_action('geodir_settings_' . sanitize_title($value['id']) . '_start');
1276 1
                echo '<table class="form-table">' . "\n\n";
1277
1278 1
                break;
1279 1
            case 'sectionend':
1280
                /**
1281
                 * Called before a GeoDirectory settings sectionend is output in the GD settings page.
1282
                 *
1283
                 * The action is called dynamically geodir_settings_$value['id']_end.
1284
                 *
1285
                 * @since 1.0.0
1286
                 */
1287 1 View Code Duplication
                if (isset($value['id']) && $value['id']) do_action('geodir_settings_' . sanitize_title($value['id']) . '_end');
1288 1
                echo '</table>';
1289
                /**
1290
                 * Called after a GeoDirectory settings sectionend is output in the GD settings page.
1291
                 *
1292
                 * The action is called dynamically geodir_settings_$value['id']_end.
1293
                 *
1294
                 * @since 1.0.0
1295
                 */
1296 1 View Code Duplication
                if (isset($value['id']) && $value['id']) do_action('geodir_settings_' . sanitize_title($value['id']) . '_after');
1297 1
                break;
1298 1 View Code Duplication
            case 'text':
1299
                ?>
1300
                <tr valign="top">
1301
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1302
                <td class="forminp"><input name="<?php echo esc_attr($value['id']); ?>"
1303
                                           id="<?php echo esc_attr($value['id']); ?>"
1304
                                           type="<?php echo esc_attr($value['type']); ?>"
1305
                                           <?php if(isset($value['placeholder'])){?>placeholder="<?php echo esc_attr($value['placeholder']); ?>"<?php }?>
1306
                                           style=" <?php echo esc_attr($value['css']); ?>"
1307
                                           value="<?php if (get_option($value['id']) !== false && get_option($value['id']) !== null) {
1308 1
                                               echo esc_attr(stripslashes(get_option($value['id'])));
1309 1
                                           } else {
1310
                                               echo esc_attr($value['std']);
1311
                                           } ?>"/> <span class="description"><?php echo $value['desc']; ?></span></td>
1312
                </tr><?php
1313 1
                break;
1314
1315 1 View Code Duplication
            case 'password':
1316
                ?>
1317
                <tr valign="top">
1318
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1319
                <td class="forminp"><input name="<?php echo esc_attr($value['id']); ?>"
1320
                                           id="<?php echo esc_attr($value['id']); ?>"
1321
                                           type="<?php echo esc_attr($value['type']); ?>"
1322
                                           <?php if(isset($value['placeholder'])){?>placeholder="<?php echo esc_attr($value['placeholder']); ?>"<?php }?>
1323
                                           style="<?php echo esc_attr($value['css']); ?>"
1324
                                           value="<?php if (get_option($value['id']) !== false && get_option($value['id']) !== null) {
1325 1
                                               echo esc_attr(stripslashes(get_option($value['id'])));
1326 1
                                           } else {
1327
                                               echo esc_attr($value['std']);
1328
                                           } ?>"/> <span class="description"><?php echo $value['desc']; ?></span></td>
1329
                </tr><?php
1330 1
                break;
1331
1332 1
            case 'html_content':
1333
                ?>
1334
                <tr valign="top">
1335
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1336
                <td class="forminp"><span class="description"><?php echo $value['desc']; ?></span></td>
1337
                </tr><?php
1338 1
                break;
1339
1340 1
            case 'color' :
1341
                ?>
1342
                <tr valign="top">
1343
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1344
                <td class="forminp"><input name="<?php echo esc_attr($value['id']); ?>"
1345
                                           id="<?php echo esc_attr($value['id']); ?>" type="text"
1346
                                           style="<?php echo esc_attr($value['css']); ?>"
1347
                                           value="<?php if (get_option($value['id']) !== false && get_option($value['id']) !== null) {
1348 1
                                               echo esc_attr(stripslashes(get_option($value['id'])));
1349 1
                                           } else {
1350
                                               echo esc_attr($value['std']);
1351
                                           } ?>" class="colorpick"/> <span
1352
                        class="description"><?php echo $value['desc']; ?></span>
1353
1354
                    <div id="colorPickerDiv_<?php echo esc_attr($value['id']); ?>" class="colorpickdiv"
1355
                         style="z-index: 100;background:#eee;border:1px solid #ccc;position:absolute;display:none;"></div>
1356
                </td>
1357
                </tr><?php
1358 1
                break;
1359 1
            case 'image_width' :
1360
                ?>
1361
                <tr valign="top">
1362
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1363
                <td class="forminp">
1364
1365
                    <?php _e('Width', 'geodirectory'); ?> <input
1366
                        name="<?php echo esc_attr($value['id']); ?>_width"
1367
                        id="<?php echo esc_attr($value['id']); ?>_width" type="text" size="3"
1368
                        value="<?php if ($size = get_option($value['id'] . '_width')) echo stripslashes($size); else echo $value['std']; ?>"/>
1369
1370
                    <?php _e('Height', 'geodirectory'); ?> <input
1371
                        name="<?php echo esc_attr($value['id']); ?>_height"
1372
                        id="<?php echo esc_attr($value['id']); ?>_height" type="text" size="3"
1373
                        value="<?php if ($size = get_option($value['id'] . '_height')) echo stripslashes($size); else echo $value['std']; ?>"/>
1374
1375
                    <label><?php _e('Hard Crop', 'geodirectory'); ?> <input
1376
                            name="<?php echo esc_attr($value['id']); ?>_crop"
1377
                            id="<?php echo esc_attr($value['id']); ?>_crop"
1378
                            type="checkbox" <?php if (get_option($value['id'] . '_crop') != '') checked(get_option($value['id'] . '_crop'), 1); else checked(1); ?> /></label>
1379
1380
                    <span class="description"><?php echo $value['desc'] ?></span></td>
1381
                </tr><?php
1382
                break;
1383 1
            case 'select':
1384 1
                $option_value = get_option($value['id']);
1385 1
                $option_value = !empty($option_value) ? stripslashes_deep($option_value) : $option_value;
1386
                ?>
1387
                <tr valign="top">
1388
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1389
                <td class="forminp"><select name="<?php echo esc_attr($value['id']); ?>"
1390
                                            id="<?php echo esc_attr($value['id']); ?>"
1391
                                            style="<?php echo esc_attr($value['css']); ?>"
1392
                                            class="<?php if (isset($value['class'])) echo $value['class']; ?>"
1393
                                            option-ajaxchosen="false">
1394
                        <?php
1395 1
                        foreach ($value['options'] as $key => $val) {
1396 1
                            $geodir_select_value = '';
1397 1
                            if ($option_value != '') {
1398 1
                                if ($option_value != '' && $option_value == $key)
1399 1
                                    $geodir_select_value = ' selected="selected" ';
1400 1
                            } else {
1401 1
                                if ($value['std'] == $key)
1402 1
                                    $geodir_select_value = ' selected="selected" ';
1403
                            }
1404
                            ?>
1405
                            <option
1406
                                value="<?php echo esc_attr($key); ?>" <?php echo $geodir_select_value; ?> ><?php echo ucfirst($val) ?></option>
1407
                        <?php
1408 1
                        }
1409
                        ?>
1410
                    </select> <span class="description"><?php echo $value['desc'] ?></span>
1411
                </td>
1412
                </tr><?php
1413 1
                break;
1414
1415 1
            case 'multiselect':
1416 1
                $option_values = get_option($value['id']);
1417 1
                if ($option_values === '' && !empty($value['std']) && is_array($value['std'])) {
1418
                   $option_values = $value['std'];
1419
                }
1420 1
                $option_values = !empty($option_values) ? stripslashes_deep($option_values) : $option_values;
1421
                ?>
1422
                <tr valign="top">
1423
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1424
                <td class="forminp"><select multiple="multiple" name="<?php echo esc_attr($value['id']); ?>[]"
1425
                                            id="<?php echo esc_attr($value['id']); ?>"
1426
                                            style="<?php echo esc_attr($value['css']); ?>"
1427
                                            class="<?php if (isset($value['class'])) echo $value['class']; ?>"
1428
                                            data-placeholder="<?php if (isset($value['placeholder_text'])) echo $value['placeholder_text'];?>"
1429
                                            option-ajaxchosen="false">
1430
                        <?php
1431 1
                        foreach ($value['options'] as $key => $val) {
1432 1
                            if (strpos($key, 'optgroup_start-') === 0) {
1433
                                ?><optgroup label="<?php echo ucfirst($val); ?>"><?php
1434 1
                            } else if (strpos($key, 'optgroup_end-') === 0) {
1435
                                ?></optgroup><?php
1436
                            } else {
1437
                                ?>
1438
                                <option
1439
                                    value="<?php echo esc_attr($key); ?>" <?php selected(true, (is_array($option_values) && in_array($key, $option_values)));?>><?php echo ucfirst($val) ?></option>
1440
                            <?php
1441
                            }
1442 1
                        }
1443
                        ?>
1444
                    </select> <span class="description"><?php echo $value['desc'] ?></span>
1445
                </td>
1446
                </tr><?php
1447 1
                break;
1448 1
            case 'file':
1449
                ?>
1450
                <tr valign="top">
1451
                <th scope="row" class="titledesc"><?php echo $value['name']; ?></th>
1452
                <td class="forminp">
1453
                    <input type="file" name="<?php echo esc_attr($value['id']); ?>"
1454
                           id="<?php echo esc_attr($value['id']); ?>" style="<?php echo esc_attr($value['css']); ?>"
1455
                           class="<?php if (isset($value['class'])) echo $value['class']; ?>"/>
1456
                    <?php if (get_option($value['id'])) { ?>
1457
                        <input type="hidden" name="<?php echo esc_attr($value['id']); ?>_remove"
1458
                               id="<?php echo esc_attr($value['id']); ?>_remove" value="0">
1459
                        <span class="description"> <a
1460
                                href="<?php echo get_option($value['id']); ?>"
1461
                                target="_blank"><?php echo get_option($value['id']); ?></a> <i
1462
                                title="<?php _e('remove file (set to empty)', 'geodirectory'); ?>"
1463
                                onclick="jQuery('#<?php echo esc_attr($value['id']); ?>_remove').val('1'); jQuery( this ).parent().text('<?php _e('save to remove file', 'geodirectory'); ?>');"
1464
                                class="fa fa-times gd-remove-file"></i></span>
1465
1466
                    <?php } ?>
1467
                </td>
1468
                </tr><?php
1469 1
                break;
1470 1
            case 'map_default_settings' :
1471
                ?>
1472
1473
                <tr valign="top">
1474
                    <th class="titledesc" width="40%"><?php _e('Default map language', 'geodirectory');?></th>
1475
                    <td width="60%">
1476
                        <select name="geodir_default_map_language" style="width:60%">
1477
                            <?php
1478
                            $arr_map_langages = array(
1479 1
                                'ar' => __('ARABIC', 'geodirectory'),
1480 1
                                'eu' => __('BASQUE', 'geodirectory'),
1481 1
                                'bg' => __('BULGARIAN', 'geodirectory'),
1482 1
                                'bn' => __('BENGALI', 'geodirectory'),
1483 1
                                'ca' => __('CATALAN', 'geodirectory'),
1484 1
                                'cs' => __('CZECH', 'geodirectory'),
1485 1
                                'da' => __('DANISH', 'geodirectory'),
1486 1
                                'de' => __('GERMAN', 'geodirectory'),
1487 1
                                'el' => __('GREEK', 'geodirectory'),
1488 1
                                'en' => __('ENGLISH', 'geodirectory'),
1489 1
                                'en-AU' => __('ENGLISH (AUSTRALIAN)', 'geodirectory'),
1490 1
                                'en-GB' => __('ENGLISH (GREAT BRITAIN)', 'geodirectory'),
1491 1
                                'es' => __('SPANISH', 'geodirectory'),
1492 1
                                'eu' => __('BASQUE', 'geodirectory'),
1493 1
                                'fa' => __('FARSI', 'geodirectory'),
1494 1
                                'fi' => __('FINNISH', 'geodirectory'),
1495 1
                                'fil' => __('FILIPINO', 'geodirectory'),
1496 1
                                'fr' => __('FRENCH', 'geodirectory'),
1497 1
                                'gl' => __('GALICIAN', 'geodirectory'),
1498 1
                                'gu' => __('GUJARATI', 'geodirectory'),
1499 1
                                'hi' => __('HINDI', 'geodirectory'),
1500 1
                                'hr' => __('CROATIAN', 'geodirectory'),
1501 1
                                'hu' => __('HUNGARIAN', 'geodirectory'),
1502 1
                                'id' => __('INDONESIAN', 'geodirectory'),
1503 1
                                'it' => __('ITALIAN', 'geodirectory'),
1504 1
                                'iw' => __('HEBREW', 'geodirectory'),
1505 1
                                'ja' => __('JAPANESE', 'geodirectory'),
1506 1
                                'kn' => __('KANNADA', 'geodirectory'),
1507 1
                                'ko' => __('KOREAN', 'geodirectory'),
1508 1
                                'lt' => __('LITHUANIAN', 'geodirectory'),
1509 1
                                'lv' => __('LATVIAN', 'geodirectory'),
1510 1
                                'ml' => __('MALAYALAM', 'geodirectory'),
1511 1
                                'mr' => __('MARATHI', 'geodirectory'),
1512 1
                                'nl' => __('DUTCH', 'geodirectory'),
1513 1
                                'no' => __('NORWEGIAN', 'geodirectory'),
1514 1
                                'pl' => __('POLISH', 'geodirectory'),
1515 1
                                'pt' => __('PORTUGUESE', 'geodirectory'),
1516 1
                                'pt-BR' => __('PORTUGUESE (BRAZIL)', 'geodirectory'),
1517 1
                                'pt-PT' => __('PORTUGUESE (PORTUGAL)', 'geodirectory'),
1518 1
                                'ro' => __('ROMANIAN', 'geodirectory'),
1519 1
                                'ru' => __('RUSSIAN', 'geodirectory'),
1520 1
                                'ru' => __('RUSSIAN', 'geodirectory'),
1521 1
                                'sk' => __('SLOVAK', 'geodirectory'),
1522 1
                                'sl' => __('SLOVENIAN', 'geodirectory'),
1523 1
                                'sr' => __('SERBIAN', 'geodirectory'),
1524 1
                                'sv' => __('	SWEDISH', 'geodirectory'),
1525 1
                                'tl' => __('TAGALOG', 'geodirectory'),
1526 1
                                'ta' => __('TAMIL', 'geodirectory'),
1527 1
                                'te' => __('TELUGU', 'geodirectory'),
1528 1
                                'th' => __('THAI', 'geodirectory'),
1529 1
                                'tr' => __('TURKISH', 'geodirectory'),
1530 1
                                'uk' => __('UKRAINIAN', 'geodirectory'),
1531 1
                                'vi' => __('VIETNAMESE', 'geodirectory'),
1532 1
                                'zh-CN' => __('CHINESE (SIMPLIFIED)', 'geodirectory'),
1533 1
                                'zh-TW' => __('CHINESE (TRADITIONAL)', 'geodirectory'),
1534 1
                            );
1535 1
                            $geodir_default_map_language = get_option('geodir_default_map_language');
1536 1
                            if (empty($geodir_default_map_language))
1537 1
                                $geodir_default_map_language = 'en';
1538 1
                            foreach ($arr_map_langages as $language_key => $language_txt) {
1539 1
                                if (!empty($geodir_default_map_language) && $language_key == $geodir_default_map_language)
1540 1
                                    $geodir_default_language_selected = "selected='selected'";
1541
                                else
1542 1
                                    $geodir_default_language_selected = '';
1543
1544
                                ?>
1545
                                <option
1546
                                    value="<?php echo $language_key?>" <?php echo $geodir_default_language_selected; ?>><?php echo $language_txt; ?></option>
1547
1548
                            <?php }
1549
                            ?>
1550
                        </select>
1551
                    </td>
1552
                </tr>
1553
1554
                <tr valign="top">
1555
                    <th class="titledesc"
1556
                        width="40%"><?php _e('Default post type search on map', 'geodirectory');?></th>
1557
                    <td width="60%">
1558
                        <select name="geodir_default_map_search_pt" style="width:60%">
1559
                            <?php
1560 1
                            $post_types = geodir_get_posttypes('array');
1561 1
                            $geodir_default_map_search_pt = get_option('geodir_default_map_search_pt');
1562 1
                            if (empty($geodir_default_map_search_pt))
1563 1
                                $geodir_default_map_search_pt = 'gd_place';
1564 1
                            if (is_array($post_types)) {
1565 1
                                foreach ($post_types as $key => $post_types_obj) {
1566 1
                                    if (!empty($geodir_default_map_search_pt) && $key == $geodir_default_map_search_pt)
1567 1
                                        $geodir_search_pt_selected = "selected='selected'";
1568
                                    else
1569
                                        $geodir_search_pt_selected = '';
1570
1571
                                    ?>
1572
                                    <option
1573
                                        value="<?php echo $key?>" <?php echo $geodir_search_pt_selected; ?>><?php echo $post_types_obj['labels']['singular_name']; ?></option>
1574
1575
                                <?php }
1576
1577 1
                            }
1578
1579
                            ?>
1580
                        </select>
1581
                    </td>
1582
                </tr>
1583
1584
                <?php
1585 1
                break;
1586
1587 1
            case 'map':
1588
                ?>
1589
                <tr valign="top">
1590
                    <td class="forminp">
1591
                        <?php
1592 1
                        global $post_cat, $cat_display;
1593 1
                        $post_types = geodir_get_posttypes('object');
1594 1
                        $cat_display = 'checkbox';
1595 1
                        $gd_post_types = get_option('geodir_exclude_post_type_on_map');
1596 1
                        $gd_cats = get_option('geodir_exclude_cat_on_map');
1597 1
                        $gd_cats_upgrade = (int)get_option('geodir_exclude_cat_on_map_upgrade');
1598 1
                        $count = 1;
1599
                        ?>
1600
                        <table width="70%" class="widefat">
1601
                            <thead>
1602
                            <tr>
1603
                                <th><b><?php echo DESIGN_POST_TYPE_SNO; ?></b></th>
1604
                                <th><b><?php echo DESIGN_POST_TYPE; ?></b></th>
1605
                                <th><b><?php echo DESIGN_POST_TYPE_CAT; ?></b></th>
1606
                            </tr>
1607
                            <?php
1608 1
                            $gd_categs = $gd_cats;
1609 1
                            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...
1610 1
                                $checked = is_array($gd_post_types) && in_array($key, $gd_post_types) ? 'checked="checked"' : '';
1611 1
                                $gd_taxonomy = geodir_get_taxonomies($key);
1612 1 View Code Duplication
                                if ($gd_cats_upgrade) {
1613 1
                                    $gd_cat_taxonomy = isset($gd_taxonomy[0]) ? $gd_taxonomy[0] : '';
1614 1
                                    $gd_cats = isset($gd_categs[$gd_cat_taxonomy]) ? $gd_categs[$gd_cat_taxonomy] : array();
1615 1
                                    $gd_cats = !empty($gd_cats) && is_array($gd_cats) ? array_unique($gd_cats) : array();
1616 1
                                }
1617 1
                                $post_cat = implode(',', $gd_cats);
1618 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...
1619
                                ?>
1620
                                <tr>
1621
                                    <td valign="top" width="5%"><?php echo $count; ?></td>
1622
                                    <td valign="top" width="25%" id="td_post_types"><input type="checkbox"
1623
                                                                                           name="home_map_post_types[]"
1624
                                                                                           id="<?php echo esc_attr($value['id']); ?>"
1625
                                                                                           value="<?php echo $key; ?>"
1626
                                                                                           class="map_post_type" <?php echo $checked;?> />
1627
                                        <?php echo $post_types_obj->labels->singular_name; ?></td>
1628
                                    <td width="40%">
1629
                                        <div class="home_map_category" style="overflow:auto;width:200px;height:100px;"
1630
                                             id="<?php echo $key; ?>"><?php echo $gd_taxonomy_list; ?></div>
1631
                                    </td>
1632
                                </tr>
1633
                                <?php $count++; endforeach; ?>
1634
                            </thead>
1635
                        </table>
1636
                        <p><?php _e('Note: Tick respective post type or categories which you want to hide from home page map widget.', 'geodirectory')?></p>
1637
                    </td>
1638
                </tr>
1639
                <?php
1640 1
                break;
1641
1642 1
            case 'checkbox' :
1643
1644 1
                if (!isset($value['checkboxgroup']) || (isset($value['checkboxgroup']) && $value['checkboxgroup'] == 'start')) :
1645
                    ?>
1646
                    <tr valign="top">
1647
                    <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1648
                    <td class="forminp">
1649
                <?php
1650 1
                endif;
1651
1652
                ?>
1653
                <fieldset>
1654
                    <legend class="screen-reader-text"><span><?php echo $value['name'] ?></span></legend>
1655
                    <label for="<?php echo $value['id'] ?>">
1656
                        <input name="<?php echo esc_attr($value['id']); ?>" id="<?php echo esc_attr($value['id']); ?>"
1657
                               type="checkbox" value="1" <?php checked(get_option($value['id']), true); ?> />
1658
                        <?php echo $value['desc'] ?></label><br>
1659
                </fieldset>
1660
                <?php
1661
1662 1
                if (!isset($value['checkboxgroup']) || (isset($value['checkboxgroup']) && $value['checkboxgroup'] == 'end')) :
1663
                    ?>
1664
                    </td>
1665
                    </tr>
1666
                <?php
1667 1
                endif;
1668
1669 1
                break;
1670
1671 1
            case 'radio' :
1672
1673 1 View Code Duplication
                if (!isset($value['radiogroup']) || (isset($value['radiogroup']) && $value['radiogroup'] == 'start')) :
1674
                    ?>
1675
                    <tr valign="top">
1676
                    <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1677
                    <td class="forminp">
1678
                <?php
1679 1
                endif;
1680
1681
                ?>
1682
                <fieldset>
1683
                    <legend class="screen-reader-text"><span><?php echo $value['name'] ?></span></legend>
1684
                    <label for="<?php echo $value['id'];?>">
1685
                        <input name="<?php echo esc_attr($value['id']); ?>"
1686
                               id="<?php echo esc_attr($value['id'] . $value['value']); ?>" type="radio"
1687
                               value="<?php echo $value['value'] ?>" <?php if (get_option($value['id']) == $value['value']) {
1688 1
                            echo 'checked="checked"';
1689
                        }elseif(get_option($value['id'])=='' && $value['std']==$value['value']){echo 'checked="checked"';} ?> />
1690
                        <?php echo $value['desc']; ?></label><br>
1691
                </fieldset>
1692
                <?php
1693
1694 1 View Code Duplication
                if (!isset($value['radiogroup']) || (isset($value['radiogroup']) && $value['radiogroup'] == 'end')) :
1695
                    ?>
1696
                    </td>
1697
                    </tr>
1698
                <?php
1699 1
                endif;
1700
1701 1
                break;
1702
1703 1
            case 'textarea':
1704
                ?>
1705
                <tr valign="top">
1706
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1707
                <td class="forminp">
1708
                    <textarea
1709
                        <?php if (isset($value['args'])) echo $value['args'] . ' '; ?>name="<?php echo esc_attr($value['id']); ?>"
1710
                        id="<?php echo esc_attr($value['id']); ?>"
1711
                        <?php if(isset($value['placeholder'])){?>placeholder="<?php echo esc_attr($value['placeholder']); ?>"<?php }?>
1712
                        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
1713
                        class="description"><?php echo $value['desc'] ?></span>
1714
1715
                </td>
1716
                </tr><?php
1717 1
                break;
1718
1719 1
            case 'editor':
1720
                ?>
1721
                <tr valign="top">
1722
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1723
                <td class="forminp"><?php
1724
                    if (get_option($value['id']))
1725
                        $content = stripslashes(get_option($value['id']));
1726
                    else
1727
                        $content = $value['std'];
1728
1729
                    $editor_settings = array('media_buttons' => false, 'textarea_rows' => 10);
1730
1731
                    wp_editor($content, esc_attr($value['id']), $editor_settings);
1732
1733
                    ?> <span class="description"><?php echo $value['desc'] ?></span>
1734
1735
                </td>
1736
                </tr><?php
1737
                break;
1738
1739 1
            case 'single_select_page' :
1740
                // WPML
1741 1
				$switch_lang = false;
1742 1
				$disabled = '';
1743 1
				if (geodir_is_wpml() && isset($_REQUEST['tab']) && $_REQUEST['tab'] == 'permalink_settings') {
1744
					global $sitepress;
1745
					
1746
					$default_lang = $sitepress->get_default_language();
1747
					$current_lang = $sitepress->get_current_language();
1748
					
1749
					if ($current_lang != 'all' && $current_lang != $default_lang) {
1750
						$disabled = "disabled='disabled'";
1751
						$switch_lang = $current_lang;
1752
						$sitepress->switch_lang('all', true);
1753
					}
1754
				}
1755
				//
1756 1
				$page_setting = (int)get_option($value['id']);
1757
1758 1
                $args = array('name' => $value['id'],
1759 1
                    'id' => $value['id'],
1760 1
                    'sort_column' => 'menu_order',
1761 1
                    'sort_order' => 'ASC',
1762 1
                    'show_option_none' => ' ',
1763 1
                    'class' => $value['class'],
1764 1
                    'echo' => false,
1765 1
                    'selected' => $page_setting);
1766
1767 1
                if (isset($value['args'])) $args = wp_parse_args($value['args'], $args);
1768
1769
                ?>
1770
                <tr valign="top" class="single_select_page">
1771
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1772
                <td class="forminp">
1773
                    <?php echo str_replace(' id=', " data-placeholder='" . __('Select a page...', 'geodirectory') . "' style='" . $value['css'] . "' class='" . $value['class'] . "' " . $disabled . " id=", wp_dropdown_pages($args)); ?>
1774
                    <span class="description"><?php echo $value['desc'] ?></span>
1775
                </td>
1776
                </tr><?php
1777 1
				if ($switch_lang) {
1778
					$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...
1779
				}
1780 1
                break;
1781 1
            case 'single_select_country' :
1782
                $country_setting = (string)get_option($value['id']);
1783
                if (strstr($country_setting, ':')) :
1784
                    $country = current(explode(':', $country_setting));
1785
                    $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...
1786
                else :
1787
                    $country = $country_setting;
1788
                    $state = '*';
1789
                endif;
1790
                ?>
1791
                <tr valign="top">
1792
                <th scope="rpw" class="titledesc"><?php echo $value['name'] ?></th>
1793
                <td class="forminp"><select name="<?php echo esc_attr($value['id']); ?>"
1794
                                            style="<?php echo esc_attr($value['css']); ?>"
1795
                                            data-placeholder="<?php _e('Choose a country&hellip;', 'geodirectory'); ?>"
1796
                                            title="Country" class="chosen_select">
1797
                        <?php echo $geodirectory->countries->country_dropdown_options($country, $state); ?>
1798
                    </select> <span class="description"><?php echo $value['desc'] ?></span>
1799
                </td>
1800
                </tr><?php
1801
                break;
1802 1
            case 'multi_select_countries' :
1803
                $countries = $geodirectory->countries->countries;
1804
                asort($countries);
1805
                $selections = (array)get_option($value['id']);
1806
                ?>
1807
                <tr valign="top">
1808
                <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1809
                <td class="forminp">
1810
                    <select multiple="multiple" name="<?php echo esc_attr($value['id']); ?>[]" style="width:450px;"
1811
                            data-placeholder="<?php _e('Choose countries&hellip;', 'geodirectory'); ?>"
1812
                            title="Country" class="chosen_select">
1813
                        <?php
1814
                        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...
1815
                            echo '<option value="' . $key . '" ' . selected(in_array($key, $selections), true, false) . '>' . $val . '</option>';
1816
                        endforeach;
1817
                        ?>
1818
                    </select>
1819
                </td>
1820
                </tr>
1821
1822
                <?php
1823
1824
                break;
1825
1826 1
            case 'google_analytics' :
1827 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...
1828 1
                if(get_option('geodir_ga_client_id') && get_option('geodir_ga_client_secret') ) {
1829
                    ?>
1830
                    <tr valign="top">
1831
                        <th scope="row" class="titledesc"><?php echo $value['name'] ?></th>
1832
                        <td class="forminp">
1833
1834
1835
                            <?php
1836
1837
                            $oAuthURL = "https://accounts.google.com/o/oauth2/auth?";
1838
                            $scope = "scope=https://www.googleapis.com/auth/analytics.readonly";
1839
                            $state = "&state=123";//any string
1840
                            $redirect_uri = "&redirect_uri=" . admin_url('admin-ajax.php') . "?action=geodir_ga_callback";
1841
                            $response_type = "&response_type=code";
1842
                            $client_id = "&client_id=".get_option('geodir_ga_client_id');
1843
                            $access_type = "&access_type=offline";
1844
                            $approval_prompt = "&approval_prompt=force";
1845
1846
                            $auth_url = $oAuthURL . $scope . $state . $redirect_uri . $response_type . $client_id . $access_type . $approval_prompt;
1847
1848
1849
                            ?>
1850
                            <script>
1851
                                function gd_ga_popup() {
1852
                                    var win = window.open("<?php echo $auth_url;?>", "Google Analytics", "");
1853
                                    var pollTimer = window.setInterval(function () {
1854
                                        if (win.closed !== false) { // !== is required for compatibility with Opera
1855
                                            window.clearInterval(pollTimer);
1856
1857
                                            jQuery(".general_settings .submit .button-primary").trigger('click');
1858
                                        }
1859
                                    }, 200);
1860
                                }
1861
                            </script>
1862
1863
                            <?php
1864
                            if (get_option('gd_ga_refresh_token')) {
1865
                                ?>
1866
                                <span class="button-primary"
1867
                                      onclick="gd_ga_popup();"><?php _e('Re-authorize', 'geodirectory'); ?></span>
1868
                                <span
1869
                                    style="color: green; font-weight: bold;"><?php _e('Authorized', 'geodirectory'); ?></span>
1870
                            <?php
1871
                            } else {
1872
                                ?>
1873
                                <span class="button-primary"
1874
                                      onclick="gd_ga_popup();"><?php _e('Authorize', 'geodirectory');?></span>
1875
                            <?php
1876
                            }
1877
                            ?>
1878
                        </td>
1879
                    </tr>
1880
1881
                <?php
1882
                }
1883
1884 1
                break;
1885
1886
            case 'field_seperator' :
1887
1888
                ?>
1889
                <tr valign="top">
1890
                    <td colspan="2" class="forminp geodir_line_seperator"></td>
1891
                </tr>
1892
                <?php
1893
1894
                break;
1895
1896 1
        endswitch;
1897
1898 1
    endforeach;
1899
1900 1
    if ($first_title === false) {
1901 1
        echo "</div>";
1902 1
    }
1903
1904
    ?>
1905
1906
    <script type="text/javascript">
1907
1908
1909
        jQuery(document).ready(function () {
1910
1911
            jQuery('.geodir_option_tabs').each(function (ele) {
1912
                jQuery('#geodir_oiption_tabs').append(jQuery(this));
1913
            });
1914
1915
1916
            jQuery('.geodir_option_tabs').removeClass('gd-tab-active');
1917
            jQuery('.geodir_option_tabs:first').addClass('gd-tab-active');
1918
1919
            jQuery('.gd-content-heading').hide();
1920
            jQuery('.gd-content-heading:first').show();
1921
            jQuery('.geodir_option_tabs').bind('click', function () {
1922
                var tab_id = jQuery(this).attr('id');
1923
1924
                if (tab_id == 'dummy_data_settings') {
1925
                    jQuery('p .button-primary').hide();
1926
                } else if (tab_id == 'csv_upload_settings') {
1927
                    jQuery('p .button-primary').hide();
1928
                } else {
1929
                    jQuery('.button-primary').show();
1930
                }
1931
1932
                if (jQuery('#sub_' + tab_id + ' div').hasClass('geodir_auto_install'))
1933
                    jQuery('p .button-primary').hide();
1934
1935
                jQuery('.geodir_option_tabs').removeClass('gd-tab-active');
1936
                jQuery(this).addClass('gd-tab-active');
1937
                jQuery('.gd-content-heading').hide();
1938
                jQuery('#sub_' + tab_id).show();
1939
                jQuery('.active_tab').val(tab_id);
1940
                jQuery("select.chosen_select").trigger("chosen:updated"); //refresh chosen
1941
            });
1942
1943
            <?php if (isset($_REQUEST['active_tab']) && $_REQUEST['active_tab'] != '') { ?>
1944
            jQuery('.geodir_option_tabs').removeClass('gd-tab-active');
1945
            jQuery('#<?php echo sanitize_text_field($_REQUEST['active_tab']);?>').addClass('gd-tab-active');
1946
            jQuery('.gd-content-heading').hide();
1947
            jQuery('#sub_<?php echo sanitize_text_field($_REQUEST['active_tab']);?>').show();
1948
            <?php } ?>
1949
        });
1950
    </script>
1951
<?php
1952 1
}
1953
1954
/**
1955
 * Prints post information meta box content.
1956
 *
1957
 * @since 1.0.0
1958
 * @package GeoDirectory
1959
 * @global object $post The post object.
1960
 * @global int $post_id The post ID.
1961
 */
1962
function geodir_post_info_setting()
1963
{
1964
    global $post, $post_id;
1965
1966
    $post_type = get_post_type();
1967
1968
    $package_info = array();
1969
1970
    $package_info = geodir_post_package_info($package_info, $post, $post_type);
1971
    wp_nonce_field(plugin_basename(__FILE__), 'geodir_post_info_noncename');
1972
    echo '<div id="geodir_wrapper">';
1973
    /**
1974
     * Called before the GD custom fields are output in the wp-admin area.
1975
     *
1976
     * @since 1.0.0
1977
     * @see 'geodir_after_default_field_in_meta_box'
1978
     */
1979
    do_action('geodir_before_default_field_in_meta_box');
1980
    //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...
1981
    // to display all fields in one information box
1982
    geodir_get_custom_fields_html($package_info->pid, 'all', $post_type);
1983
    /**
1984
     * Called after the GD custom fields are output in the wp-admin area.
1985
     *
1986
     * @since 1.0.0
1987
     * @see 'geodir_before_default_field_in_meta_box'
1988
     */
1989
    do_action('geodir_after_default_field_in_meta_box');
1990
    echo '</div>';
1991
}
1992
1993
/**
1994
 * Prints additional information meta box content.
1995
 *
1996
 * @since 1.0.0
1997
 * @package GeoDirectory
1998
 * @global object $post The post object.
1999
 * @global int $post_id The post ID.
2000
 */
2001
function geodir_post_addinfo_setting()
2002
{
2003
    global $post, $post_id;
2004
2005
    $post_type = get_post_type();
2006
2007
    $package_info = array();
2008
2009
    $package_info = geodir_post_package_info($package_info, $post, $post_type);
2010
2011
    wp_nonce_field(plugin_basename(__FILE__), 'geodir_post_addinfo_noncename');
2012
    echo '<div id="geodir_wrapper">';
2013
    geodir_get_custom_fields_html($package_info->pid, 'custom', $post_type);
2014
    echo '</div>';
2015
2016
}
2017
2018
/**
2019
 * Prints Attachments meta box content.
2020
 *
2021
 * @since 1.0.0
2022
 * @package GeoDirectory
2023
 * @global object $post The post object.
2024
 * @global int $post_id The post ID.
2025
 */
2026
function geodir_post_attachments()
2027
{
2028
    global $post, $post_id;
2029
2030
    wp_nonce_field(plugin_basename(__FILE__), 'geodir_post_attachments_noncename');
2031
2032
    if (geodir_get_featured_image($post_id, 'thumbnail')) {
2033
        echo '<h4>' . __('Featured Image', 'geodirectory') . '</h4>';
2034
        geodir_show_featured_image($post_id, 'thumbnail');
2035
    }
2036
2037
    $image_limit = 0;
2038
2039
    ?>
2040
2041
2042
    <h5 class="form_title">
2043 View Code Duplication
        <?php if ($image_limit != 0 && $image_limit == 1) {
2044
            echo '<br /><small>(' . __('You can upload', 'geodirectory') . ' ' . $image_limit . ' ' . __('image with this package', 'geodirectory') . ')</small>';
2045
        } ?>
2046 View Code Duplication
        <?php if ($image_limit != 0 && $image_limit > 1) {
2047
            echo '<br /><small>(' . __('You can upload', 'geodirectory') . ' ' . $image_limit . ' ' . __('images with this package', 'geodirectory') . ')</small>';
2048
        } ?>
2049
        <?php if ($image_limit == 0) {
2050
            echo '<br /><small>(' . __('You can upload unlimited images with this package', 'geodirectory') . ')</small>';
2051
        } ?>
2052
    </h5>
2053
2054
2055
    <?php
2056
2057
    $curImages = geodir_get_images($post_id);
2058
    $place_img_array = array();
2059
2060
    if (!empty($curImages)):
2061
        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...
2062
            $place_img_array[] = $p_img->src;
2063
        endforeach;
2064
    endif;
2065
2066
    if (!empty($place_img_array))
2067
        $curImages = implode(',', $place_img_array);
2068
2069
2070
    // adjust values here
2071
    $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
2072
2073
    $svalue = $curImages; // this will be initial value of the above form field. Image urls.
2074
2075
    $multiple = true; // allow multiple files upload
2076
2077
    $width = geodir_media_image_large_width(); // If you want to automatically resize all uploaded images then provide width here (in pixels)
2078
2079
    $height = geodir_media_image_large_height(); // If you want to automatically resize all uploaded images then provide height here (in pixels)
2080
2081
    ?>
2082
2083
    <div class="gtd-form_row clearfix" id="<?php echo $id; ?>dropbox" style="border:1px solid #999999;padding:5px;text-align:center;">
2084
        <input type="hidden" name="<?php echo $id; ?>" id="<?php echo $id; ?>" value="<?php echo $svalue; ?>"/>
2085
2086
        <div
2087
            class="plupload-upload-uic hide-if-no-js <?php if ($multiple): ?>plupload-upload-uic-multiple<?php endif; ?>"
2088
            id="<?php echo $id; ?>plupload-upload-ui">
2089
            <h4><?php _e('Drop files to upload', 'geodirectory');?></h4>
2090
            <input id="<?php echo $id; ?>plupload-browse-button" type="button"
2091
                   value="<?php _e('Select Files', 'geodirectory'); ?>" class="button"/>
2092
            <span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce($id . 'pluploadan'); ?>"></span>
2093
            <?php if ($width && $height): ?>
2094
                <span class="plupload-resize"></span>
2095
                <span class="plupload-width" id="plupload-width<?php echo $width; ?>"></span>
2096
                <span class="plupload-height" id="plupload-height<?php echo $height; ?>"></span>
2097
            <?php endif; ?>
2098
            <div class="filelist"></div>
2099
        </div>
2100
        <div class="plupload-thumbs <?php if ($multiple): ?>plupload-thumbs-multiple<?php endif; ?> clearfix"
2101
             id="<?php echo $id; ?>plupload-thumbs" style="border-top:1px solid #ccc; padding-top:10px;">
2102
        </div>
2103
        <span
2104
            id="upload-msg"><?php _e('Please drag &amp; drop the images to rearrange the order', 'geodirectory');?></span>
2105
        <span id="<?php echo $id; ?>upload-error" style="display:none"></span>
2106
    </div>
2107
2108
<?php
2109
2110
}
2111
2112
/**
2113
 * Updates custom table when post get updated.
2114
 *
2115
 * @since 1.0.0
2116
 * @package GeoDirectory
2117
 * @param int $post_ID The post ID.
2118
 * @param object $post_after Post object after the update.
2119
 * @param object $post_before Post object before the update.
2120
 */
2121
function geodir_action_post_updated($post_ID, $post_after, $post_before)
2122
{
2123 1
    $post_type = get_post_type($post_ID);
2124
2125 1
    if (isset($_POST['action']) && $_POST['action'] == 'inline-save') {
2126
        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) {
2127
            geodir_save_post_meta($post_ID, 'post_title', $post_after->post_title);
2128
        }
2129
    }
2130 1
}
2131
2132
/**
2133
 * Add Listing published bcc option.
2134
 *
2135
 * WP Admin -> Geodirectory -> Notifications -> Site Bcc Options
2136
 *
2137
 * @since 1.0.0
2138
 * @package GeoDirectory
2139
 * @param array $settings The settings array.
2140
 * @return array
2141
 */
2142
function geodir_notification_add_bcc_option($settings)
2143
{
2144
    if (!empty($settings)) {
2145
        $new_settings = array();
2146
        foreach ($settings as $setting) {
2147
            if (isset($setting['id']) && $setting['id'] == 'site_bcc_options' && isset($setting['type']) && $setting['type'] == 'sectionend') {
2148
                $geodir_bcc_listing_published_yes = array(
2149
                    'name' => __('Listing published', 'geodirectory'),
2150
                    'desc' => __('Yes', 'geodirectory'),
2151
                    'id' => 'geodir_bcc_listing_published',
2152
                    'std' => 'yes',
2153
                    'type' => 'radio',
2154
                    'value' => '1',
2155
                    'radiogroup' => 'start'
2156
                );
2157
2158
                $geodir_bcc_listing_published_no = array(
2159
                    'name' => __('Listing published', 'geodirectory'),
2160
                    'desc' => __('No', 'geodirectory'),
2161
                    'id' => 'geodir_bcc_listing_published',
2162
                    'std' => 'yes',
2163
                    'type' => 'radio',
2164
                    'value' => '0',
2165
                    'radiogroup' => 'end'
2166
                );
2167
2168
                $new_settings[] = $geodir_bcc_listing_published_yes;
2169
                $new_settings[] = $geodir_bcc_listing_published_no;
2170
            }
2171
            $new_settings[] = $setting;
2172
        }
2173
        $settings = $new_settings;
2174
    }
2175
2176
    return $settings;
2177
}
2178
2179
2180
add_action('wp_ajax_get_gd_theme_compat_callback', 'get_gd_theme_compat_callback');
2181
2182
/**
2183
 * Exports theme compatibility data for given theme.
2184
 *
2185
 * @since 1.0.0
2186
 * @package GeoDirectory
2187
 * @global object $wpdb WordPress Database object.
2188
 */
2189
function get_gd_theme_compat_callback()
2190
{
2191
    global $wpdb;
2192
    $themes = get_option('gd_theme_compats');
2193
2194
    if (isset($_POST['theme']) && isset($themes[$_POST['theme']]) && !empty($themes[$_POST['theme']])) {
2195
        if (isset($_POST['export'])) {
2196
            echo json_encode(array($_POST['theme'] => $themes[$_POST['theme']]));
2197
        } else {
2198
            echo json_encode($themes[$_POST['theme']]);
2199
        }
2200
2201
    }
2202
2203
    die();
2204
}
2205
2206
add_action('wp_ajax_get_gd_theme_compat_import_callback', 'get_gd_theme_compat_import_callback');
2207
2208
/**
2209
 * Imports theme compatibility data for given theme.
2210
 *
2211
 * @since 1.0.0
2212
 * @package GeoDirectory
2213
 * @global object $wpdb WordPress Database object.
2214
 */
2215
function get_gd_theme_compat_import_callback()
2216
{
2217
    global $wpdb;
2218
    $themes = get_option('gd_theme_compats');
2219
    if (isset($_POST['theme']) && !empty($_POST['theme'])) {
2220
        $json = json_decode(stripslashes($_POST['theme']), true);
2221
        if (!empty($json) && is_array($json)) {
2222
            $key = sanitize_text_field(key($json));
2223
            $themes[$key] = $json[$key];
2224
            update_option('gd_theme_compats', $themes);
2225
            echo $key;
2226
            die();
2227
        }
2228
    }
2229
    echo '0';
2230
    die();
2231
}
2232
2233
2234
/**
2235
 * Sets theme compatibility options.
2236
 *
2237
 * @since 1.0.0
2238
 * @package GeoDirectory
2239
 * @global object $wpdb WordPress Database object.
2240
 */
2241
function gd_set_theme_compat()
2242
{
2243 1
    global $wpdb;
2244 1
    $theme = wp_get_theme();
2245
2246 1 View Code Duplication
    if ($theme->parent()) {
2247
        $theme_name = str_replace(" ", "_", $theme->parent()->get('Name'));
2248
    } else {
2249 1
        $theme_name = str_replace(" ", "_", $theme->get('Name'));
2250
    }
2251
2252 1
    $theme_compats = get_option('gd_theme_compats');
2253 1
    $current_compat = get_option('gd_theme_compat');
2254 1
    $current_compat = str_replace("_custom", "", $current_compat);
2255
2256 1
    if ($current_compat == $theme_name && strpos("_custom", get_option('gd_theme_compat')) !== false) {
2257
        return;
2258
    }// if already running correct compat then bail
2259
2260 1
    if (isset($theme_compats[$theme_name])) {// if there is a compat avail then set it
2261
        update_option('gd_theme_compat', $theme_name);
2262
        update_option('theme_compatibility_setting', $theme_compats[$theme_name]);
2263
2264
        // if there are default options to set then set them
2265
        if (isset($theme_compats[$theme_name]['geodir_theme_compat_default_options']) && !empty($theme_compats[$theme_name]['geodir_theme_compat_default_options'])) {
2266
2267
            foreach ($theme_compats[$theme_name]['geodir_theme_compat_default_options'] as $key => $val) {
2268
                update_option($key, $val);
2269
            }
2270
        }
2271
2272
    } else {
2273 1
        update_option('gd_theme_compat', '');
2274 1
        update_option('theme_compatibility_setting', '');
2275
    }
2276
2277
2278 1
}
2279
2280
2281
add_action('wp_loaded', 'gd_check_avada_compat');
2282
/**
2283
 * Function to check if Avada needs header.php replaced
2284
 *
2285
 * @since 1.0.0
2286
 * @package GeoDirectory
2287
 */
2288
function gd_check_avada_compat()
2289
{
2290
    if (function_exists('avada_load_textdomain') && !get_option('avada_nag')) {
2291
        add_action('admin_notices', 'gd_avada_compat_warning');
2292
    }
2293
}
2294
2295
2296
/**
2297
 * Displays Avada compatibility warning.
2298
 *
2299
 * @since 1.0.0
2300
 * @package GeoDirectory
2301
 */
2302
function gd_avada_compat_warning()
2303
{
2304
2305
    /*
2306
    $msg_type = error
2307
    $msg_type = updated fade
2308
    $msg_type = update-nag
2309
    */
2310
2311
    $plugin = 'avada-nag';
2312
    $timestamp = 'avada-nag1234';
2313
    $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');
2314
    echo '<div id="' . $timestamp . '"  class="error">';
2315
    echo '<span class="gd-remove-noti" onclick="gdRemoveANotification(\'' . $plugin . '\',\'' . $timestamp . '\');" ><i class="fa fa-times"></i></span>';
2316
    echo "<img class='gd-icon-noti' src='" . plugin_dir_url('') . "geodirectory/geodirectory-assets/images/favicon.ico' > ";
2317
    echo "<p>$message</p>";
2318
    echo "</div>";
2319
2320
    ?>
2321
    <script>
2322
        function gdRemoveANotification($plugin, $timestamp) {
2323
2324
            jQuery('#' + $timestamp).css("background-color", "red");
2325
            jQuery('#' + $timestamp).fadeOut("slow");
2326
            // This does the ajax request
2327
            jQuery.ajax({
2328
                url: ajaxurl,
2329
                type: 'POST',
2330
                data: {
2331
                    'action': 'geodir_avada_remove_notification',
2332
                    'plugin': $plugin,
2333
                    'timestamp': $timestamp
2334
                },
2335
                success: function (data) {
2336
                    // This outputs the result of the ajax request
2337
                    //alert(data);
2338
                },
2339
                error: function (errorThrown) {
2340
                    console.log(errorThrown);
2341
                }
2342
            });
2343
2344
        }
2345
    </script>
2346
    <style>
2347
        .gd-icon-noti {
2348
            float: left;
2349
            margin-top: 10px;
2350
            margin-right: 5px;
2351
        }
2352
2353
        .update-nag .gd-icon-noti {
2354
            margin-top: 2px;
2355
        }
2356
2357
        .gd-remove-noti {
2358
            float: right;
2359
            margin-top: -20px;
2360
            margin-right: -20px;
2361
            color: #FF0000;
2362
            cursor: pointer;
2363
        }
2364
2365
        .updated .gd-remove-noti, .error .gd-remove-noti {
2366
            float: right;
2367
            margin-top: -10px;
2368
            margin-right: -17px;
2369
            color: #FF0000;
2370
            cursor: pointer;
2371
        }
2372
2373
2374
    </style>
2375
<?php
2376
2377
}
2378
2379
2380
/**
2381
 * Removes Avada compatibility warning.
2382
 *
2383
 * @since 1.0.0
2384
 * @package GeoDirectory
2385
 */
2386
function geodir_avada_remove_notification()
2387
{
2388
    update_option('avada_nag', TRUE);
2389
2390
    // Always die in functions echoing ajax content
2391
    die();
2392
}
2393
2394
2395
add_action('wp_ajax_geodir_avada_remove_notification', 'geodir_avada_remove_notification');
2396
2397
/**
2398
 * Get the current post type in the WordPress admin
2399
 *
2400
 * @since 1.4.2
2401
 * @package GeoDirectory
2402
 *
2403
 * @global null|WP_Post $post Post object.
2404
 * @global string $typenow Post type.
2405
 * @global object|WP_Screen $current_screen Current screen object
2406
 *
2407
 * @return string Post type ex: gd_place
2408
 */
2409
function geodir_admin_current_post_type() {
2410
	global $post, $typenow, $current_screen;
2411
	
2412
	$post_type = NULL;
2413
	
2414
	if ($post && isset($post->post_type))
2415
		$post_type = $post->post_type;
2416
	elseif ($typenow)
2417
		$post_type = $typenow;
2418
	elseif ($current_screen && isset($current_screen->post_type))
2419
		$post_type = $current_screen->post_type;
2420
	elseif (isset($_REQUEST['post_type']))
2421
		$post_type = sanitize_key($_REQUEST['post_type']);
2422
	elseif (isset($_REQUEST['post']) && get_post_type($_REQUEST['post']))
2423
		$post_type = get_post_type($_REQUEST['post']);
2424
2425
	return $post_type;
2426
}
2427
2428
/**
2429
 * Fires before updating geodirectory admin settings.
2430
 *
2431
 * @since 1.4.2
2432
 * @package GeoDirectory
2433
 *
2434
 * @global object $sitepress Sitepress WPML object.
2435
 *
2436
 * @param string $current_tab Current tab in geodirectory settings.
2437
 * @param array  $geodir_settings Array of geodirectory settings.
2438
 */
2439
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...
2440
	$active_tab = isset($_REQUEST['active_tab']) ? trim($_REQUEST['active_tab']) : '';
2441
		
2442
	// Permalink settings
2443
	if ($current_tab == 'permalink_settings') {
2444
		$listing_prefix = isset($_POST['geodir_listing_prefix']) ? trim($_POST['geodir_listing_prefix']) : '';
2445
		$location_prefix = isset($_POST['geodir_location_prefix']) ? trim($_POST['geodir_location_prefix']) : '';
2446
		
2447
		// Don't allow same slug url for listing and location
2448
		if (geodir_strtolower($listing_prefix) == geodir_strtolower($location_prefix)) {
2449
			$redirect_url = admin_url('admin.php?page=geodirectory&tab=' . $current_tab . '&active_tab=' . $active_tab . '&msg=fail&gderr=21');
2450
        	wp_redirect($redirect_url);
2451
			exit;
2452
		}
2453
		
2454
		// Don't allow to update page settings on different language.
2455
		if (geodir_is_wpml()) {
2456
			global $sitepress;
2457
			$current_language = $sitepress->get_current_language();
2458
			$default_language = $sitepress->get_default_language();
2459
			
2460
			if ($current_language != 'all' && $current_language != $default_language) {
2461
				$redirect_url = admin_url('admin.php?page=geodirectory&tab=' . $current_tab . '&active_tab=' . $active_tab);
2462
				wp_redirect($redirect_url);
2463
				exit;
2464
			}
2465
		}
2466
	}
2467
}
2468
2469
2470
/**
2471
 * Removes the preview buttons from the wp-admin area for GD post types.
2472
 *
2473
 * This was removed as the preview page was causing bugs.
2474
 *
2475
 * @global string $post_type The current post type.
2476
 * @since 1.4.3
2477
 * @package GeoDirectory
2478
 */
2479
function geodir_hide_admin_preview_button() {
2480
    global $post_type;
2481
    $post_types = geodir_get_posttypes();
2482
    if(in_array($post_type, $post_types))
2483
        echo '<style type="text/css">#post-preview, #view-post-btn{display: none;}</style>';
2484
}
2485
add_action( 'admin_head-post-new.php', 'geodir_hide_admin_preview_button' );
2486
add_action( 'admin_head-post.php', 'geodir_hide_admin_preview_button' );
2487
2488
/**
2489
 * Add the tab in left sidebar menu fro import & export page.
2490
 *
2491
 * @since 1.4.6
2492
 * @package GeoDirectory
2493
 *
2494
 * @return array Array of tab data.
2495
 */
2496
function geodir_import_export_tab( $tabs ) {
2497 1
	$tabs['import_export'] = array( 'label' => __( 'Import & Export', 'geodirectory' ) );
2498 1
    return $tabs;
2499
}
2500
2501
/**
2502
 * Display the page to manage import/export categories/listings.
2503
 *
2504
 * @since 1.4.6
2505
 * @since 1.5.6 Option added to export max number listings per csv file.
2506
 * @package GeoDirectory
2507
 *
2508
 * @return string Html content.
2509
 */
2510
function geodir_import_export_page() {
2511 1
	$nonce = wp_create_nonce( 'geodir_import_export_nonce' );
2512 1
	$gd_cats_sample_csv = geodir_plugin_url() . '/geodirectory-assets/gd_sample_categories.csv';
2513
    /**
2514
     * Filter sample category data csv file url.
2515
     *
2516
     * @since 1.0.0
2517
     * @package GeoDirectory
2518
     *
2519
     * @param string $gd_cats_sample_csv Sample category data csv file url.
2520
     */
2521 1
	$gd_cats_sample_csv = apply_filters( 'geodir_export_cats_sample_csv', $gd_cats_sample_csv );
2522
	
2523 1
	$gd_posts_sample_csv = geodir_plugin_url() . '/geodirectory-assets/place_listing.csv';
2524
    /**
2525
     * Filter sample post data csv file url.
2526
     *
2527
     * @since 1.0.0
2528
     * @package GeoDirectory
2529
     *
2530
     * @param string $gd_posts_sample_csv Sample post data csv file url.
2531
     */
2532 1
    $gd_posts_sample_csv = apply_filters( 'geodir_export_posts_sample_csv', $gd_posts_sample_csv );
2533
	
2534 1
	$gd_posttypes = geodir_get_posttypes( 'array' );
2535
	
2536 1
	$gd_posttypes_option = '';
2537 1
	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...
2538 1
		$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>';
2539 1
	}
2540 1
	wp_enqueue_script( 'jquery-ui-progressbar' );
2541
	
2542 1
	$gd_chunksize_options = array();
2543 1
	$gd_chunksize_options[100] = 100;
2544 1
	$gd_chunksize_options[200] = 200;
2545 1
	$gd_chunksize_options[500] = 500;
2546 1
	$gd_chunksize_options[1000] = 1000;
2547 1
	$gd_chunksize_options[2000] = 2000;
2548 1
	$gd_chunksize_options[5000] = 5000;
2549 1
	$gd_chunksize_options[10000] = 10000;
2550 1
	$gd_chunksize_options[20000] = 20000;
2551 1
	$gd_chunksize_options[50000] = 50000;
2552 1
	$gd_chunksize_options[100000] = 100000;
2553
	 
2554
	 /**
2555
     * Filter max entries per export csv file.
2556
     *
2557
     * @since 1.5.6
2558
     * @package GeoDirectory
2559
     *
2560
     * @param string $gd_chunksize_options Entries options.
2561
     */
2562 1
    $gd_chunksize_options = apply_filters( 'geodir_export_csv_chunksize_options', $gd_chunksize_options );
2563
	
2564 1
	$gd_chunksize_option = '';
2565 1
	foreach ($gd_chunksize_options as $value => $title) {
2566 1
		$gd_chunksize_option .= '<option value="' . $value . '" ' . selected($value, 5000, false) . '>' . $title . '</option>';
2567 1
	}
2568
	
2569 1
	$uploads = wp_upload_dir();
2570
?>
2571
</form>
2572
<div class="inner_content_tab_main gd-import-export">
2573
  <h3><?php _e( 'GD Import & Export CSV', 'geodirectory' ) ;?></h3>
2574
  <span class="description"><?php _e( 'Import & export csv for GD listings & categories.', 'geodirectory' ) ;?></span>
2575
  <div class="gd-content-heading">
2576
2577
  <?php
2578 1
    ini_set('max_execution_time', 999999);
2579 1
    $ini_max_execution_time_check = @ini_get( 'max_execution_time' );
2580 1
    ini_restore('max_execution_time');
2581
2582 1
    if($ini_max_execution_time_check != 999999){ // only show these setting to the user if we can't change the ini setting
2583
        ?>
2584
	<div id="gd_ie_reqs" class="metabox-holder">
2585
      <div class="meta-box-sortables ui-sortable">
2586
        <div class="postbox">
2587
          <h3 class="hndle"><span style='vertical-align:top;'><?php echo __( 'PHP Requirements for GD Import & Export CSV', 'geodirectory' );?></span></h3>
2588
          <div class="inside">
2589
            <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>
2590
			<table class="form-table">
2591
				<thead>
2592
				  <tr>
2593
				  	<th><?php _e( 'PHP Settings', 'geodirectory' );?></th><th><?php _e( 'Current Value', 'geodirectory' );?></th><th><?php _e( 'Recommended Value', 'geodirectory' );?></th>
2594
				  </tr>
2595
				</thead>
2596
				<tbody>
2597
				  <tr>
2598
				  	<td>max_input_time</td><td><?php echo @ini_get( 'max_input_time' );?></td><td>3000</td>
2599
				  </tr>
2600
				  <tr>
2601
				  	<td>max_execution_time</td><td><?php  echo @ini_get( 'max_execution_time' );?></td><td>3000</td>
2602
				  </tr>
2603
				  <tr>
2604
				  	<td>memory_limit</td><td><?php echo @ini_get( 'memory_limit' );?></td><td>256M</td>
2605
				  </tr>
2606
				</tbody>
2607
		    </table>
2608
		  </div>
2609
		</div>
2610
	  </div>
2611
	</div>
2612
	<?php }?>
2613
	<div id="gd_ie_imposts" class="metabox-holder">
2614
      <div class="meta-box-sortables ui-sortable">
2615
        <div id="gd_ie_im_posts" class="postbox gd-hndle-pbox">
2616
          <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>
2617
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Listings: Import CSV', 'geodirectory' );?></span></h3>
2618
          <div class="inside">
2619
            <table class="form-table">
2620
				<tbody>
2621
				  <tr>
2622
					<td class="gd-imex-box">
2623
						<div class="gd-im-choices">
2624
						<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>
2625
						<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>
2626
						</div>
2627
						<div class="plupload-upload-uic hide-if-no-js" id="gd_im_postplupload-upload-ui">
2628
							<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');" />
2629
							<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">
2630
						<input type="hidden" id="gd_ie_imposts_csv" value="<?php echo $gd_posts_sample_csv;?>" />
2631
							<?php
2632
							/**
2633
							 * Called just after the sample CSV download link.
2634
							 *
2635
							 * @since 1.0.0
2636
							 */
2637 1
							do_action('geodir_sample_csv_download_link');
2638
							?>
2639
							<span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce( 'gd_im_postpluploadan' ); ?>"></span>
2640
							<div class="filelist"></div>
2641
						</div>
2642
						<span id="gd_im_catupload-error" style="display:none"></span>
2643
						<span class="description"></span>
2644
						<div id="gd_importer" style="display:none">
2645
							<input type="hidden" id="gd_total" value="0"/>
2646
							<input type="hidden" id="gd_prepared" value="continue"/>
2647
							<input type="hidden" id="gd_processed" value="0"/>
2648
							<input type="hidden" id="gd_created" value="0"/>
2649
							<input type="hidden" id="gd_updated" value="0"/>
2650
							<input type="hidden" id="gd_skipped" value="0"/>
2651
							<input type="hidden" id="gd_invalid" value="0"/>
2652
							<input type="hidden" id="gd_invalid_addr" value="0"/>
2653
							<input type="hidden" id="gd_images" value="0"/>
2654
							<input type="hidden" id="gd_terminateaction" value="continue"/>
2655
						</div>
2656
						<div class="gd-import-progress" id="gd-import-progress" style="display:none">
2657
							<div class="gd-import-file"><b><?php _e("Import Data Status :", 'geodirectory');?> </b><font
2658
									id="gd-import-done">0</font> / <font id="gd-import-total">0</font>&nbsp;( <font
2659
									id="gd-import-perc">0%</font> )
2660
								<div class="gd-fileprogress"></div>
2661
							</div>
2662
						</div>
2663
						<div class="gd-import-msg" id="gd-import-msg" style="display:none">
2664
							<div id="message" class="message fade"></div>
2665
						</div>
2666
                    	<div class="gd-imex-btns" style="display:none;">
2667
                        	<input type="hidden" class="geodir_import_file" name="geodir_import_file" value="save"/>
2668
                        	<input onclick="gd_imex_PrepareImport(this, 'post')" type="button" value="<?php echo CSV_IMPORT_DATA; ?>" id="gd_import_data" class="button-primary" />
2669
                        	<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"/>
2670
                        	<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')"/>
2671
							<div id="gd_process_data" style="display:none">
2672
								<span class="spinner is-active" style="display:inline-block;margin:0 5px 0 5px;float:left"></span><?php _e("Wait, processing import data...", 'geodirectory');?>
2673
							</div>
2674
						</div>
2675
					</td>
2676
				  </tr>
2677
				</tbody>
2678
			</table>
2679
          </div>
2680
        </div>
2681
      </div>
2682
    </div>
2683
	<div id="gd_ie_excategs" class="metabox-holder">
2684
	  <div class="meta-box-sortables ui-sortable">
2685
		<div id="gd_ie_ex_posts" class="postbox gd-hndle-pbox">
2686
		  <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>
2687
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Listings: Export CSV', 'geodirectory' );?></span></h3>
2688
		  <div class="inside">
2689
			<table class="form-table">
2690
			  <tbody>
2691
				<tr>
2692
				  <td class="fld"><label for="gd_post_type">
2693
					<?php _e( 'Post Type:', 'geodirectory' );?>
2694
					</label></td>
2695
				  <td><select name="gd_post_type" id="gd_post_type" style="min-width:140px">
2696
					  <?php echo $gd_posttypes_option;?>
2697
					</select></td>
2698
				</tr>
2699
				<tr>
2700
					<td class="fld" style="vertical-align:top"><label for="gd_chunk_size"><?php _e( 'Max entries per csv file:', 'geodirectory' );?></label></td>
2701
					<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>
2702
				  </tr>
2703
				<tr>
2704
				  <td class="fld" style="vertical-align:top"><label>
2705
					<?php _e( 'Progress:', 'geodirectory' );?>
2706
					</label></td>
2707
				  <td><div id='gd_progressbar_box'>
2708
					  <div id="gd_progressbar" class="gd_progressbar">
2709
						<div class="gd-progress-label"></div>
2710
					  </div>
2711
					</div>
2712
					<p style="display:inline-block">
2713
					  <?php _e( 'Elapsed Time:', 'geodirectory' );?>
2714
					</p>
2715
					  
2716
					<p id="gd_timer" class="gd_timer">00:00:00</p></td>
2717
				</tr>
2718
				<tr class="gd-ie-actions">
2719
				  <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">
2720
				  </td>
2721
				  <td id="gd_ie_ex_files" class="gd-ie-files"></td>
2722
				</tr>
2723
			  </tbody>
2724
			</table>
2725
		  </div>
2726
		</div>
2727
	  </div>
2728
	</div>
2729
	<div id="gd_ie_imcategs" class="metabox-holder">
2730
      <div class="meta-box-sortables ui-sortable">
2731
        <div id="gd_ie_imcats" class="postbox gd-hndle-pbox">
2732
          <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>
2733
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Categories: Import CSV', 'geodirectory' );?></span></h3>
2734
          <div class="inside">
2735
            <table class="form-table">
2736
				<tbody>
2737
				  <tr>
2738
					<td class="gd-imex-box">
2739
						<div class="gd-im-choices">
2740
						<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>
2741
						<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>
2742
						</div>
2743
						<div class="plupload-upload-uic hide-if-no-js" id="gd_im_catplupload-upload-ui">
2744
							<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');" />
2745
							<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">
2746
						<input type="hidden" id="gd_ie_imcats_csv" value="<?php echo $gd_cats_sample_csv;?>" />
2747
						<?php
2748
						/**
2749
						 * Called just after the sample CSV download link.
2750
						 *
2751
						 * @since 1.0.0
2752
                         * @package GeoDirectory
2753
						 */
2754 1
						do_action('geodir_sample_cats_csv_download_link');
2755
						?>
2756
							<span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce( 'gd_im_catpluploadan' ); ?>"></span>
2757
							<div class="filelist"></div>
2758
						</div>
2759
						<span id="gd_im_catupload-error" style="display:none"></span>
2760
						<span class="description"></span>
2761
						<div id="gd_importer" style="display:none">
2762
							<input type="hidden" id="gd_total" value="0"/>
2763
							<input type="hidden" id="gd_prepared" value="continue"/>
2764
							<input type="hidden" id="gd_processed" value="0"/>
2765
							<input type="hidden" id="gd_created" value="0"/>
2766
							<input type="hidden" id="gd_updated" value="0"/>
2767
							<input type="hidden" id="gd_skipped" value="0"/>
2768
							<input type="hidden" id="gd_invalid" value="0"/>
2769
							<input type="hidden" id="gd_images" value="0"/>
2770
							<input type="hidden" id="gd_terminateaction" value="continue"/>
2771
						</div>
2772
						<div class="gd-import-progress" id="gd-import-progress" style="display:none">
2773
							<div class="gd-import-file"><b><?php _e("Import Data Status :", 'geodirectory');?> </b><font
2774
									id="gd-import-done">0</font> / <font id="gd-import-total">0</font>&nbsp;( <font
2775
									id="gd-import-perc">0%</font> )
2776
								<div class="gd-fileprogress"></div>
2777
							</div>
2778
						</div>
2779
						<div class="gd-import-msg" id="gd-import-msg" style="display:none">
2780
							<div id="message" class="message fade"></div>
2781
						</div>
2782
                    	<div class="gd-imex-btns" style="display:none;">
2783
                        	<input type="hidden" class="geodir_import_file" name="geodir_import_file" value="save"/>
2784
                        	<input onclick="gd_imex_PrepareImport(this, 'cat')" type="button" value="<?php echo CSV_IMPORT_DATA; ?>" id="gd_import_data" class="button-primary" />
2785
                        	<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"/>
2786
                        	<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')"/>
2787
							<div id="gd_process_data" style="display:none">
2788
								<span class="spinner is-active" style="display:inline-block;margin:0 5px 0 5px;float:left"></span><?php _e("Wait, processing import data...", 'geodirectory');?>
2789
							</div>
2790
						</div>
2791
					</td>
2792
				  </tr>
2793
				</tbody>
2794
			</table>
2795
          </div>
2796
        </div>
2797
      </div>
2798
    </div>
2799
	<div id="gd_ie_excategs" class="metabox-holder">
2800
      <div class="meta-box-sortables ui-sortable">
2801
        <div id="gd_ie_ex_cats" class="postbox gd-hndle-pbox">
2802
          <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>
2803
          <h3 class="hndle gd-hndle-click"><span style='vertical-align:top;'><?php echo __( 'GD Categories: Export CSV', 'geodirectory' );?></span></h3>
2804
          <div class="inside">
2805
            <table class="form-table">
2806
				<tbody>
2807
				  <tr>
2808
					<td class="fld"><label for="gd_post_type"><?php _e( 'Post Type:', 'geodirectory' );?></label></td>
2809
					<td><select name="gd_post_type" id="gd_post_type" style="min-width:140px"><?php echo $gd_posttypes_option;?></select></td>
2810
				  </tr>
2811
				   <tr>
2812
					<td class="fld" style="vertical-align:top"><label for="gd_chunk_size"><?php _e( 'Max entries per csv file:', 'geodirectory' );?></label></td>
2813
					<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>
2814
				  </tr>
2815
				  <tr>
2816
					<td class="fld" style="vertical-align:top"><label><?php _e( 'Progress:', 'geodirectory' );?></label></td>
2817
					<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>
2818
				  </tr>
2819
				  <tr class="gd-ie-actions">
2820
					<td style="vertical-align:top">
2821
						<input type="submit" value="<?php echo esc_attr( __( 'Export CSV', 'geodirectory' ) );?>" class="button-primary" name="gd_ie_excats_submit" id="gd_ie_excats_submit">
2822
					</td>
2823
					<td id="gd_ie_ex_files" class="gd-ie-files"></td>
2824
				  </tr>
2825
				</tbody>
2826
			</table>
2827
          </div>
2828
        </div>
2829
      </div>
2830
    </div>
2831
	<?php
2832
	/**
2833
	 * Allows you to add more setting to the GD > Import & Export page.
2834
	 *
2835
	 * Called after the last setting on the GD > Import & Export page.
2836
	 * @since 1.4.6
2837
     * @package GeoDirectory
2838
	 *
2839
	 * @param array $gd_posttypes GD post types.
2840
     * @param array $gd_chunksize_options File chunk size options.
2841
     * @param string $nonce Wordpress security token for GD import & export.
2842
	 */
2843 1
	do_action( 'geodir_import_export', $gd_posttypes, $gd_chunksize_options, $nonce );
2844
	?>
2845
  </div>
2846
</div>
2847
<script type="text/javascript">
2848
var timoutC, timoutP, timoutL, timoutH;
2849
2850
function gd_imex_PrepareImport(el, type) {
2851
    var cont = jQuery(el).closest('.gd-imex-box');
2852
    var gd_prepared = jQuery('#gd_prepared', cont).val();
2853
    var uploadedFile = jQuery('#gd_im_' + type, cont).val();
2854
    jQuery('gd-import-msg', cont).hide();
2855
    if(gd_prepared == uploadedFile) {
2856
        gd_imex_ContinueImport(el, type);
2857
        jQuery('#gd_import_data', cont).attr('disabled', 'disabled');
2858
    } else {
2859
        jQuery.ajax({
2860
            url: ajaxurl,
2861
            type: "POST",
2862
            data: 'action=geodir_import_export&task=prepare_import&_pt=' + type + '&_file=' + uploadedFile + '&_nonce=<?php echo $nonce;?>',
2863
            dataType: 'json',
2864
            cache: false,
2865
            success: function(data) {
2866
                if(typeof data == 'object') {
2867
                    if(data.error) {
2868
                        jQuery('#gd-import-msg', cont).find('#message').removeClass('updated').addClass('error').html('<p>' + data.error + '</p>');
2869
                        jQuery('#gd-import-msg', cont).show();
2870
                    } else if(!data.error && typeof data.rows != 'undefined') {
2871
                        jQuery('#gd_total', cont).val(data.rows);
2872
                        jQuery('#gd_prepared', cont).val(uploadedFile);
2873
                        jQuery('#gd_processed', cont).val('0');
2874
                        jQuery('#gd_created', cont).val('0');
2875
                        jQuery('#gd_updated', cont).val('0');
2876
                        jQuery('#gd_skipped', cont).val('0');
2877
                        jQuery('#gd_invalid', cont).val('0');
2878
                        jQuery('#gd_images', cont).val('0');
2879
                        if(type == 'post') {
2880
                            jQuery('#gd_invalid_addr', cont).val('0');
2881
                        }
2882
                        gd_imex_StartImport(el, type);
2883
                    }
2884
                }
2885
            },
2886
            error: function(errorThrown) {
2887
                console.log(errorThrown);
2888
            }
2889
        });
2890
    }
2891
}
2892
2893
function gd_imex_StartImport(el, type) {
2894
    var cont = jQuery(el).closest('.gd-imex-box');
2895
2896
    var limit = 1;
2897
    var total = parseInt(jQuery('#gd_total', cont).val());
2898
    var total_processed = parseInt(jQuery('#gd_processed', cont).val());
2899
    var uploadedFile = jQuery('#gd_im_' + type, cont).val();
2900
    var choice = jQuery('input[name="gd_im_choice'+ type +'"]:checked', cont).val();
2901
2902
    if (!uploadedFile) {
2903
        jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2904
        jQuery('#gd_stop_import', cont).hide();
2905
        jQuery('#gd_process_data', cont).hide();
2906
        jQuery('#gd-import-progress', cont).hide();
2907
        jQuery('.gd-fileprogress', cont).width(0);
2908
        jQuery('#gd-import-done', cont).text('0');
2909
        jQuery('#gd-import-total', cont).text('0');
2910
        jQuery('#gd-import-perc', cont).text('0%');
2911
2912
        jQuery(cont).find('.filelist .file').remove();
2913
        
2914
        jQuery('#gd-import-msg', cont).find('#message').removeClass('updated').addClass('error').html("<p><?php echo esc_attr( PLZ_SELECT_CSV_FILE );?></p>");
2915
        jQuery('#gd-import-msg', cont).show();
2916
        
2917
        return false;
2918
    }
2919
2920
    jQuery('#gd-import-total', cont).text(total);
2921
    jQuery('#gd_stop_import', cont).show();
2922
    jQuery('#gd_process_data', cont).css({
2923
        'display': 'inline-block'
2924
    });
2925
    jQuery('#gd-import-progress', cont).show();
2926
    if ((parseInt(total) / 100) > 0) {
2927
        limit = parseInt(parseInt(total) / 100);
2928
    }
2929
    if (limit == 1) {
2930
        if (parseInt(total) > 50) {
2931
            limit = 5;
2932
        } else if (parseInt(total) > 10 && parseInt(total) < 51) {
2933
            limit = 2;
2934
        }
2935
    }
2936
    if (limit > 10) {
2937
        limit = 10;
2938
    }
2939
    if (limit < 1) {
2940
        limit = 1;
2941
    }
2942
2943
    if ( parseInt(limit) > parseInt(total) )
2944
        limit = parseInt(total);
2945
    if (total_processed >= total) {
2946
        jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2947
        jQuery('#gd_stop_import', cont).hide();
2948
        jQuery('#gd_process_data', cont).hide();
2949
        
2950
        gd_imex_showStatusMsg(el, type);
2951
        
2952
        jQuery('#gd_im_' + type, cont).val('');
2953
        jQuery('#gd_prepared', cont).val('');
2954
2955
        return false;
2956
    }
2957
    jQuery('#gd-import-msg', cont).hide();
2958
        
2959
    var gd_processed = parseInt(jQuery('#gd_processed', cont).val());
2960
    var gd_created = parseInt(jQuery('#gd_created', cont).val());
2961
    var gd_updated = parseInt(jQuery('#gd_updated', cont).val());
2962
    var gd_skipped = parseInt(jQuery('#gd_skipped', cont).val());
2963
    var gd_invalid = parseInt(jQuery('#gd_invalid', cont).val());
2964
    var gd_images = parseInt(jQuery('#gd_images', cont).val());
2965
    if (type=='post') {
2966
        var gd_invalid_addr = parseInt(jQuery('#gd_invalid_addr', cont).val());
2967
    }
2968
2969
    var gddata = '&limit=' + limit + '&processed=' + gd_processed;
2970
    jQuery.ajax({
2971
        url: ajaxurl,
2972
        type: "POST",
2973
        data: 'action=geodir_import_export&task=import_' + type + '&_pt=' + type + '&_file=' + uploadedFile + gddata + '&_ch=' + choice + '&_nonce=<?php echo $nonce;?>',
2974
        dataType : 'json',
2975
        cache: false,
2976
        success: function (data) {
2977
            if (typeof data == 'object') {
2978
                if (data.error) {
2979
                    jQuery('#gd_import_data', cont).removeAttr('disabled').show();
2980
                    jQuery('#gd_stop_import', cont).hide();
2981
                    jQuery('#gd_process_data', cont).hide();
2982
                    jQuery('#gd-import-msg', cont).find('#message').removeClass('updated').addClass('error').html('<p>' + data.error + '</p>');
2983
                    jQuery('#gd-import-msg', cont).show();
2984
                } else {
2985
                    gd_processed = gd_processed + parseInt(data.processed);
2986
                    gd_processed = Math.min(gd_processed, total);
2987
                    gd_created = gd_created + parseInt(data.created);
2988
                    gd_updated = gd_updated + parseInt(data.updated);
2989
                    gd_skipped = gd_skipped + parseInt(data.skipped);
2990
                    gd_invalid = gd_invalid + parseInt(data.invalid);
2991
                    gd_images = gd_images + parseInt(data.images);
2992
                    if (type=='post' && typeof data.invalid_addr != 'undefined') {
2993
                        gd_invalid_addr = gd_invalid_addr + parseInt(data.invalid_addr);
2994
                    }
2995
2996
                    jQuery('#gd_processed', cont).val(gd_processed);
2997
                    jQuery('#gd_created', cont).val(gd_created);
2998
                    jQuery('#gd_updated', cont).val(gd_updated);
2999
                    jQuery('#gd_skipped', cont).val(gd_skipped);
3000
                    jQuery('#gd_invalid', cont).val(gd_invalid);
3001
                    jQuery('#gd_images', cont).val(gd_images);
3002
                    if (type=='post') {
3003
                        jQuery('#gd_invalid_addr', cont).val(gd_invalid_addr);
3004
                    }
3005
3006
                    if (parseInt(gd_processed) == parseInt(total)) {
3007
                        jQuery('#gd-import-done', cont).text(total);
3008
                        jQuery('#gd-import-perc', cont).text('100%');
3009
                        jQuery('.gd-fileprogress', cont).css({
3010
                            'width': '100%'
3011
                        });
3012
                        jQuery('#gd_im_' + type, cont).val('');
3013
                        jQuery('#gd_prepared', cont).val('');
3014
                        
3015
                        gd_imex_showStatusMsg(el, type);
3016
                        gd_imex_FinishImport(el, type);
3017
3018
                        jQuery('#gd_stop_import', cont).hide();
3019
                    }
3020
                    if (parseInt(gd_processed) < parseInt(total)) {
3021
                        var terminate_action = jQuery('#gd_terminateaction', cont).val();
3022
                        if (terminate_action == 'continue') {
3023
                            var nTmpCnt = parseInt(total_processed) + parseInt(limit);
3024
                            nTmpCnt = nTmpCnt > total ? total : nTmpCnt;
3025
3026
                            jQuery('#gd_processed', cont).val(nTmpCnt);
3027
3028
                            jQuery('#gd-import-done', cont).text(nTmpCnt);
3029
                            if (parseInt(total) > 0) {
3030
                                var percentage = ((parseInt(nTmpCnt) / parseInt(total)) * 100);
3031
                                percentage = percentage > 100 ? 100 : percentage;
3032
                                jQuery('#gd-import-perc', cont).text(parseInt(percentage) + '%');
3033
                                jQuery('.gd-fileprogress', cont).css({
3034
                                    'width': percentage + '%'
3035
                                });
3036
                            }
3037
                            
3038
                            if (type=='cat') {
3039
                                clearTimeout(timoutC);
3040
                                timoutC = setTimeout(function () {
3041
                                    gd_imex_StartImport(el, type);
3042
                                }, 0);
3043
                            }
3044
                            if (type=='post') {
3045
                                clearTimeout(timoutP);
3046
                                timoutP = setTimeout(function () {
3047
                                    gd_imex_StartImport(el, type);
3048
                                }, 0);
3049
                            }
3050
                            if (type=='loc') {
3051
                                clearTimeout(timoutL);
3052
                                timoutL = setTimeout(function () {
3053
                                    gd_imex_StartImport(el, type);
3054
                                }, 0);
3055
                            }
3056
                            if (type=='hood') {
3057
                                clearTimeout(timoutH);
3058
                                timoutH = setTimeout(function () {
3059
                                    gd_imex_StartImport(el, type);
3060
                                }, 0);
3061
                            }
3062
                        } else {
3063
                            jQuery('#gd_import_data', cont).hide();
3064
                            jQuery('#gd_stop_import', cont).hide();
3065
                            jQuery('#gd_process_data', cont).hide();
3066
                            jQuery('#gd_continue_data', cont).show();
3067
                            return false;
3068
                        }
3069
                    } else {
3070
                        jQuery('#gd_import_data', cont).removeAttr('disabled').show();
3071
                        jQuery('#gd_stop_import', cont).hide();
3072
                        jQuery('#gd_process_data', cont).hide();
3073
                        return false;
3074
                    }
3075
                }
3076
            } else {
3077
                jQuery('#gd_import_data', cont).removeAttr('disabled').show();
3078
                jQuery('#gd_stop_import', cont).hide();
3079
                jQuery('#gd_process_data', cont).hide();
3080
            }
3081
        },
3082
        error: function (errorThrown) {
3083
            jQuery('#gd_import_data', cont).removeAttr('disabled').show();
3084
            jQuery('#gd_stop_import', cont).hide();
3085
            jQuery('#gd_process_data', cont).hide();
3086
            console.log(errorThrown);
3087
        }
3088
    });
3089
}
3090
3091
function gd_imex_TerminateImport(el, type) {
3092
    var cont = jQuery(el).closest('.gd-imex-box');
3093
    jQuery('#gd_terminateaction', cont).val('terminate');
3094
    jQuery('#gd_import_data', cont).hide();
3095
    jQuery('#gd_stop_import', cont).hide();
3096
    jQuery('#gd_process_data', cont).hide();
3097
    jQuery('#gd_continue_data', cont).show();
3098
}
3099
3100
function gd_imex_ContinueImport(el, type) {	
3101
    var cont = jQuery(el).closest('.gd-imex-box');
3102
    var processed = jQuery('#gd_processed', cont).val();
3103
    var total = jQuery('#gd_total', cont).val();
3104
    if (parseInt(processed) > parseInt(total)) {
3105
        jQuery('#gd_stop_import', cont).hide();
3106
    } else {
3107
        jQuery('#gd_stop_import', cont).show();
3108
    }
3109
    jQuery('#gd_import_data', cont).show();
3110
    jQuery('#gd_import_data', cont).attr('disabled', 'disabled');
3111
    jQuery('#gd_process_data', cont).css({
3112
        'display': 'inline-block'
3113
    });
3114
    jQuery('#gd_continue_data', cont).hide();
3115
    jQuery('#gd_terminateaction', cont).val('continue');
3116
3117
    if (type=='cat') {
3118
        clearTimeout(timoutC);
3119
        timoutC = setTimeout(function () {
3120
            gd_imex_StartImport(el, type);
3121
        }, 0);
3122
    }
3123
3124
    if (type=='post') {
3125
        clearTimeout(timoutP);
3126
        timoutP = setTimeout(function () {
3127
            gd_imex_StartImport(el, type);
3128
        }, 0);
3129
    }
3130
3131
    if (type=='loc') {
3132
        clearTimeout(timoutL);
3133
        timoutL = setTimeout(function () {
3134
            gd_imex_StartImport(el, type);
3135
        }, 0);
3136
    }
3137
    
3138
    if (type=='hood') {
3139
        clearTimeout(timoutH);
3140
        timoutH = setTimeout(function () {
3141
            gd_imex_StartImport(el, type);
3142
        }, 0);
3143
    }
3144
}
3145
3146
function gd_imex_showStatusMsg(el, type) {
3147
    var cont = jQuery(el).closest('.gd-imex-box');
3148
3149
    var total = parseInt(jQuery('#gd_total', cont).val());
3150
    var processed = parseInt(jQuery('#gd_processed', cont).val());
3151
    var created = parseInt(jQuery('#gd_created', cont).val());
3152
    var updated = parseInt(jQuery('#gd_updated', cont).val());
3153
    var skipped = parseInt(jQuery('#gd_skipped', cont).val());
3154
    var invalid = parseInt(jQuery('#gd_invalid', cont).val());
3155
    var images = parseInt(jQuery('#gd_images', cont).val());
3156
    if (type=='post') {
3157
        var invalid_addr = parseInt(jQuery('#gd_invalid_addr', cont).val());
3158
    }
3159
3160
    var gdMsg = '<p></p>';
3161
    if ( processed > 0 ) {
3162
        var msgParse = '<p><?php echo addslashes( sprintf( __( 'Total %s item(s) found.', 'geodirectory' ), '%s' ) );?></p>';
3163
        msgParse = msgParse.replace("%s", processed);
3164
        gdMsg += msgParse;
3165
    }
3166
3167
    if ( updated > 0 ) {
3168
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) updated.', 'geodirectory' ), '%s', '%d' ) );?></p>';
3169
        msgParse = msgParse.replace("%s", updated);
3170
        msgParse = msgParse.replace("%d", processed);
3171
        gdMsg += msgParse;
3172
    }
3173
3174
    if ( created > 0 ) {
3175
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) added.', 'geodirectory' ), '%s', '%d' ) );?></p>';
3176
        msgParse = msgParse.replace("%s", created);
3177
        msgParse = msgParse.replace("%d", processed);
3178
        gdMsg += msgParse;
3179
    }
3180
3181
    if ( skipped > 0 ) {
3182
        var msgParse = '<p><?php echo addslashes( sprintf( __( '%s / %s item(s) ignored due to already exists.', 'geodirectory' ), '%s', '%d' ) );?></p>';
3183
        msgParse = msgParse.replace("%s", skipped);
3184
        msgParse = msgParse.replace("%d", processed);
3185
        gdMsg += msgParse;
3186
    }
3187
3188
    if ((type=='post' && invalid_addr > 0) || (type=='loc' && invalid > 0)) {
3189
        if (type=='loc') {
3190
            invalid_addr = invalid;
3191
        }
3192
        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>';
3193
        msgParse = msgParse.replace("%s", invalid_addr);
3194
        msgParse = msgParse.replace("%d", total);
3195
        gdMsg += msgParse;
3196
    }
3197
3198
    if (invalid > 0 && type!='loc') {
3199
        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>';
3200
        
3201
        if (type=='hood') {
3202
            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>';
3203
        }
3204
        msgParse = msgParse.replace("%s", invalid);
3205
        msgParse = msgParse.replace("%d", total);
3206
        gdMsg += msgParse;
3207
    }
3208
3209
    if (images > 0) {
3210
        gdMsg += '<p><?php echo addslashes( sprintf( CSV_TRANSFER_IMG_FOLDER, $uploads['subdir'] ) );?></p>';
3211
    }
3212
    gdMsg += '<p></p>';
3213
    jQuery('#gd-import-msg', cont).find('#message').removeClass('error').addClass('updated').html(gdMsg);
3214
    jQuery('#gd-import-msg', cont).show();
3215
    return;
3216
}
3217
3218
function gd_progressbar(el, value, label) {
3219
    var value = parseFloat(value);
3220
    if ( value <= 100 ) {
3221
        jQuery(el).find('#gd_progressbar').progressbar("value",value);
3222
        if (typeof label != 'undefined') {
3223
            jQuery(el).find('#gd_progressbar .gd-progress-label').html(label);
3224
        }
3225
    }
3226
}
3227
3228
jQuery(function(){
3229
    jQuery('.postbox.gd-hndle-pbox').addClass('closed');
3230
    jQuery('.gd-import-export .postbox .gd-hndle-click, .gd-import-export .postbox .button-link').click(function(e){
3231
        var $this = this;
3232
        var $postbox = jQuery($this).closest('.postbox');
3233
        
3234
        $postbox.toggleClass('closed');
3235
    });
3236
3237
    var intIp;
3238
    var intIc;
3239
3240
    jQuery(".gd-imex-pupload").click(function () {
3241
        var $this = this;
3242
        var $cont = jQuery($this).closest('.gd-imex-box');
3243
        clearInterval(intIp);
3244
        intIp = setInterval(function () {
3245
            if (jQuery($cont).find('.gd-imex-file').val()) {
3246
                jQuery($cont).find('.gd-imex-btns').show();
3247
            }
3248
        }, 1000);
3249
    });
3250
3251
    jQuery(".gd-imex-cupload").click(function () {
3252
        var $this = this;
3253
        var $cont = jQuery($this).closest('.gd-imex-box');
3254
        clearInterval(intIc);
3255
        intIc = setInterval(function () {
3256
            if (jQuery($cont).find('.gd-imex-file').val()) {
3257
                jQuery($cont).find('.gd-imex-btns').show();
3258
            }
3259
        }, 1000);
3260
    });
3261
                
3262
    jQuery('#gd_ie_imposts_sample').click(function(){
3263
        if (jQuery('#gd_ie_imposts_csv').val() != '') {
3264
            window.location.href = jQuery('#gd_ie_imposts_csv').val();
3265
            return false;
3266
        }
3267
    });
3268
3269
    jQuery('#gd_ie_imcats_sample').click(function(){
3270
        if (jQuery('#gd_ie_imcats_csv').val() != '') {
3271
            window.location.href = jQuery('#gd_ie_imcats_csv').val();
3272
            return false;
3273
        }
3274
    });
3275
3276
    jQuery('.gd-import-export .geodir_event_csv_download a').addClass('button-secondary');
3277
3278
    jQuery( '.gd_progressbar' ).each(function(){
3279
        jQuery(this).progressbar({value:0});
3280
    });
3281
3282
    var timer_posts;
3283
    var pseconds;
3284
    jQuery('#gd_ie_exposts_submit').click(function(){
3285
        pseconds = 1;
3286
        
3287
        var el = jQuery(this).closest('.postbox');
3288
        var post_type = jQuery(el).find('#gd_post_type').val();
3289
        if ( !post_type ) {
3290
            jQuery(el).find('#gd_post_type').focus();
3291
            return false;
3292
        }
3293
        window.clearInterval(timer_posts);
3294
        
3295
        jQuery(this).prop('disabled', true);
3296
        
3297
        timer_posts = window.setInterval( function() {
3298
            jQuery(el).find(".gd_timer").gdposts_timer();
3299
        }, 1000);
3300
        
3301
        var chunk_size = parseInt(jQuery('#gd_chunk_size', el).val());
3302
        var total_posts = parseInt(jQuery('option:selected', jQuery(el).find('#gd_post_type')).attr('data-posts'));
3303
        chunk_size = chunk_size < 50 || chunk_size > 100000 ? 5000 : chunk_size;
3304
        if (chunk_size > total_posts) {
3305
            chunk_size = total_posts;
3306
        }
3307
        var pages = Math.ceil( total_posts / chunk_size );
3308
        
3309
        gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, 1);
3310
    });
3311
3312
    jQuery.fn.gdposts_timer = function() {
3313
        pseconds++;
3314
        jQuery(this).text( pseconds.toString().toHMS() );
3315
    }
3316
3317
    var timer_cats;
3318
    var cseconds;
3319
    jQuery('#gd_ie_excats_submit').click(function(){
3320
        cseconds = 1;
3321
        
3322
        var el = jQuery(this).closest('.postbox');
3323
        var post_type = jQuery(el).find('#gd_post_type').val();
3324
        if ( !post_type ) {
3325
            jQuery(el).find('#gd_post_type').focus();
3326
            return false;
3327
        }
3328
        window.clearInterval(timer_cats);
3329
        
3330
        jQuery(this).prop('disabled', true);
3331
        
3332
        timer_cats = window.setInterval( function() {
3333
            jQuery(el).find(".gd_timer").gdcats_timer();
3334
        }, 1000);
3335
        
3336
        var chunk_size = parseInt(jQuery('#gd_chunk_size', el).val());
3337
        var total_cats = parseInt(jQuery('option:selected', jQuery(el).find('#gd_post_type')).attr('data-cats'));
3338
        chunk_size = chunk_size < 50 || chunk_size > 100000 ? 5000 : chunk_size;
3339
        if (chunk_size > total_cats) {
3340
            chunk_size = total_cats;
3341
        }
3342
        var pages = Math.ceil( total_cats / chunk_size );
3343
        
3344
        gd_process_export_cats(el, post_type, total_cats, chunk_size, pages, 1);
3345
    });
3346
3347
    jQuery.fn.gdcats_timer = function() {
3348
        cseconds++;
3349
        jQuery(this).text( cseconds.toString().toHMS() );
3350
    }
3351
3352
    String.prototype.toHMS = function () {
3353
        var sec_num = parseInt(this, 10); // don't forget the second param
3354
        var hours   = Math.floor(sec_num / 3600);
3355
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
3356
        var seconds = sec_num - (hours * 3600) - (minutes * 60);
3357
3358
        if (hours   < 10) {hours   = "0"+hours;}
3359
        if (minutes < 10) {minutes = "0"+minutes;}
3360
        if (seconds < 10) {seconds = "0"+seconds;}
3361
        var time    = hours+':'+minutes+':'+seconds;
3362
        return time;
3363
    }
3364
        
3365
    function gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, page) {
3366
        if (page < 2) {
3367
            gd_progressbar(el, 0, '0% (0 / ' + total_posts + ') <i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Exporting...', 'geodirectory' ) );?>');
3368
            jQuery(el).find('#gd_timer').text('00:00:01');
3369
            jQuery('#gd_ie_ex_files', el).html('');
3370
        }
3371
3372
        jQuery.ajax({
3373
            url: ajaxurl,
3374
            type: "POST",
3375
            data: 'action=geodir_import_export&task=export_posts&_pt=' + post_type + '&_n=' + chunk_size + '&_nonce=<?php echo $nonce;?>&_p=' + page,
3376
            dataType : 'json',
3377
            cache: false,
3378
            beforeSend: function (jqXHR, settings) {},
3379
            success: function( data ) {
3380
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3381
                
3382
                if (typeof data == 'object') {
3383
                    if (typeof data.error != 'undefined' && data.error) {
3384
                        gd_progressbar(el, 0, '<i class="fa fa-warning"></i>' + data.error);
3385
                        window.clearInterval(timer_posts);
3386
                    } else {
3387
                        if (pages < page || pages == page) {
3388
                            window.clearInterval(timer_posts);
3389
                            gd_progressbar(el, 100, '100% (' + total_posts + ' / ' + total_posts + ') <i class="fa fa-check"></i><?php echo esc_attr( __( 'Complete!', 'geodirectory' ) );?>');
3390
                        } else {
3391
                            var percentage = Math.round(((page * chunk_size) / total_posts) * 100);
3392
                            percentage = percentage > 100 ? 100 : percentage;
3393
                            gd_progressbar(el, percentage, '' + percentage + '% (' + ( page * chunk_size ) + ' / ' + total_posts + ') <i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Exporting...', 'geodirectory' ) );?>');
3394
                        }
3395
                        if (typeof data.files != 'undefined' && jQuery(data.files).length ) {
3396
                            var obj_files = data.files;
3397
                            var files = '';
3398
                            for (var i in data.files) {
3399
                                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>';
3400
                            }
3401
                            jQuery('#gd_ie_ex_files', el).append(files);
3402
                            if (pages > page) {
3403
                                return gd_process_export_posts(el, post_type, total_posts, chunk_size, pages, (page + 1));
3404
                            }
3405
                            return true;
3406
                        }
3407
                    }
3408
                }
3409
            },
3410
            error: function( data ) {
3411
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3412
                window.clearInterval(timer_posts);
3413
                return;
3414
            },
3415
            complete: function( jqXHR, textStatus  ) {
3416
                return;
3417
            }
3418
        });
3419
    }
3420
3421
    function gd_process_export_cats(el, post_type, total_cats, chunk_size, pages, page) {
3422
        if (page < 2) {
3423
            gd_progressbar(el, 0, '0% (0 / ' + total_cats + ') <i class="fa fa-refresh fa-spin"></i><?php echo esc_attr( __( 'Exporting...', 'geodirectory' ) );?>');
3424
            jQuery(el).find('#gd_timer').text('00:00:01');
3425
            jQuery('#gd_ie_ex_files', el).html('');
3426
        }
3427
3428
        jQuery.ajax({
3429
            url: ajaxurl,
3430
            type: "POST",
3431
            data: 'action=geodir_import_export&task=export_cats&_pt=' + post_type + '&_n=' + chunk_size + '&_nonce=<?php echo $nonce;?>&_p=' + page,
3432
            dataType : 'json',
3433
            cache: false,
3434
            beforeSend: function (jqXHR, settings) {},
3435
            success: function( data ) {
3436
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3437
                
3438
                if (typeof data == 'object') {
3439
                    if (typeof data.error != 'undefined' && data.error) {
3440
                        gd_progressbar(el, 0, '<i class="fa fa-warning"></i>' + data.error);
3441
                        window.clearInterval(timer_cats);
3442
                    } else {
3443
                        if (pages < page || pages == page) {
3444
                            window.clearInterval(timer_cats);
3445
                            gd_progressbar(el, 100, '100% (' + total_cats + ' / ' + total_cats + ') <i class="fa fa-check"></i><?php echo esc_attr( __( 'Complete!', 'geodirectory' ) );?>');
3446
                        } else {
3447
                            var percentage = Math.round(((page * chunk_size) / total_cats) * 100);
3448
                            percentage = percentage > 100 ? 100 : percentage;
3449
                            gd_progressbar(el, percentage, '' + percentage + '% (' + ( page * chunk_size ) + ' / ' + total_cats + ') <i class="fa fa-refresh fa-spin"></i><?php esc_attr_e( 'Exporting...', 'geodirectory' );?>');
3450
                        }
3451
                        if (typeof data.files != 'undefined' && jQuery(data.files).length ) {
3452
                            var obj_files = data.files;
3453
                            var files = '';
3454
                            for (var i in data.files) {
3455
                                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>';
3456
                            }
3457
                            jQuery('#gd_ie_ex_files', el).append(files);
3458
                            if (pages > page) {
3459
                                return gd_process_export_cats(el, post_type, total_cats, chunk_size, pages, (page + 1));
3460
                            }
3461
                            return true;
3462
                        }
3463
                    }
3464
                }
3465
            },
3466
            error: function( data ) {
3467
                jQuery(el).find('input[type="submit"]').prop('disabled', false);
3468
                window.clearInterval(timer_cats);
3469
                return;
3470
            },
3471
            complete: function( jqXHR, textStatus  ) {
3472
                return;
3473
            }
3474
        });
3475
    }
3476
});
3477
3478
function gd_imex_FinishImport(el, type) {
3479
    if (type=='post') {
3480
        jQuery.ajax({
3481
            url: ajaxurl,
3482
            type: "POST",
3483
            data: 'action=geodir_import_export&task=import_finish&_pt=' + type + '&_nonce=<?php echo $nonce; ?>',
3484
            dataType : 'json',
3485
            cache: false,
3486
            success: function (data) {
3487
                //import done
3488
            }
3489
        });
3490
    }
3491
}
3492
</script>
3493
<?php
3494 1
}
3495
3496
/**
3497
 * Initiate the WordPress file system and provide fallback if needed.
3498
 *
3499
 * @since 1.4.8
3500
 * @package GeoDirectory
3501
 * @return bool|string Returns the file system class on success. False on failure.
3502
 */
3503
function geodir_init_filesystem()
3504
{
3505
3506
    if(!function_exists('get_filesystem_method')){
3507
        require_once(ABSPATH."/wp-admin/includes/file.php");
3508
    }
3509
    $access_type = get_filesystem_method();
3510
    if ($access_type === 'direct') {
3511
        /* you can safely run request_filesystem_credentials() without any issues and don't need to worry about passing in a URL */
3512
        $creds = request_filesystem_credentials(trailingslashit(site_url()) . 'wp-admin/', '', false, false, array());
3513
3514
        /* initialize the API */
3515
        if (!WP_Filesystem($creds)) {
3516
            /* any problems and we exit */
3517
            //return '@@@3';
3518
            return false;
3519
        }
3520
3521
        global $wp_filesystem;
3522
        return $wp_filesystem;
3523
        /* do our file manipulations below */
3524
    } elseif (defined('FTP_USER')) {
3525
        $creds = request_filesystem_credentials(trailingslashit(site_url()) . 'wp-admin/', '', false, false, array());
3526
3527
        /* initialize the API */
3528
        if (!WP_Filesystem($creds)) {
3529
            /* any problems and we exit */
3530
            //return '@@@33';
3531
            return false;
3532
        }
3533
3534
        global $wp_filesystem;
3535
        //return '@@@1';
3536
        return $wp_filesystem;
3537
3538
    } else {
3539
        //return '@@@2';
3540
        /* don't have direct write access. Prompt user with our notice */
3541
        add_action('admin_notice', 'geodir_filesystem_notice');
3542
        return false;
3543
    }
3544
3545
}
3546
3547
3548
add_action('admin_init', 'geodir_filesystem_notice');
3549
3550
/**
3551
 * Output error message for file system access.
3552
 *
3553
 * Displays an admin message if the WordPress file system can't be automatically accessed. Called via admin_init hook.
3554
 *
3555
 * @since 1.4.8
3556
 * @since 1.4.9 Added check to not run function when doing ajax calls.
3557
 * @package GeoDirectory
3558
 */
3559
function geodir_filesystem_notice()
3560 1
{   if ( defined( 'DOING_AJAX' ) ){return;}
3561
    $access_type = get_filesystem_method();
3562
    if ($access_type === 'direct') {
3563
    } elseif (!defined('FTP_USER')) {
3564
        ?>
3565
        <div class="error">
3566
            <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'); ?>
3567
                <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>
3568
            </p>
3569
        </div>
3570
    <?php }
3571
}
3572
3573
3574
3575
/**
3576
 * Handle import/export for categories & listings.
3577
 *
3578
 * @since 1.4.6
3579
 * @since 1.5.4 Modified to add default category via csv import.
3580
 * @since 1.5.7 Modified to fix 504 Gateway Time-out for very large data.
3581
 * @package GeoDirectory
3582
 *
3583
 * @global object $wpdb WordPress Database object.
3584
 * @global string $plugin_prefix Geodirectory plugin table prefix.
3585
 * @global object $current_user Current user object.
3586
 * @global null|object $wp_filesystem WP_Filesystem object.
3587
 * @return string Json data.
3588
 */
3589
function geodir_ajax_import_export() {
3590
    global $wpdb, $plugin_prefix, $current_user, $wp_filesystem;
3591
    
3592
    error_reporting(0);
3593
3594
    // try to set higher limits for import
3595
    $max_input_time = ini_get('max_input_time');
3596
    $max_execution_time = ini_get('max_execution_time');
3597
    $memory_limit= ini_get('memory_limit');
3598
3599
    if(!$max_input_time || $max_input_time<3000){
3600
        ini_set('max_input_time', 3000);
3601
    }
3602
3603
    if(!$max_execution_time || $max_execution_time<3000){
3604
        ini_set('max_execution_time', 3000);
3605
    }
3606
3607
    if($memory_limit && str_replace('M','',$memory_limit)){
3608
        if(str_replace('M','',$memory_limit)<256){
3609
            ini_set('memory_limit', '256M');
3610
        }
3611
    }
3612
3613
    $json = array();
3614
3615
    if ( !current_user_can( 'manage_options' ) ) {
3616
        wp_send_json( $json );
3617
    }
3618
3619
    $task = isset( $_REQUEST['task'] ) ? $_REQUEST['task'] : NULL;
3620
    $nonce = isset( $_REQUEST['_nonce'] ) ? $_REQUEST['_nonce'] : NULL;
3621
    $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...
3622
3623
    if ( !wp_verify_nonce( $nonce, 'geodir_import_export_nonce' ) ) {
3624
        wp_send_json( $json );
3625
    }
3626
3627
    $post_type = isset( $_REQUEST['_pt'] ) ? $_REQUEST['_pt'] : NULL;
3628
    $chunk_per_page = isset( $_REQUEST['_n'] ) ? absint($_REQUEST['_n']) : NULL;
3629
    $chunk_per_page = $chunk_per_page < 50 || $chunk_per_page > 100000 ? 5000 : $chunk_per_page;
3630
    $chunk_page_no = isset( $_REQUEST['_p'] ) ? absint($_REQUEST['_p']) : 1;
3631
3632
    $wp_filesystem = geodir_init_filesystem();
3633
    if (!$wp_filesystem) {
3634
        $json['error'] = __( 'Filesystem ERROR: Could not access filesystem.', 'geodirectory' );
3635
        wp_send_json( $json );
3636
    }
3637
3638
    if (!empty($wp_filesystem) && isset($wp_filesystem->errors) && is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
3639
        $json['error'] = __( 'Filesystem ERROR: ' . $wp_filesystem->errors->get_error_message(), 'geodirectory' );
3640
        wp_send_json( $json );
3641
    }
3642
3643
    $csv_file_dir = geodir_path_import_export( false );
3644
    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...
3645
        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...
3646
            $json['error'] = __( 'ERROR: Could not create cache directory. This is usually due to inconsistent file permissions.', 'geodirectory' );
3647
            wp_send_json( $json );
3648
        }
3649
    }
3650
    
3651
    $location_manager = function_exists('geodir_location_plugin_activated') ? true : false; // Check location manager installed & active.
3652
    $neighbourhood_active = $location_manager && get_option('location_neighbourhoods') ? true : false;
3653
3654
    switch ( $task ) {
3655
        case 'export_posts': {
3656
            // WPML
3657
            $is_wpml = geodir_is_wpml();
3658
            if ($is_wpml) {
3659
                global $sitepress;
3660
                $active_lang = ICL_LANGUAGE_CODE;
3661
                
3662
                $sitepress->switch_lang('all', true);
3663
            }
3664
            // WPML
3665
            if ( $post_type == 'gd_event' ) {
3666
                add_filter( 'geodir_imex_export_posts_query', 'geodir_imex_get_events_query', 10, 2 );
3667
            }
3668
            $file_name = $post_type . '_' . date( 'dmyHi' );
3669
            $posts_count = geodir_get_posts_count( $post_type );
3670
            $file_url_base = geodir_path_import_export() . '/';
3671
            $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...
3672
            $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...
3673
            $file_path_temp = $csv_file_dir . '/' . $post_type . '_' . $nonce . '.csv';
3674
            
3675
            $chunk_file_paths = array();
3676
3677
            if ( isset( $_REQUEST['_st'] ) ) {
3678
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3679
                $percentage = count( $posts_count ) > 0 && $line_count > 0 ? ceil( $line_count / $posts_count ) * 100 : 0;
3680
                $percentage = min( $percentage, 100 );
3681
                
3682
                $json['percentage'] = $percentage;
3683
                // WPML
3684
                if ($is_wpml) {
3685
                    $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...
3686
                }
3687
                // WPML
3688
                wp_send_json( $json );
3689
                gd_die();
3690
            } else {
3691
                if ( !$posts_count > 0 ) {
3692
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3693
                } else {
3694
                    $total_posts = $posts_count;
3695
                    if ($chunk_per_page > $total_posts) {
3696
                        $chunk_per_page = $total_posts;
3697
                    }
3698
                    $chunk_total_pages = ceil( $total_posts / $chunk_per_page );
3699
                    
3700
                    $j = $chunk_page_no;
3701
                    $chunk_save_posts = geodir_imex_get_posts( $post_type, $chunk_per_page, $j );
3702
                    
3703
                    $per_page = 500;
3704
                    if ($per_page > $chunk_per_page) {
3705
                        $per_page = $chunk_per_page;
3706
                    }
3707
                    $total_pages = ceil( $chunk_per_page / $per_page );
3708
                    
3709
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3710
                        $save_posts = array_slice( $chunk_save_posts , ( $i * $per_page ), $per_page );
3711
                        
3712
                        $clear = $i == 0 ? true : false;
3713
                        geodir_save_csv_data( $file_path_temp, $save_posts, $clear );
3714
                    }
3715
                        
3716
                    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...
3717
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3718
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3719
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3720
                        $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...
3721
                        
3722
                        $file_url = $file_url_base . $chunk_file_name;
3723
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3724
                    }
3725
                    
3726
                    if ( !empty($chunk_file_paths) ) {
3727
                        $json['total'] = $posts_count;
3728
                        $json['files'] = $chunk_file_paths;
3729
                    } else {
3730
                        if ($j > 1) {
3731
                            $json['total'] = $posts_count;
3732
                            $json['files'] = array();
3733
                        } else {
3734
                            $json['error'] = __( 'ERROR: Could not create csv file. This is usually due to inconsistent file permissions.', 'geodirectory' );
3735
                        }
3736
                    }
3737
                }
3738
                // WPML
3739
                if ($is_wpml) {
3740
                    $sitepress->switch_lang($active_lang, true);
3741
                }
3742
                // WPML
3743
                wp_send_json( $json );
3744
            }
3745
        }
3746
        break;
3747
        case 'export_cats': {
3748
            // WPML
3749
            $is_wpml = geodir_is_wpml();
3750
            if ($is_wpml) {
3751
                global $sitepress;
3752
                $active_lang = ICL_LANGUAGE_CODE;
3753
                
3754
                $sitepress->switch_lang('all', true);
3755
            }
3756
            // WPML
3757
            $file_name = $post_type . 'category_' . date( 'dmyHi' );
3758
            
3759
            $terms_count = geodir_get_terms_count( $post_type );
3760
            $file_url_base = geodir_path_import_export() . '/';
3761
            $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...
3762
            $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...
3763
            $file_path_temp = $csv_file_dir . '/' . $post_type . 'category_' . $nonce . '.csv';
3764
            
3765
            $chunk_file_paths = array();
3766
            
3767
            if ( isset( $_REQUEST['_st'] ) ) {
3768
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3769
                $percentage = count( $terms_count ) > 0 && $line_count > 0 ? ceil( $line_count / $terms_count ) * 100 : 0;
3770
                $percentage = min( $percentage, 100 );
3771
                
3772
                $json['percentage'] = $percentage;
3773
                // WPML
3774
                if ($is_wpml) {
3775
                    $sitepress->switch_lang($active_lang, true);
3776
                }
3777
                // WPML
3778
                wp_send_json( $json );
3779
            } else {
3780
                if ( !$terms_count > 0 ) {
3781
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3782
                } else {
3783
                    $total_terms = $terms_count;
3784
                    if ($chunk_per_page > $terms_count) {
3785
                        $chunk_per_page = $terms_count;
3786
                    }
3787
                    $chunk_total_pages = ceil( $total_terms / $chunk_per_page );
3788
                    
3789
                    $j = $chunk_page_no;
3790
                    $chunk_save_terms = geodir_imex_get_terms( $post_type, $chunk_per_page, $j );
3791
                    
3792
                    $per_page = 500;
3793
                    if ($per_page > $chunk_per_page) {
3794
                        $per_page = $chunk_per_page;
3795
                    }
3796
                    $total_pages = ceil( $chunk_per_page / $per_page );
3797
                    
3798
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3799
                        $save_terms = array_slice( $chunk_save_terms , ( $i * $per_page ), $per_page );
3800
                        
3801
                        $clear = $i == 0 ? true : false;
3802
                        geodir_save_csv_data( $file_path_temp, $save_terms, $clear );
3803
                    }
3804
                    
3805
                    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...
3806
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3807
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3808
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3809
                        $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...
3810
                        
3811
                        $file_url = $file_url_base . $chunk_file_name;
3812
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3813
                    }
3814
                    
3815
                    if ( !empty($chunk_file_paths) ) {
3816
                        $json['total'] = $terms_count;
3817
                        $json['files'] = $chunk_file_paths;
3818
                    } else {
3819
                        $json['error'] = __( 'ERROR: Could not create csv file. This is usually due to inconsistent file permissions.', 'geodirectory' );
3820
                    }
3821
                }
3822
                // WPML
3823
                if ($is_wpml) {
3824
                    $sitepress->switch_lang($active_lang, true);
3825
                }
3826
                // WPML
3827
                wp_send_json( $json );
3828
            }
3829
        }
3830
        break;
3831 View Code Duplication
        case 'export_locations': {
3832
            $file_url_base = geodir_path_import_export() . '/';
3833
            $file_name = 'gd_locations_' . date( 'dmyHi' );
3834
            $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...
3835
            $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...
3836
            $file_path_temp = $csv_file_dir . '/gd_locations_' . $nonce . '.csv';
3837
            
3838
            $items_count = (int)geodir_location_imex_count_locations();
3839
            
3840
            if ( isset( $_REQUEST['_st'] ) ) {
3841
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3842
                $percentage = count( $items_count ) > 0 && $line_count > 0 ? ceil( $line_count / $items_count ) * 100 : 0;
3843
                $percentage = min( $percentage, 100 );
3844
                
3845
                $json['percentage'] = $percentage;
3846
                wp_send_json( $json );
3847
            } else {
3848
                $chunk_file_paths = array();
3849
                
3850
                if ( !$items_count > 0 ) {
3851
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3852
                } else {
3853
                    $chunk_per_page = min( $chunk_per_page, $items_count );
3854
                    $chunk_total_pages = ceil( $items_count / $chunk_per_page );
3855
                    
3856
                    $j = $chunk_page_no;
3857
                    $chunk_save_items = geodir_location_imex_locations_data( $chunk_per_page, $j );
3858
                    
3859
                    $per_page = 500;
3860
                    $per_page = min( $per_page, $chunk_per_page );
3861
                    $total_pages = ceil( $chunk_per_page / $per_page );
3862
                    
3863
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3864
                        $save_items = array_slice( $chunk_save_items , ( $i * $per_page ), $per_page );
3865
                        
3866
                        $clear = $i == 0 ? true : false;
3867
                        geodir_save_csv_data( $file_path_temp, $save_items, $clear );
3868
                    }
3869
                    
3870
                    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...
3871
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3872
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3873
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3874
                        $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...
3875
                        
3876
                        $file_url = $file_url_base . $chunk_file_name;
3877
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3878
                    }
3879
                    
3880
                    if ( !empty($chunk_file_paths) ) {
3881
                        $json['total'] = $items_count;
3882
                        $json['files'] = $chunk_file_paths;
3883
                    } else {
3884
                        $json['error'] = __( 'Fail, something wrong to create csv file.', 'geodirectory' );
3885
                    }
3886
                }
3887
                wp_send_json( $json );
3888
            }
3889
        }
3890
        break;
3891 View Code Duplication
        case 'export_hoods': {
3892
            $file_url_base = geodir_path_import_export() . '/';
3893
            $file_name = 'gd_neighbourhoods_' . date( 'dmyHi' );
3894
            $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...
3895
            $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...
3896
            $file_path_temp = $csv_file_dir . '/gd_neighbourhoods_' . $nonce . '.csv';
3897
            
3898
            $items_count = (int)geodir_location_imex_count_neighbourhoods();
3899
            
3900
            if ( isset( $_REQUEST['_st'] ) ) {
3901
                $line_count = (int)geodir_import_export_line_count( $file_path_temp );
3902
                $percentage = count( $items_count ) > 0 && $line_count > 0 ? ceil( $line_count / $items_count ) * 100 : 0;
3903
                $percentage = min( $percentage, 100 );
3904
                
3905
                $json['percentage'] = $percentage;
3906
                wp_send_json( $json );
3907
            } else {
3908
                $chunk_file_paths = array();
3909
                
3910
                if ( !$items_count > 0 ) {
3911
                    $json['error'] = __( 'No records to export.', 'geodirectory' );
3912
                } else {
3913
                    $chunk_per_page = min( $chunk_per_page, $items_count );
3914
                    $chunk_total_pages = ceil( $items_count / $chunk_per_page );
3915
                    
3916
                    $j = $chunk_page_no;
3917
                    $chunk_save_items = geodir_location_imex_neighbourhoods_data( $chunk_per_page, $j );
3918
                    
3919
                    $per_page = 500;
3920
                    $per_page = min( $per_page, $chunk_per_page );
3921
                    $total_pages = ceil( $chunk_per_page / $per_page );
3922
                    
3923
                    for ( $i = 0; $i <= $total_pages; $i++ ) {
3924
                        $save_items = array_slice( $chunk_save_items , ( $i * $per_page ), $per_page );
3925
                        
3926
                        $clear = $i == 0 ? true : false;
3927
                        geodir_save_csv_data( $file_path_temp, $save_items, $clear );
3928
                    }
3929
                    
3930
                    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...
3931
                        $chunk_page_no = $chunk_total_pages > 1 ? '-' . $j : '';
3932
                        $chunk_file_name = $file_name . $chunk_page_no . '.csv';
3933
                        $file_path = $csv_file_dir . '/' . $chunk_file_name;
3934
                        $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...
3935
                        
3936
                        $file_url = $file_url_base . $chunk_file_name;
3937
                        $chunk_file_paths[] = array('i' => $j . '.', 'u' => $file_url, 's' => size_format(filesize($file_path), 2));
3938
                    }
3939
                    
3940
                    if ( !empty($chunk_file_paths) ) {
3941
                        $json['total'] = $items_count;
3942
                        $json['files'] = $chunk_file_paths;
3943
                    } else {
3944
                        $json['error'] = __( 'Fail, something wrong to create csv file.', 'geodirectory' );
3945
                    }
3946
                }
3947
                wp_send_json( $json );
3948
            }
3949
        }
3950
        break;
3951
        case 'prepare_import':
3952
        case 'import_cat':
3953
        case 'import_post':
3954
        case 'import_loc':
3955
        case 'import_hood': {
3956
            // WPML
3957
            $is_wpml = geodir_is_wpml();
3958
            if ($is_wpml) {
3959
                global $sitepress;
3960
                $active_lang = ICL_LANGUAGE_CODE;
3961
            }
3962
            // WPML
3963
            
3964
            ini_set( 'auto_detect_line_endings', true );
3965
            
3966
            $uploads = wp_upload_dir();
3967
            $uploads_dir = $uploads['path'];
3968
            $uploads_subdir = $uploads['subdir'];
3969
            
3970
            $csv_file = isset( $_POST['_file'] ) ? $_POST['_file'] : NULL;
3971
            $import_choice = isset( $_REQUEST['_ch'] ) ? $_REQUEST['_ch'] : 'skip';
3972
            
3973
            $csv_file_arr = explode( '/', $csv_file );
3974
            $csv_filename = end( $csv_file_arr );
3975
            $target_path = $uploads_dir . '/temp_' . $current_user->data->ID . '/' . $csv_filename;
3976
            
3977
            $json['file'] = $csv_file;
3978
            $json['error'] = __( 'The uploaded file is not a valid csv file. Please try again.', 'geodirectory' );
3979
            $file = array();
3980
3981
            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...
3982
                $wp_filetype = wp_check_filetype_and_ext( $target_path, $csv_filename );
3983
                
3984
                if (!empty($wp_filetype) && isset($wp_filetype['ext']) && geodir_strtolower($wp_filetype['ext']) == 'csv') {
3985
                    $json['error'] = NULL;
3986
                    $json['rows'] = 0;
3987
                    
3988
                    if ( ( $handle = fopen($target_path, "r" ) ) !== FALSE ) {
3989
                        while ( ( $data = fgetcsv( $handle, 100000, "," ) ) !== FALSE ) {
3990
                            if ( !empty( $data ) ) {
3991
                                $file[] = $data;
3992
                            }
3993
                        }
3994
                        fclose($handle);
3995
                    }
3996
3997
                    $json['rows'] = (!empty($file) && count($file) > 1) ? count($file) - 1 : 0;
3998
                    
3999
                    if (!$json['rows'] > 0) {
4000
                        $json['error'] = __('No data found in csv file.', 'geodirectory');
4001
                    }
4002
                } else {
4003
                    wp_send_json( $json );
4004
                }
4005
            } else {
4006
                wp_send_json( $json );
4007
            }
4008
            
4009
            if ( $task == 'prepare_import' || !empty( $json['error'] ) ) {
4010
                wp_send_json( $json );
4011
            }
4012
            
4013
            $total = $json['rows'];
4014
            $limit = isset($_POST['limit']) ? (int)$_POST['limit'] : 1;
4015
            $processed = isset($_POST['processed']) ? (int)$_POST['processed'] : 0;
4016
            
4017
            $count = $limit;
4018
            
4019
            if ($count < $total) {
4020
                $count = $processed + $count;
4021
                if ($count > $total) {
4022
                    $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...
4023
                }
4024
            } else {
4025
                $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...
4026
            }
4027
            
4028
            $created = 0;
4029
            $updated = 0;
4030
            $skipped = 0;
4031
            $invalid = 0;
4032
            $invalid_addr = 0;
4033
            $images = 0;
4034
            
4035
            $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...
4036
            $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...
4037
            
4038
            $post_types = geodir_get_posttypes();
4039
4040
            if ( $task == 'import_cat' ) {
4041
                if (!empty($file)) {
4042
                    $columns = isset($file[0]) ? $file[0] : NULL;
4043
                    
4044 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4045
                        $json['error'] = CSV_INVAILD_FILE;
4046
                        wp_send_json( $json );
4047
                        exit;
4048
                    }
4049
                    
4050
                    $gd_error_log = __('GD IMPORT CATEGORIES [ROW %d]:', 'geodirectory');
4051
                    
4052
                    for ($i = 1; $i <= $limit; $i++) {
4053
                        $index = $processed + $i;
4054
                        
4055
                        if (isset($file[$index])) {
4056
                            $row = $file[$index];
4057
                            $row = array_map( 'trim', $row );
4058
                            //$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...
4059
                            
4060
                            $cat_id = '';
4061
                            $cat_name = '';
4062
                            $cat_slug = '';
4063
                            $cat_posttype = '';
4064
                            $cat_parent = '';
4065
                            $cat_description = '';
4066
                            $cat_schema = '';
4067
                            $cat_top_description = '';
4068
                            $cat_image = '';
4069
                            $cat_icon = '';
4070
                            $cat_language = '';
4071
                            $cat_id_original = '';
4072
                            
4073
                            $c = 0;
4074
                            foreach ($columns as $column ) {
4075
                                if ( $column == 'cat_id' ) {
4076
                                    $cat_id = (int)$row[$c];
4077
                                } else if ( $column == 'cat_name' ) {
4078
                                    $cat_name = $row[$c];
4079
                                } else if ( $column == 'cat_slug' ) {
4080
                                    $cat_slug = $row[$c];
4081
                                } else if ( $column == 'cat_posttype' ) {
4082
                                    $cat_posttype = $row[$c];
4083
                                } else if ( $column == 'cat_parent' ) {
4084
                                    $cat_parent = trim($row[$c]);
4085
                                } else if ( $column == 'cat_schema' && $row[$c] != '' ) {
4086
                                    $cat_schema = $row[$c];
4087
                                } else if ( $column == 'cat_description' ) {
4088
                                    $cat_description = $row[$c];
4089
                                } else if ( $column == 'cat_top_description' ) {
4090
                                    $cat_top_description = $row[$c];
4091
                                } else if ( $column == 'cat_image' ) {
4092
                                    $cat_image = $row[$c];
4093
                                } else if ( $column == 'cat_icon' ) {
4094
                                    $cat_icon = $row[$c];
4095
                                }
4096
                                // WPML
4097 View Code Duplication
                                if ( $is_wpml ) {
4098
                                    if ( $column == 'cat_language' ) {
4099
                                        $cat_language = geodir_strtolower( trim( $row[$c] ) );
4100
                                    } else if ( $column == 'cat_id_original' ) {
4101
                                        $cat_id_original = (int)$row[$c];
4102
                                    }
4103
                                }
4104
                                // WPML
4105
                                $c++;
4106
                            }
4107
                            
4108
                            if ( $cat_name == '' || !in_array( $cat_posttype, $post_types ) ) {
4109
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to blank title/invalid post type', 'geodirectory' ) );
4110
                                
4111
                                $invalid++;
4112
                                continue;
4113
                            }
4114
                            
4115
                            // WPML
4116
                            if ($is_wpml && $cat_language != '') {
4117
                                $sitepress->switch_lang($cat_language, true);
4118
                            }
4119
                            // WPML
4120
                                                        
4121
                            $term_data = array();
4122
                            $term_data['name'] = $cat_name;
4123
                            $term_data['slug'] = $cat_slug;
4124
                            $term_data['description'] = $cat_description;
4125
                            $term_data['cat_schema'] = $cat_schema;
4126
                            $term_data['top_description'] = $cat_top_description;
4127
                            $term_data['image'] = $cat_image != '' ? basename( $cat_image ) : '';
4128
                            $term_data['icon'] = $cat_icon != '' ? basename( $cat_icon ) : '';
4129
                            
4130
                            //$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...
4131
                            
4132
                            $taxonomy = $cat_posttype . 'category';
4133
                            
4134
                            $term_data['taxonomy'] = $taxonomy;
4135
4136
                            $term_parent_id = 0;
4137
                            if ($cat_parent != "" || (int)$cat_parent > 0) {
4138
                                $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...
4139
                                
4140
                                if ( $term_parent = get_term_by( 'name', $cat_parent, $taxonomy ) ) {
4141
                                    //
4142
                                } else if ( $term_parent = get_term_by( 'slug', $cat_parent, $taxonomy ) ) {
4143
                                    //
4144
                                } else if ( $term_parent = get_term_by( 'id', $cat_parent, $taxonomy ) ) {
4145
                                    //
4146
                                } else {
4147
                                    $term_parent_data = array();
4148
                                    $term_parent_data['name'] = $cat_parent;
4149
                                    //$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...
4150
                                    $term_parent_data['taxonomy'] = $taxonomy;
4151
                                    
4152
                                    $term_parent_id = (int)geodir_imex_insert_term( $taxonomy, $term_parent_data );
4153
                                }
4154
                                
4155
                                if ( !empty( $term_parent ) && !is_wp_error( $term_parent ) ) {
4156
                                    $term_parent_id = (int)$term_parent->term_id;
4157
                                }
4158
                            }
4159
                            $term_data['parent'] = (int)$term_parent_id;
4160
4161
                            $term_id = NULL;
4162
                            if ( $import_choice == 'update' ) {
4163
                                if ( $cat_id > 0 && $term = (array)term_exists( $cat_id, $taxonomy ) ) {
4164
                                    $term_data['term_id'] = $term['term_id'];
4165
                                    
4166 View Code Duplication
                                    if ( $term_id = geodir_imex_update_term( $taxonomy, $term_data ) ) {
4167
                                        $updated++;
4168
                                    } else {
4169
                                        $invalid++;
4170
                                        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' ) );
4171
                                    }
4172
                                } else if ( $term_data['slug'] != '' && $term = (array)term_exists( $term_data['slug'], $taxonomy ) ) {
4173
                                    $term_data['term_id'] = $term['term_id'];
4174
                                    
4175 View Code Duplication
                                    if ( $term_id = geodir_imex_update_term( $taxonomy, $term_data ) ) {
4176
                                        $updated++;
4177
                                    } else {
4178
                                        $invalid++;
4179
                                        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' ) );
4180
                                    }
4181 View Code Duplication
                                } else {
4182
                                    if ( $term_id = geodir_imex_insert_term( $taxonomy, $term_data ) ) {
4183
                                        $created++;
4184
                                    } else {
4185
                                        $invalid++;
4186
                                        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' ) );
4187
                                    }
4188
                                }
4189
                            } else if ( $import_choice == 'skip' ) {
4190
                                if ( $cat_id > 0 && $term = (array)term_exists( $cat_id, $taxonomy ) ) {
4191
                                    $skipped++;
4192
                                } else if ( $term_data['slug'] != '' && $term = (array)term_exists( $term_data['slug'], $taxonomy ) ) {
4193
                                    $skipped++;
4194 View Code Duplication
                                } else {
4195
                                    if ( $term_id = geodir_imex_insert_term( $taxonomy, $term_data ) ) {
4196
                                        $created++;
4197
                                    } else {
4198
                                        $invalid++;
4199
                                        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' ) );
4200
                                    }
4201
                                }
4202
                            } else {
4203
                                $invalid++;
4204
                                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' ) );
4205
                            }
4206
                            
4207
                            if ( $term_id ) {
4208
                                // WPML
4209 View Code Duplication
                                if ($is_wpml && $cat_id_original > 0 && $cat_language != '') {
4210
                                    $wpml_element_type = 'tax_' . $taxonomy;
4211
                                    $source_language = geodir_get_language_for_element( $cat_id_original, $wpml_element_type );
4212
                                    $source_language = $source_language != '' ? $source_language : $sitepress->get_default_language();
4213
4214
                                    $trid = $sitepress->get_element_trid( $cat_id_original, $wpml_element_type );
4215
                                    
4216
                                    $sitepress->set_element_language_details( $term_id, $wpml_element_type, $trid, $cat_language, $source_language );
4217
                                }
4218
                                // WPML
4219
                                
4220
                                if ( isset( $term_data['top_description'] ) ) {
4221
                                    update_tax_meta( $term_id, 'ct_cat_top_desc', $term_data['top_description'], $cat_posttype );
4222
                                }
4223
                                
4224
                                if ( isset( $term_data['cat_schema'] ) ) {
4225
                                    update_tax_meta( $term_id, 'ct_cat_schema', $term_data['cat_schema'], $cat_posttype );
4226
                                }
4227
            
4228
                                $attachment = false;
4229 View Code Duplication
                                if ( isset( $term_data['image'] ) && $term_data['image'] != '' ) {
4230
                                    $cat_image = geodir_get_default_catimage( $term_id, $cat_posttype );
4231
                                    $cat_image = !empty( $cat_image ) && isset( $cat_image['src'] ) ? $cat_image['src'] : '';
4232
                                    
4233
                                    if ( basename($cat_image) != $term_data['image'] ) {
4234
                                        $attachment = true;
4235
                                        update_tax_meta( $term_id, 'ct_cat_default_img', array( 'id' => 'image', 'src' => $uploads['url'] . '/' . $term_data['image'] ), $cat_posttype );
4236
                                    }
4237
                                }
4238
                                
4239 View Code Duplication
                                if ( isset( $term_data['icon'] ) && $term_data['icon'] != '' ) {
4240
                                    $cat_icon = get_tax_meta( $term_id, 'ct_cat_icon', false, $cat_posttype );
4241
                                    $cat_icon = !empty( $cat_icon ) && isset( $cat_icon['src'] ) ? $cat_icon['src'] : '';
4242
                                        
4243
                                    if ( basename($cat_icon) != $term_data['icon'] ) {
4244
                                        $attachment = true;
4245
                                        update_tax_meta( $term_id, 'ct_cat_icon', array( 'id' => 'icon', 'src' => $uploads['url'] . '/' . $term_data['icon'] ), $cat_posttype );
4246
                                    }
4247
                                }
4248
                                
4249
                                if ( $attachment ) {
4250
                                    $images++;
4251
                                }
4252
                            }
4253
                            
4254
                            // WPML
4255
                            if ($is_wpml && $cat_language != '') {
4256
                                $sitepress->switch_lang($active_lang, true);
4257
                            }
4258
                            // WPML
4259
                        }
4260
                    }
4261
                }
4262
                
4263
                $json = array();
4264
                $json['processed'] = $limit;
4265
                $json['created'] = $created;
4266
                $json['updated'] = $updated;
4267
                $json['skipped'] = $skipped;
4268
                $json['invalid'] = $invalid;
4269
                $json['images'] = $images;
4270
                
4271
                wp_send_json( $json );
4272
                exit;
4273
            } else if ( $task == 'import_post' ) {
4274
                //run some stuff to make the import quicker
4275
                wp_defer_term_counting( true );
4276
                wp_defer_comment_counting( true );
4277
                $wpdb->query( 'SET autocommit = 0;' );
4278
4279
                //remove_all_actions('publish_post');
4280
                //remove_all_actions('transition_post_status');
4281
                //remove_all_actions('publish_future_post');
4282
4283
                if (!empty($file)) {
4284
                    $wp_post_statuses = get_post_statuses(); // All of the WordPress supported post statuses.
4285
                    $default_status = 'publish';
4286
                    $current_date = date_i18n( 'Y-m-d', time() );
4287
                    
4288
                    $columns = isset($file[0]) ? $file[0] : NULL;
4289
                    
4290 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4291
                        $json['error'] = CSV_INVAILD_FILE;
4292
                        wp_send_json( $json );
4293
                        exit;
4294
                    }
4295
4296
                    $gd_error_log = __('GD IMPORT LISTINGS [ROW %d]:', 'geodirectory');
4297
                    $wp_chars_error = __( '(check & remove if any invalid characters used in data)', 'geodirectory' );
4298
                    $processed_actual = 0;
4299
                    for ($i = 1; $i <= $limit; $i++) {
4300
                        $index = $processed + $i;
4301
                        $gd_post = array();
4302
                        
4303
                        if (isset($file[$index])) {
4304
                            $processed_actual++;
4305
                            $row = $file[$index];
4306
                            $row = array_map( 'trim', $row );
4307
                            //$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...
4308
                            $row = array_map( 'addslashes_gpc', $row );
4309
                            
4310
                            $post_id = '';
4311
                            $post_title = '';
4312
                            $post_author = '';
4313
                            $post_content = '';
4314
                            $post_category_arr = array();
4315
                            $default_category = '';
4316
                            $post_tags = array();
4317
                            $post_type = '';
4318
                            $post_status = '';
4319
                            $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...
4320
                            $post_address = '';
4321
                            $post_city = '';
4322
                            $post_region = '';
4323
                            $post_country = '';
4324
                            $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...
4325
                            $post_latitude = '';
4326
                            $post_longitude = '';
4327
                            $post_neighbourhood = '';
4328
                            $neighbourhood_latitude = '';
4329
                            $neighbourhood_longitude = '';
4330
                            $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...
4331
                            $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...
4332
                            $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...
4333
                            $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...
4334
                            $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...
4335
                            $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...
4336
                            $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...
4337
                            $post_images = array();
4338
                            
4339
                            $expire_date = 'Never';
4340
                            
4341
                            $language = '';
4342
                            $original_post_id = '';
4343
                                                        
4344
                            $c = 0;
4345
                            foreach ($columns as $column ) {
4346
                                $gd_post[$column] = $row[$c];
4347
                                
4348
                                if ( $column == 'post_id' ) {
4349
                                    $post_id = $row[$c];
4350
                                } else if ( $column == 'post_title' ) {
4351
                                    $post_title = sanitize_text_field($row[$c]);
4352
                                } else if ( $column == 'post_author' ) {
4353
                                    $post_author = $row[$c];
4354
                                } else if ( $column == 'post_content' ) {
4355
                                    $post_content = $row[$c];
4356
                                } else if ( $column == 'post_category' && $row[$c] != '' ) {
4357
                                    $post_category_arr = explode( ',', $row[$c] );
4358
                                } else if ( $column == 'default_category' ) {
4359
                                    $default_category = wp_kses_normalize_entities($row[$c]);
4360
                                } else if ( $column == 'post_tags' && $row[$c] != '' ) {
4361
                                    $post_tags = explode( ',', sanitize_text_field($row[$c]) );
4362
                                } else if ( $column == 'post_type' ) {
4363
                                    $post_type = $row[$c];
4364
                                } else if ( $column == 'post_status' ) {
4365
                                    $post_status = sanitize_key( $row[$c] );
4366
                                } else if ( $column == 'is_featured' ) {
4367
                                    $is_featured = (int)$row[$c];
4368
                                } else if ( $column == 'geodir_video' ) {
4369
                                    $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...
4370
                                } else if ( $column == 'post_address' ) {
4371
                                    $post_address = sanitize_text_field($row[$c]);
4372
                                } else if ( $column == 'post_city' ) {
4373
                                    $post_city = sanitize_text_field($row[$c]);
4374
                                } else if ( $column == 'post_region' ) {
4375
                                    $post_region = sanitize_text_field($row[$c]);
4376
                                } else if ( $column == 'post_country' ) {
4377
                                    $post_country = sanitize_text_field($row[$c]);
4378
                                } else if ( $column == 'post_zip' ) {
4379
                                    $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...
4380
                                } else if ( $column == 'post_latitude' ) {
4381
                                    $post_latitude = sanitize_text_field($row[$c]);
4382
                                } else if ( $column == 'post_longitude' ) {
4383
                                    $post_longitude = sanitize_text_field($row[$c]);
4384
                                } else if ( $column == 'post_neighbourhood' ) {
4385
                                    $post_neighbourhood = sanitize_text_field($row[$c]);
4386
                                    unset($gd_post[$column]);
4387
                                } else if ( $column == 'neighbourhood_latitude' ) {
4388
                                    $neighbourhood_latitude = sanitize_text_field($row[$c]);
4389
                                } else if ( $column == 'neighbourhood_longitude' ) {
4390
                                    $neighbourhood_longitude = sanitize_text_field($row[$c]);
4391
                                } else if ( $column == 'geodir_timing' ) {
4392
                                    $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...
4393
                                } else if ( $column == 'geodir_contact' ) {
4394
                                    $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...
4395
                                } else if ( $column == 'geodir_email' ) {
4396
                                    $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...
4397
                                } else if ( $column == 'geodir_website' ) {
4398
                                    $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...
4399
                                } else if ( $column == 'geodir_twitter' ) {
4400
                                    $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...
4401
                                } else if ( $column == 'geodir_facebook' ) {
4402
                                    $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...
4403
                                } else if ( $column == 'geodir_twitter' ) {
4404
                                    $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...
4405
                                } else if ( $column == 'IMAGE' && !empty( $row[$c] ) && $row[$c] != '' ) {
4406
                                    $post_images[] = $row[$c];
4407
                                } else if ( $column == 'alive_days' && (int)$row[$c] > 0 ) {
4408
                                    $expire_date = date_i18n( 'Y-m-d', strtotime( $current_date . '+' . (int)$row[$c] . ' days' ) );
4409
                                } else if ( $column == 'expire_date' && $row[$c] != '' && geodir_strtolower($row[$c]) != 'never' ) {
4410
                                    $row[$c] = str_replace('/', '-', $row[$c]);
4411
                                    $expire_date = date_i18n( 'Y-m-d', strtotime( $row[$c] ) );
4412
                                }
4413
                                // WPML
4414
                                if ($is_wpml) {
4415 View Code Duplication
                                    if ($column == 'language') {
4416
                                        $language = geodir_strtolower(trim($row[$c]));
4417
                                    } else if ($column == 'original_post_id') {
4418
                                        $original_post_id = (int)$row[$c];
4419
                                    }
4420
                                }
4421
                                // WPML
4422
                                $c++;
4423
                            }
4424
                            
4425
                            // WPML
4426
                            if ($is_wpml && $language != '') {
4427
                                $sitepress->switch_lang($language, true);
4428
                            }
4429
                            // WPML
4430
4431
                            $gd_post['IMAGE'] = $post_images;
4432
                            
4433
                            $post_status = !empty( $post_status ) ? sanitize_key( $post_status ) : $default_status;
4434
                            $post_status = !empty( $wp_post_statuses ) && !isset( $wp_post_statuses[$post_status] ) ? $default_status : $post_status;
4435
                                                                                                                
4436
                            $valid = true;
4437
                            
4438
                            if ( $post_title == '' || !in_array( $post_type, $post_types ) ) {
4439
                                $invalid++;
4440
                                $valid = false;
4441
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . __( 'Could not be added due to blank title/invalid post type', 'geodirectory' ) );
4442
                            }
4443
                            
4444
                            $location_allowed = function_exists( 'geodir_cpt_no_location' ) && geodir_cpt_no_location( $post_type ) ? false : true;
4445
                            if ( $location_allowed ) {
4446
                                $location_result = geodir_get_default_location();
4447
                                if ( $post_address == '' || $post_city == '' || $post_region == '' || $post_country == '' || $post_latitude == '' || $post_longitude == '' ) {
4448
                                    $invalid_addr++;
4449
                                    $valid = false;
4450
                                    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' ) );
4451
                                } else if ( !empty( $location_result ) && $location_result->location_id == 0 ) {
4452
                                    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 ) ) ) {
4453
                                        $invalid_addr++;
4454
                                        $valid = false;
4455
                                        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' ) );
4456
                                    } else {
4457
                                        if (!$location_manager) {
4458
                                            $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.
4459
                                        }
4460
                                    }
4461
                                }
4462
                            }
4463
                            
4464
                            if ( !$valid ) {
4465
                                continue;
4466
                            }
4467
4468
                            $cat_taxonomy = $post_type . 'category';
4469
                            $tags_taxonomy = $post_type . '_tags';
4470
                            
4471
                            if ($default_category != '' && !in_array($default_category, $post_category_arr)) {
4472
                                $post_category_arr = array_merge(array($default_category), $post_category_arr);
4473
                            }
4474
4475
                            $post_category = array();
4476
                            $default_category_id = NULL;
4477
                            if ( !empty( $post_category_arr ) ) {
4478
                                foreach ( $post_category_arr as $value ) {
4479
                                    $category_name = wp_kses_normalize_entities( trim( $value ) );
4480
                                    
4481
                                    if ( $category_name != '' ) {
4482
                                        $term_category = array();
4483
                                        
4484
                                        if ( $term = get_term_by( 'name', $category_name, $cat_taxonomy ) ) {
4485
                                            $term_category = $term;
4486
                                        } else if ( $term = get_term_by( 'slug', $category_name, $cat_taxonomy ) ) {
4487
                                            $term_category = $term;
4488
                                        } else {
4489
                                            $term_data = array();
4490
                                            $term_data['name'] = $category_name;
4491
                                            $term_data['taxonomy'] = $cat_taxonomy;
4492
                                            
4493
                                            $term_id = geodir_imex_insert_term( $cat_taxonomy, $term_data );
4494
                                            if ( $term_id ) {
4495
                                                $term_category = get_term( $term_id, $cat_taxonomy );
4496
                                            }
4497
                                        }
4498
                                        
4499
                                        if ( !empty( $term_category ) && !is_wp_error( $term_category ) ) {
4500
                                            $post_category[] = intval($term_category->term_id);
4501
                                            
4502
                                            if ($category_name == $default_category) {
4503
                                                $default_category_id = intval($term_category->term_id);
4504
                                            }
4505
                                        }
4506
                                    }
4507
                                }
4508
                            }
4509
4510
                            $save_post = array();
4511
                            $save_post['post_title'] = $post_title;
4512
                            $save_post['post_content'] = $post_content;
4513
                            $save_post['post_type'] = $post_type;
4514
                            $save_post['post_author'] = $post_author;
4515
                            $save_post['post_status'] = $post_status;
4516
                            $save_post['post_category'] = $post_category;
4517
                            $save_post['post_tags'] = $post_tags;
4518
4519
                            $saved_post_id = NULL;
4520
                            if ( $import_choice == 'update' ) {
4521
                                $gd_wp_error = __( 'Unable to add listing, please check the listing data.', 'geodirectory' );
4522
                                
4523
                                if ( $post_id > 0 && get_post( $post_id ) ) {
4524
                                    $save_post['ID'] = $post_id;
4525
                                    
4526 View Code Duplication
                                    if ( $saved_post_id = wp_update_post( $save_post, true ) ) {
4527
                                        if ( is_wp_error( $saved_post_id ) ) {
4528
                                            $gd_wp_error = $saved_post_id->get_error_message() . ' ' . $wp_chars_error;
4529
                                            $saved_post_id = 0;
4530
                                        } else {
4531
                                            $saved_post_id = $post_id;
4532
                                            $updated++;
4533
                                        }
4534
                                    }
4535 View Code Duplication
                                } else {
4536
                                    if ( $saved_post_id = wp_insert_post( $save_post, true ) ) {
4537
                                        if ( is_wp_error( $saved_post_id ) ) {
4538
                                            $gd_wp_error = $saved_post_id->get_error_message() . ' ' . $wp_chars_error;
4539
                                            $saved_post_id = 0;
4540
                                        } else {
4541
                                            $created++;
4542
                                        }
4543
                                    }
4544
                                }
4545
                                
4546
                                if ( !$saved_post_id > 0 ) {
4547
                                    $invalid++;
4548
                                    geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_wp_error );
4549
                                }
4550
                            } else if ( $import_choice == 'skip' ) {
4551
                                if ( $post_id > 0 && get_post( $post_id ) ) {
4552
                                    $skipped++;	
4553
                                } else {
4554
                                    if ( $saved_post_id = wp_insert_post( $save_post, true ) ) {
4555
                                        if ( is_wp_error( $saved_post_id ) ) {
4556
                                            $invalid++;
4557
                                            
4558
                                            geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $saved_post_id->get_error_message() . ' ' . $wp_chars_error );
4559
                                            $saved_post_id = 0;
4560
                                        } else {
4561
                                            $created++;
4562
                                        }
4563
                                    } else {
4564
                                        $invalid++;
4565
                                        
4566
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $wp_chars_error );
4567
                                    }
4568
                                }
4569
                            } else {
4570
                                $invalid++;
4571
                                
4572
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $wp_chars_error );
4573
                            }
4574
4575
                            if ( (int)$saved_post_id > 0 ) {
4576
                                // WPML
4577 View Code Duplication
                                if ($is_wpml && $original_post_id > 0 && $language != '') {
4578
                                    $wpml_post_type = 'post_' . $post_type;
4579
                                    $source_language = geodir_get_language_for_element( $original_post_id, $wpml_post_type );
4580
                                    $source_language = $source_language != '' ? $source_language : $sitepress->get_default_language();
4581
4582
                                    $trid = $sitepress->get_element_trid( $original_post_id, $wpml_post_type );
4583
                                    
4584
                                    $sitepress->set_element_language_details( $saved_post_id, $wpml_post_type, $trid, $language, $source_language );
4585
                                }
4586
                                // WPML
4587
                                $gd_post_info = geodir_get_post_info( $saved_post_id );
4588
                                
4589
                                $gd_post['post_id'] = $saved_post_id;
4590
                                $gd_post['ID'] = $saved_post_id;
4591
                                $gd_post['post_tags'] = $post_tags;
4592
                                $gd_post['post_title'] = $post_title;
4593
                                $gd_post['post_status'] = $post_status;
4594
                                $gd_post['submit_time'] = time();
4595
                                $gd_post['submit_ip'] = $_SERVER['REMOTE_ADDR'];
4596
                                                    
4597
                                // post location
4598
                                $post_location_id = 0;
4599
                                if ( $location_allowed && !empty( $location_result ) && $location_result->location_id > 0 ) {
4600
                                    $gd_post['post_neighbourhood'] = '';
4601
                                    
4602
                                    $post_location_info = array(
4603
                                                                'city' => $post_city,
4604
                                                                'region' => $post_region,
4605
                                                                'country' => $post_country,
4606
                                                                'geo_lat' => $post_latitude,
4607
                                                                'geo_lng' => $post_longitude
4608
                                                            );
4609
                                    if ( $location_id = (int)geodir_add_new_location( $post_location_info ) ) {
4610
                                        $post_location_id = $location_id;
4611
                                    }
4612
                                    
4613
                                    if ($post_location_id > 0 && $neighbourhood_active && !empty($post_neighbourhood)) {
4614
                                        $neighbourhood_info = geodir_location_neighbourhood_by_name_loc_id($post_neighbourhood, $post_location_id);
4615
4616
                                        $hood_data = array();
4617
                                        $hood_data['hood_location_id'] = $post_location_id;
4618
                                        $hood_data['hood_name'] = $post_neighbourhood;
4619
                                        
4620
                                        if (!empty($neighbourhood_info)) {
4621
                                            $hood_data['hood_id'] = $neighbourhood_info->hood_id;
4622
                                            $hood_data['hood_slug'] = $neighbourhood_info->hood_slug;
4623
                                            
4624
                                            if (empty($neighbourhood_latitude) || empty($neighbourhood_longitude)) {
4625
                                                $neighbourhood_latitude = $neighbourhood_info->hood_latitude;
4626
                                                $neighbourhood_longitude = $neighbourhood_info->hood_longitude;
4627
                                            }
4628
                                        }
4629
                                        
4630
                                        if (empty($neighbourhood_latitude) || empty($neighbourhood_longitude)) {
4631
                                            $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...
4632
                                            $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...
4633
                                        }
4634
                                        
4635
                                        $hood_data['hood_latitude'] = $post_latitude;
4636
                                        $hood_data['hood_longitude'] = $post_longitude;
4637
4638
                                        $neighbourhood_info = geodir_location_insert_update_neighbourhood($hood_data);
4639
                                        if (!empty($neighbourhood_info) && isset($neighbourhood_info->hood_slug)) {
4640
                                            $gd_post['post_neighbourhood'] = $neighbourhood_info->hood_slug;
4641
                                        }
4642
                                    }
4643
                                }
4644
                                $gd_post['post_location_id'] = $post_location_id;
4645
                                
4646
                                // post package info
4647
                                $package_id = isset( $gd_post['package_id'] ) && !empty( $gd_post['package_id'] ) ? (int)$gd_post['package_id'] : 0;
4648
                                if (!$package_id && !empty($gd_post_info) && isset($gd_post_info->package_id) && $gd_post_info->package_id) {
4649
                                    $package_id = $gd_post_info->package_id;
4650
                                }
4651
                                
4652
                                $package_info = array();
4653
                                if ($package_id && function_exists('geodir_get_package_info_by_id')) {
4654
                                    $package_info = (array)geodir_get_package_info_by_id($package_id);
4655
                                    
4656
                                    if (!(!empty($package_info) && isset($package_info['post_type']) && $package_info['post_type'] == $post_type)) {
4657
                                        $package_info = array();
4658
                                    }
4659
                                }
4660
                                
4661
                                if (empty($package_info)) {
4662
                                    $package_info = (array)geodir_post_package_info( array(), '', $post_type );
4663
                                }
4664
                                 
4665
                                if (!empty($package_info))	 {
4666
                                    $package_id = $package_info['pid'];
4667
                                    
4668
                                    if (isset($gd_post['alive_days']) || isset($gd_post['expire_date'])) {
4669
                                        $gd_post['expire_date'] = $expire_date;
4670
                                    } else {
4671
                                        if ( isset( $package_info['days'] ) && (int)$package_info['days'] > 0 ) {
4672
                                            $gd_post['alive_days'] = (int)$package_info['days'];
4673
                                            $gd_post['expire_date'] = date_i18n( 'Y-m-d', strtotime( $current_date . '+' . (int)$package_info['days'] . ' days' ) );
4674
                                        } else {
4675
                                            $gd_post['expire_date'] = 'Never';
4676
                                        }
4677
                                    }
4678
                                    
4679
                                    $gd_post['package_id'] = $package_id;
4680
                                }
4681
4682
                                $table = $plugin_prefix . $post_type . '_detail';
4683
                                
4684
                                if ($post_type == 'gd_event') {
4685
                                    $gd_post = geodir_imex_process_event_data($gd_post);
4686
                                }
4687
                                
4688
                                if (isset($gd_post['post_id'])) {
4689
                                    unset($gd_post['post_id']);
4690
                                }
4691
4692
                                // Export franchise fields
4693
                                $is_franchise_active = is_plugin_active( 'geodir_franchise/geodir_franchise.php' ) && geodir_franchise_enabled( $post_type ) ? true : false;
4694
                                if ($is_franchise_active) {
4695
                                    if ( isset( $gd_post['gd_is_franchise'] ) && (int)$gd_post['gd_is_franchise'] == 1 ) {
4696
                                        $gd_franchise_lock = array();
4697
                                        
4698
                                        if ( isset( $gd_post['gd_franchise_lock'] ) ) {
4699
                                            $gd_franchise_lock = str_replace(" ", "", $gd_post['gd_franchise_lock'] );
4700
                                            $gd_franchise_lock = trim( $gd_franchise_lock );
4701
                                            $gd_franchise_lock = explode( ",", $gd_franchise_lock );
4702
                                        }
4703
                                        
4704
                                        update_post_meta( $saved_post_id, 'gd_is_franchise', 1 );
4705
                                        update_post_meta( $saved_post_id, 'gd_franchise_lock', $gd_franchise_lock );
4706
                                    } else {
4707
                                        if ( isset( $gd_post['franchise'] ) && (int)$gd_post['franchise'] > 0 && geodir_franchise_check( (int)$gd_post['franchise'] ) ) {
4708
                                            geodir_save_post_meta( $saved_post_id, 'franchise', (int)$gd_post['franchise'] );
4709
                                        }
4710
                                    }
4711
                                }
4712
                                
4713
                                if (!empty($save_post['post_category']) && is_array($save_post['post_category'])) {
4714
                                    $save_post['post_category'] = array_unique( array_map( 'intval', $save_post['post_category'] ) );
4715
                                    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...
4716
                                        $save_post['post_default_category'] = $default_category_id;
4717
                                        $gd_post['default_category'] = $default_category_id;
4718
                                    }
4719
                                    $gd_post[$cat_taxonomy] = $save_post['post_category'];
4720
                                }
4721
                                
4722
                                // Save post info
4723
                                geodir_save_post_info( $saved_post_id, $gd_post );
4724
                                // post taxonomies
4725
                                if ( !empty( $save_post['post_category'] ) ) {
4726
                                    wp_set_object_terms( $saved_post_id, $save_post['post_category'], $cat_taxonomy );
4727
                                    
4728
                                    $post_default_category = isset( $save_post['post_default_category'] ) ? $save_post['post_default_category'] : '';
4729
                                    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...
4730
                                        $post_default_category = $default_category_id;
4731
                                    }
4732
                                    $post_cat_ids = geodir_get_post_meta($saved_post_id, $cat_taxonomy);
4733
                                    $save_post['post_category'] = !empty($post_cat_ids) ? explode(",", trim($post_cat_ids, ",")) : $save_post['post_category'];
4734
                                    $post_category_str = !empty($save_post['post_category']) ? implode(",y:#", $save_post['post_category']) . ',y:' : '';
4735
                                    
4736
                                    if ($post_category_str != '' && $post_default_category) {
4737
                                        $post_category_str = str_replace($post_default_category . ',y:', $post_default_category . ',y,d:', $post_category_str);
4738
                                    }
4739
                                    
4740
                                    $post_category_str = $post_category_str != '' ? array($cat_taxonomy => $post_category_str) : '';
4741
                                    
4742
                                    geodir_set_postcat_structure( $saved_post_id, $cat_taxonomy, $post_default_category, $post_category_str );
4743
                                }
4744
4745
                                if ( !empty( $save_post['post_tags'] ) ) {
4746
                                    wp_set_object_terms( $saved_post_id, $save_post['post_tags'], $tags_taxonomy );
4747
                                }
4748
4749
                                // Post images
4750
                                if ( !empty( $post_images ) ) {
4751
                                    $post_images = array_unique($post_images);
4752
                                    
4753
                                    $old_post_images_arr = array();
4754
                                    $saved_post_images_arr = array();
4755
                                    
4756
                                    $order = 1;
4757
                                    
4758
                                    $old_post_images = geodir_get_images( $saved_post_id );
4759
                                    if (!empty($old_post_images)) {
4760
                                        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...
4761
                                            if (!empty($old_post_image) && isset($old_post_image->file) && $old_post_image->file != '') {
4762
                                                $old_post_images_arr[] = $old_post_image->file;
4763
                                            }
4764
                                        }
4765
                                    }
4766
                                    
4767
                                    foreach ( $post_images as $post_image ) {
4768
                                        $image_name = basename( $post_image );
4769
                                        $saved_post_images_arr[] = $image_name;
4770
                                        
4771
                                        if (!empty($old_post_images_arr) && in_array( $image_name, $old_post_images_arr) ) {
4772
                                            continue; // Skip if image already exists.
4773
                                        }
4774
                                        
4775
                                        $image_name_parts = explode( '.', $image_name );
4776
                                        array_pop( $image_name_parts );
4777
                                        $proper_image_name = implode( '.', $image_name_parts );
4778
                                        
4779
                                        $arr_file_type = wp_check_filetype( $image_name );
4780
                                        
4781
                                        if ( !empty( $arr_file_type ) ) {
4782
                                            $uploaded_file_type = $arr_file_type['type'];
4783
                                            
4784
                                            $attachment = array();
4785
                                            $attachment['post_id'] = $saved_post_id;
4786
                                            $attachment['title'] = $proper_image_name;
4787
                                            $attachment['content'] = '';
4788
                                            $attachment['file'] = $uploads_subdir . '/' . $image_name;
4789
                                            $attachment['mime_type'] = $uploaded_file_type;
4790
                                            $attachment['menu_order'] = $order;
4791
                                            $attachment['is_featured'] = 0;
4792
4793
                                            $attachment_set = '';
4794
                                            foreach ( $attachment as $key => $val ) {
4795
                                                if ( $val != '' ) {
4796
                                                    $attachment_set .= $key . " = '" . $val . "', ";
4797
                                                }
4798
                                            }
4799
                                            $attachment_set = trim( $attachment_set, ", " );
4800
                                                                                        
4801
                                            // Add new attachment
4802
                                            $wpdb->query( "INSERT INTO " . GEODIR_ATTACHMENT_TABLE . " SET " . $attachment_set );
4803
                                                                                        
4804
                                            $order++;
4805
                                        }
4806
                                    }
4807
4808
                                    $saved_post_images_sql = !empty($saved_post_images_arr) ? " AND ( file NOT LIKE '%/" . implode("' AND file NOT LIKE '%/",  $saved_post_images_arr) . "' )" : '';
4809
                                    // Remove previous attachment
4810
                                    $wpdb->query( "DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id = " . (int)$saved_post_id . " " . $saved_post_images_sql );
4811
                                    
4812
                                    if ( !empty( $saved_post_images_arr ) ) {
4813
                                        $menu_order = 1;
4814
                                        
4815
                                        foreach ( $saved_post_images_arr as $img_name ) {
4816
                                            $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 ) ) );
4817
                                            
4818
                                            if( $menu_order == 1 ) {
4819
                                                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 ) ) ) ) {
4820
                                                    $wpdb->query( $wpdb->prepare( "UPDATE " . $table . " SET featured_image = %s WHERE post_id =%d", array( $featured_image, $saved_post_id ) ) );
4821
                                                }
4822
                                            }
4823
                                            $menu_order++;
4824
                                        }
4825
                                    }
4826
                                    
4827
                                    if ( $order > 1 ) {
4828
                                        $images++;
4829
                                    }
4830
                                }
4831
4832
                                /** This action is documented in geodirectory-functions/post-functions.php */
4833
                                do_action( 'geodir_after_save_listing', $saved_post_id, $gd_post );
4834
                                
4835
                                if (isset($is_featured)) {
4836
                                    geodir_save_post_meta($saved_post_id, 'is_featured', $is_featured);
4837
                                }
4838
                                if (isset($gd_post['expire_date'])) {
4839
                                    geodir_save_post_meta($saved_post_id, 'expire_date', $gd_post['expire_date']);
4840
                                }
4841
                            }
4842
                            
4843
                            // WPML
4844
                            if ($is_wpml && $language != '') {
4845
                                $sitepress->switch_lang($active_lang, true);
4846
                            }
4847
                            // WPML
4848
                        }
4849
                    }
4850
                }
4851
4852
                //undo some stuff to make the import quicker
4853
                wp_defer_term_counting( false );
4854
                wp_defer_comment_counting( false );
4855
                $wpdb->query( 'COMMIT;' );
4856
                $wpdb->query( 'SET autocommit = 1;' );
4857
4858
                $json = array();
4859
                $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...
4860
                $json['created'] = $created;
4861
                $json['updated'] = $updated;
4862
                $json['skipped'] = $skipped;
4863
                $json['invalid'] = $invalid;
4864
                $json['invalid_addr'] = $invalid_addr;
4865
                $json['images'] = $images;
4866
                
4867
                wp_send_json( $json );
4868
                exit;
4869
            } else if ( $task == 'import_loc' ) {
4870
                global $gd_post_types;
4871
                $gd_post_types = $post_types;
4872
                
4873
                if (!empty($file)) {
4874
                    $columns = isset($file[0]) ? $file[0] : NULL;
4875
                    
4876 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4877
                        $json['error'] = __('File you are uploading is not valid. Columns does not matching.', 'geodirectory');
4878
                        wp_send_json( $json );
4879
                    }
4880
                    
4881
                    $gd_error_log = __('GD IMPORT LOCATIONS [ROW %d]:', 'geodirectory');
4882
                    $gd_error_location = __( 'Could not be saved due to blank/invalid address(city, region, country, latitude, longitude)', 'geodirectory' );
4883
                    for ($i = 1; $i <= $limit; $i++) {
4884
                        $index = $processed + $i;
4885
                        
4886
                        if (isset($file[$index])) {
4887
                            $row = $file[$index];
4888
                            $row = array_map( 'trim', $row );
4889
                            $data = array();
4890
                            
4891
                            foreach ($columns as $c => $column ) {
4892
                                if (in_array($column, array('location_id', 'latitude', 'longitude', 'city', 'city_slug', 'region', 'country', 'city_meta', 'city_desc', 'region_meta', 'region_desc', 'country_meta', 'country_desc'))) {
4893
                                    $data[$column] = $row[$c];
4894
                                }
4895
                            }
4896
4897
                            if ( empty($data['city']) || empty($data['region']) || empty($data['country']) || empty($data['latitude']) || empty($data['longitude']) ) {
4898
                                $invalid++;
4899
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4900
                                continue;
4901
                            }
4902
                            
4903
                            $data['location_id'] = isset($data['location_id']) ? absint($data['location_id']) : 0;
4904
                            
4905
                            if ( $import_choice == 'update' ) {
4906
                                if ( (int)$data['location_id'] > 0 && $location = geodir_get_location_by_id( '', (int)$data['location_id'] ) ) {
4907
                                    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...
4908
                                        $updated++;
4909
                                    } else {
4910
                                        $invalid++;
4911
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4912
                                    }
4913
                                } else if ( !empty( $data['city_slug'] ) && $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'] ) ) ) {
4914
                                    $data['location_id'] = (int)$location->location_id;
4915
                                    
4916
                                    if ( $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'], 'country' => $data['country'], 'region' => $data['region'] ) ) ) {
4917
                                        $data['location_id'] = (int)$location->location_id;
4918
                                    } else if ( $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'], 'region' => $data['region'] ) ) ) {
4919
                                        $data['location_id'] = (int)$location->location_id;
4920
                                    } else if ( $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'], 'country' => $data['country'] ) ) ) {
4921
                                        $data['location_id'] = (int)$location->location_id;
4922
                                    }
4923
                                    
4924
                                    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...
4925
                                        $updated++;
4926
                                    } else {
4927
                                        $invalid++;
4928
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4929
                                    }
4930
                                } else {
4931
                                    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...
4932
                                        $created++;
4933
                                    } else {
4934
                                        $invalid++;
4935
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4936
                                    }
4937
                                }
4938 View Code Duplication
                            } elseif ( $import_choice == 'skip' ) {
4939
                                if ( (int)$data['location_id'] > 0 && $location = geodir_get_location_by_id( '', (int)$data['location_id'] ) ) {
4940
                                    $skipped++;
4941
                                } else if ( !empty( $data['city_slug'] ) && $location = geodir_get_location_by_slug( 'city', array( 'city_slug' => $data['city_slug'] ) ) ) {
4942
                                    $skipped++;
4943
                                } else {
4944
                                    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...
4945
                                        $created++;
4946
                                    } else {
4947
                                        $invalid++;
4948
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4949
                                    }
4950
                                }
4951
                            } else {
4952
                                $invalid++;
4953
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_location );
4954
                            }
4955
                        }
4956
                    }
4957
                }
4958
                
4959
                $json = array();
4960
                $json['processed'] = $limit;
4961
                $json['created'] = $created;
4962
                $json['updated'] = $updated;
4963
                $json['skipped'] = $skipped;
4964
                $json['invalid'] = $invalid;
4965
                $json['images'] = $images;
4966
                
4967
                wp_send_json( $json );
4968
            } else if ( $task == 'import_hood' ) {               
4969
                if (!empty($file)) {
4970
                    $columns = isset($file[0]) ? $file[0] : NULL;
4971
                    
4972 View Code Duplication
                    if (empty($columns) || (!empty($columns) && $columns[0] == '')) {
4973
                        $json['error'] = __('File you are uploading is not valid. Columns does not matching.', 'geodirectory');
4974
                        wp_send_json( $json );
4975
                    }
4976
                    
4977
                    $gd_error_log = __('GD IMPORT NEIGHBOURHOODS [ROW %d]:', 'geodirectory');
4978
                    $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' );
4979
                    for ($i = 1; $i <= $limit; $i++) {
4980
                        $index = $processed + $i;
4981
                        
4982
                        if (isset($file[$index])) {
4983
                            $row = $file[$index];
4984
                            $row = array_map( 'trim', $row );
4985
                            $data = array();
4986
                            
4987
                            foreach ($columns as $c => $column) {
4988
                                if (in_array($column, array('neighbourhood_id', 'neighbourhood_name', 'neighbourhood_slug', 'latitude', 'longitude', 'location_id', 'city', 'region', 'country'))) {
4989
                                    $data[$column] = sanitize_text_field($row[$c]);
4990
                                }
4991
                            }
4992
4993
                            if (empty($data['neighbourhood_name']) || empty($data['latitude']) || empty($data['longitude'])) {
4994
                                $invalid++;
4995
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
4996
                                continue;
4997
                            }
4998
                            
4999
                            $location_info = array();
5000
                            if (!empty($data['location_id']) && (int)$data['location_id'] > 0) {
5001
                                $location_info = geodir_get_location_by_id('', (int)$data['location_id']);
5002
                            } else if (!empty($data['city']) && !empty($data['region']) && !empty($data['country'])) {
5003
                                $location_info = geodir_get_location_by_slug('city', array('fields' => 'location_id', 'city' => $data['city'], 'country' => $data['country'], 'region' => $data['region']));
5004
                            }
5005
5006
                            if (empty($location_info)) {
5007
                                $invalid++;
5008
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
5009
                                continue;
5010
                            }
5011
                            
5012
                            $location_id = $location_info->location_id;
5013
5014
                            $data['neighbourhood_id'] = isset($data['neighbourhood_id']) ? absint($data['neighbourhood_id']) : 0;
5015
                            
5016
                            $hood_data = array();
5017
                            $hood_data['hood_name'] = $data['neighbourhood_name'];
5018
                            $hood_data['hood_slug'] = $data['neighbourhood_slug'];
5019
                            $hood_data['hood_latitude'] = $data['latitude'];
5020
                            $hood_data['hood_longitude'] = $data['longitude'];
5021
                            $hood_data['hood_location_id'] = $location_id;
5022
                                    
5023
                            if ( $import_choice == 'update' ) {
5024
                                if ((int)$data['neighbourhood_id'] > 0 && ($neighbourhood = geodir_location_get_neighbourhood_by_id((int)$data['neighbourhood_id']))) {
5025
                                    $hood_data['hood_id'] = (int)$data['neighbourhood_id'];
5026
                                    
5027
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
5028
                                        $updated++;
5029
                                    } else {
5030
                                        $invalid++;
5031
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
5032
                                    }
5033
                                } else if (!empty($data['neighbourhood_slug']) && ($neighbourhood = geodir_location_get_neighbourhood_by_id($data['neighbourhood_slug'], true))) {
5034
                                    $hood_data['hood_id'] = (int)$neighbourhood->hood_id;
5035
                                    
5036
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
5037
                                        $updated++;
5038
                                    } else {
5039
                                        $invalid++;
5040
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
5041
                                    }
5042
                                } else {
5043
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
5044
                                        $created++;
5045
                                    } else {
5046
                                        $invalid++;
5047
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
5048
                                    }
5049
                                }
5050 View Code Duplication
                            } elseif ( $import_choice == 'skip' ) {
5051
                                if ((int)$data['neighbourhood_id'] > 0 && ($neighbourhood = geodir_location_get_neighbourhood_by_id((int)$data['neighbourhood_id']))) {
5052
                                    $skipped++;
5053
                                } else if (!empty($data['neighbourhood_slug']) && ($neighbourhood = geodir_location_get_neighbourhood_by_id($data['neighbourhood_slug'], true))) {
5054
                                    $skipped++;
5055
                                } else {
5056
                                    
5057
                                    if ($neighbourhood = geodir_location_insert_update_neighbourhood($hood_data)) {
5058
                                        $created++;
5059
                                    } else {
5060
                                        $invalid++;
5061
                                        geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
5062
                                    }
5063
                                }
5064
                            } else {
5065
                                $invalid++;
5066
                                geodir_error_log( wp_sprintf( $gd_error_log, ($index + 1) ) . ' ' . $gd_error_hood );
5067
                            }
5068
                        }
5069
                    }
5070
                }
5071
                
5072
                $json = array();
5073
                $json['processed'] = $limit;
5074
                $json['created'] = $created;
5075
                $json['updated'] = $updated;
5076
                $json['skipped'] = $skipped;
5077
                $json['invalid'] = $invalid;
5078
                $json['images'] = $images;
5079
                
5080
                wp_send_json( $json );
5081
            }
5082
        }
5083
        break;
5084
        case 'import_finish':{
5085
            /**
5086
             * Run an action when an import finishes.
5087
             *
5088
             * This action can be used to fire functions after an import ends.
5089
             *
5090
             * @since 1.5.3
5091
             * @package GeoDirectory
5092
             */
5093
            do_action('geodir_import_finished');
5094
        }
5095
        break;
5096
5097
    }
5098
    echo '0';
5099
    gd_die();
5100
}
5101
5102
/**
5103
 * Create new the post term.
5104
 *
5105
 * @since 1.4.6
5106
 * @package GeoDirectory
5107
 *
5108
 * @param string $taxonomy Post taxonomy.
5109
 * @param array $term_data {
5110
 *    Attributes of term data.
5111
 *
5112
 *    @type string $name Term name.
5113
 *    @type string $slug Term slug.
5114
 *    @type string $description Term description.
5115
 *    @type string $top_description Term top description.
5116
 *    @type string $image Default Term image.
5117
 *    @type string $icon Default Term icon.
5118
 *    @type string $taxonomy Term taxonomy.
5119
 *    @type int $parent Term parent ID.
5120
 *
5121
 * }
5122
 * @return int|bool Term id when success, false when fail.
5123
 */
5124
function geodir_imex_insert_term( $taxonomy, $term_data ) {
5125
	if ( empty( $taxonomy ) || empty( $term_data ) ) {
5126
		return false;
5127
	}
5128
	
5129
	$term = isset( $term_data['name'] ) && !empty( $term_data['name'] ) ? $term_data['name'] : '';
5130
	$args = array();
5131
	$args['description'] = isset( $term_data['description'] ) ? $term_data['description'] : '';
5132
	$args['slug'] = isset( $term_data['slug'] ) ? $term_data['slug'] : '';
5133
	$args['parent'] = isset( $term_data['parent'] ) ? (int)$term_data['parent'] : '';
5134
	
5135
	if ( ( !empty( $args['slug'] ) && term_exists( $args['slug'], $taxonomy ) ) || empty( $args['slug'] ) ) {
5136
		$term_args = array_merge( $term_data, $args );
5137
		$defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
5138
		$term_args = wp_parse_args( $term_args, $defaults );
5139
		$term_args = sanitize_term( $term_args, $taxonomy, 'db' );
5140
		$args['slug'] = wp_unique_term_slug( $args['slug'], (object)$term_args );
5141
	}
5142
	
5143
    if( !empty( $term ) ) {
5144
		$result = wp_insert_term( $term, $taxonomy, $args );
5145
        if( !is_wp_error( $result ) ) {
5146
            return isset( $result['term_id'] ) ? $result['term_id'] : 0;
5147
        }
5148
    }
5149
	
5150
	return false;
5151
}
5152
5153
/**
5154
 * Update the post term.
5155
 *
5156
 * @since 1.4.6
5157
 * @package GeoDirectory
5158
 *
5159
 * @param string $taxonomy Post taxonomy.
5160
 * @param array $term_data {
5161
 *    Attributes of term data.
5162
 *
5163
 *    @type string $term_id Term ID.
5164
 *    @type string $name Term name.
5165
 *    @type string $slug Term slug.
5166
 *    @type string $description Term description.
5167
 *    @type string $top_description Term top description.
5168
 *    @type string $image Default Term image.
5169
 *    @type string $icon Default Term icon.
5170
 *    @type string $taxonomy Term taxonomy.
5171
 *    @type int $parent Term parent ID.
5172
 *
5173
 * }
5174
 * @return int|bool Term id when success, false when fail.
5175
 */
5176
function geodir_imex_update_term( $taxonomy, $term_data ) {
5177
	if ( empty( $taxonomy ) || empty( $term_data ) ) {
5178
		return false;
5179
	}
5180
	
5181
	$term_id = isset( $term_data['term_id'] ) && !empty( $term_data['term_id'] ) ? $term_data['term_id'] : 0;
5182
	
5183
	$args = array();
5184
	$args['description'] = isset( $term_data['description'] ) ? $term_data['description'] : '';
5185
	$args['slug'] = isset( $term_data['slug'] ) ? $term_data['slug'] : '';
5186
	$args['parent'] = isset( $term_data['parent'] ) ? (int)$term_data['parent'] : '';
5187
	
5188
	if ( $term_id > 0 && $term_info = (array)get_term( $term_id, $taxonomy ) ) {
5189
		$term_data['term_id'] = $term_info['term_id'];
5190
		
5191
		$result = wp_update_term( $term_data['term_id'], $taxonomy, $term_data );
5192
		
5193
		if( !is_wp_error( $result ) ) {
5194
            return isset( $result['term_id'] ) ? $result['term_id'] : 0;
5195
        }
5196
	} else if ( $term_data['slug'] != '' && $term_info = (array)term_exists( $term_data['slug'], $taxonomy ) ) {
5197
		$term_data['term_id'] = $term_info['term_id'];
5198
		
5199
		$result = wp_update_term( $term_data['term_id'], $taxonomy, $term_data );
5200
		
5201
		if( !is_wp_error( $result ) ) {
5202
            return isset( $result['term_id'] ) ? $result['term_id'] : 0;
5203
        }
5204
	} else {
5205
		return geodir_imex_insert_term( $taxonomy, $term_data );
5206
	}
5207
	
5208
	return false;
5209
}
5210
5211
/**
5212
 * Get the posts counts for the current post type.
5213
 *
5214
 * @since 1.4.6
5215
 * @package GeoDirectory
5216
 *
5217
 * @global object $wpdb WordPress Database object.
5218
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5219
 *
5220
 * @param string $post_type Post type.
5221
 * @return int Posts count.
5222
 */
5223
function geodir_get_posts_count( $post_type ) {
5224 1
    global $wpdb, $plugin_prefix;
5225
5226 1
    if ( !post_type_exists( $post_type ) ) {
5227
        return 0;
5228
    }
5229
        
5230 1
    $table = $plugin_prefix . $post_type . '_detail';
5231
5232
    // Skip listing with statuses trash, auto-draft etc...
5233 1
    $skip_statuses = geodir_imex_export_skip_statuses();
5234 1
    $where_statuses = '';
5235 1 View Code Duplication
    if ( !empty( $skip_statuses ) && is_array( $skip_statuses ) ) {
5236 1
        $where_statuses = "AND `" . $wpdb->posts . "`.`post_status` NOT IN('" . implode( "','", $skip_statuses ) . "')";
5237 1
    }
5238
5239 1
    $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 );
5240
5241 1
    $posts_count = (int)$wpdb->get_var( $query );
5242
    
5243
    /**
5244
     * Modify returned post counts for the current post type.
5245
     *
5246
     * @since 1.4.6
5247
     * @package GeoDirectory
5248
     *
5249
     * @param int $posts_count Post counts.
5250
     * @param string $post_type Post type.
5251
     */
5252 1
    $posts_count = apply_filters( 'geodir_imex_count_posts', $posts_count, $post_type );
5253
5254 1
    return $posts_count;
5255
}
5256
5257
/**
5258
 * Retrieves the posts for the current post type.
5259
 *
5260
 * @since 1.4.6
5261
 * @since 1.5.1 Updated to import & export recurring events.
5262
 * @since 1.5.3 Fixed to get wpml original post id.
5263
 * @since 1.5.7 $per_page & $page_no parameters added.
5264
 * @package GeoDirectory
5265
 *
5266
 * @global object $wp_filesystem WordPress FileSystem object.
5267
 *
5268
 * @param string $post_type Post type.
5269
 * @param int $per_page Per page limit. Default 0.
5270
 * @param int $page_no Page number. Default 0.
5271
 * @return array Array of posts data.
5272
 */
5273
function geodir_imex_get_posts( $post_type, $per_page = 0, $page_no = 0 ) {	
5274
	global $wp_filesystem;
5275
5276
	$posts = geodir_get_export_posts( $post_type, $per_page, $page_no );
5277
5278
	$csv_rows = array();
5279
	
5280
	if ( !empty( $posts ) ) {
5281
		$is_payment_plugin = is_plugin_active( 'geodir_payment_manager/geodir_payment_manager.php' );
5282
        $location_manager = function_exists('geodir_location_plugin_activated') ? true : false; // Check location manager installed & active.
5283
        $location_allowed = function_exists( 'geodir_cpt_no_location' ) && geodir_cpt_no_location( $post_type ) ? false : true;
5284
        $neighbourhood_active = $location_manager && $location_allowed && get_option('location_neighbourhoods') ? true : false;
5285
		
5286
		$csv_row = array();
5287
		$csv_row[] = 'post_id';
5288
		$csv_row[] = 'post_title';
5289
		$csv_row[] = 'post_author';
5290
		$csv_row[] = 'post_content';
5291
		$csv_row[] = 'post_category';
5292
		$csv_row[] = 'default_category';
5293
		$csv_row[] = 'post_tags';
5294
		$csv_row[] = 'post_type';
5295
		if ( $post_type == 'gd_event' ) {
5296
			$csv_row[] = 'event_date';
5297
			$csv_row[] = 'event_enddate';
5298
			$csv_row[] = 'starttime';
5299
			$csv_row[] = 'endtime';
5300
			
5301
			$csv_row[] = 'is_recurring_event';
5302
			$csv_row[] = 'event_duration_days';
5303
			$csv_row[] = 'recurring_dates';
5304
			$csv_row[] = 'is_whole_day_event';
5305
			$csv_row[] = 'event_starttimes';
5306
			$csv_row[] = 'event_endtimes';
5307
			$csv_row[] = 'recurring_type';
5308
			$csv_row[] = 'recurring_interval';
5309
			$csv_row[] = 'recurring_week_days';
5310
			$csv_row[] = 'recurring_week_nos';
5311
			$csv_row[] = 'max_recurring_count';
5312
			$csv_row[] = 'recurring_end_date';
5313
		}
5314
		$csv_row[] = 'post_status';
5315
		$csv_row[] = 'is_featured';
5316
		if ($is_payment_plugin) {
5317
			$csv_row[] = 'package_id';
5318
			$csv_row[] = 'expire_date';
5319
		}
5320
		$csv_row[] = 'geodir_video';
5321
		$csv_row[] = 'post_address';
5322
		$csv_row[] = 'post_city';
5323
		$csv_row[] = 'post_region';
5324
		$csv_row[] = 'post_country';
5325
		$csv_row[] = 'post_zip';
5326
		$csv_row[] = 'post_latitude';
5327
		$csv_row[] = 'post_longitude';
5328
        if ($neighbourhood_active) {
5329
            $csv_row[] = 'post_neighbourhood';
5330
            $csv_row[] = 'neighbourhood_latitude';
5331
            $csv_row[] = 'neighbourhood_longitude';
5332
        }
5333
		$csv_row[] = 'geodir_timing';
5334
		$csv_row[] = 'geodir_contact';
5335
		$csv_row[] = 'geodir_email';
5336
		$csv_row[] = 'geodir_website';
5337
		$csv_row[] = 'geodir_twitter';
5338
		$csv_row[] = 'geodir_facebook';
5339
		$csv_row[] = 'geodir_video';
5340
		$csv_row[] = 'geodir_special_offers';
5341
		// WPML
5342
		$is_wpml = geodir_is_wpml();
5343
		if ($is_wpml) {
5344
			$csv_row[] = 'language';
5345
			$csv_row[] = 'original_post_id';
5346
		}
5347
		// WPML
5348
5349
		$custom_fields = geodir_imex_get_custom_fields( $post_type );
5350
		if ( !empty( $custom_fields ) ) {
5351
			foreach ( $custom_fields as $custom_field ) {
5352
				$csv_row[] = $custom_field->htmlvar_name;
5353
			}
5354
		}
5355
5356
		// Export franchise fields
5357
		$is_franchise_active = is_plugin_active( 'geodir_franchise/geodir_franchise.php' ) && geodir_franchise_enabled( $post_type ) ? true : false;
5358
		if ($is_franchise_active) {
5359
			$csv_row[] = 'gd_is_franchise';
5360
			$csv_row[] = 'gd_franchise_lock';
5361
			$csv_row[] = 'franchise';
5362
		}
5363
		
5364
		$csv_rows[] = $csv_row;
5365
5366
		$images_count = 5;
5367
        $xx=0;
5368
		foreach ( $posts as $post ) {$xx++;
5369
			$post_id = $post['ID'];
5370
			
5371
			$gd_post_info = geodir_get_post_info( $post_id );
5372
			$post_info = (array)$gd_post_info;
5373
						
5374
			$taxonomy_category = $post_type . 'category';
5375
			$taxonomy_tags = $post_type . '_tags';
5376
			
5377
			$post_category = '';
5378
			$default_category_id = $gd_post_info->default_category;
5379
			$default_category = '';
5380
			$post_tags = '';
5381
			$terms = wp_get_post_terms( $post_id, array( $taxonomy_category, $taxonomy_tags ) );
5382
			
5383
			if ( !empty( $terms ) && !is_wp_error( $terms ) ) {
5384
				$post_category = array();
5385
				$post_tags = array();
5386
			
5387
				foreach ( $terms as $term ) {
5388
					if ( $term->taxonomy == $taxonomy_category ) {
5389
						$post_category[] = $term->name;
5390
						
5391
						if ($default_category_id == $term->term_id) {
5392
							$default_category = $term->name; // Default category.
5393
						}
5394
					}
5395
					
5396
					if ( $term->taxonomy == $taxonomy_tags ) {
5397
						$post_tags[] = $term->name;
5398
					}
5399
				}
5400
				
5401
				if (empty($default_category) && !empty($post_category)) {
5402
					$default_category = $post_category[0]; // Set first one as default category.
5403
				}
5404
				$post_category = !empty( $post_category ) ? implode( ',', $post_category ) : '';
5405
				$post_tags = !empty( $post_tags ) ? implode( ',', $post_tags ) : '';
5406
			}
5407
5408
			// Franchise data
5409
			if ($is_franchise_active && isset($post_info['franchise']) && (int)$post_info['franchise'] > 0 && geodir_franchise_check((int)$post_info['franchise'])) {
5410
				$franchise_id = $post_info['franchise'];
5411
				$gd_franchise_info = geodir_get_post_info($franchise_id);
5412
5413
				if (geodir_franchise_pkg_is_active($gd_franchise_info)) {
5414
					$franchise_info = (array)$gd_franchise_info;
5415
					$locked_fields = geodir_franchise_get_locked_fields($franchise_id, true);
5416
					
5417
					if (!empty($locked_fields)) {
5418
						foreach( $locked_fields as $locked_field) {
5419
							if (isset($post_info[$locked_field]) && isset($franchise_info[$locked_field])) {
5420
								$post_info[$locked_field] = $franchise_info[$locked_field];
5421
							}
5422
							
5423
							if (in_array($taxonomy_category, $locked_fields) || in_array('post_tags', $locked_fields)) {
5424
								$franchise_terms = wp_get_post_terms( $franchise_id, array( $taxonomy_category, $taxonomy_tags ) );
5425
			
5426
								if ( !empty( $franchise_terms ) && !is_wp_error( $franchise_terms ) ) {
5427
									$franchise_post_category = array();
5428
									$franchise_post_tags = array();
5429
								
5430
									foreach ( $franchise_terms as $franchise_term ) {
5431
										if ( $franchise_term->taxonomy == $taxonomy_category ) {
5432
											$franchise_post_category[] = $franchise_term->name;
5433
										}
5434
										
5435
										if ( $franchise_term->taxonomy == $taxonomy_tags ) {
5436
											$franchise_post_tags[] = $franchise_term->name;
5437
										}
5438
									}
5439
									
5440
									if (in_array($taxonomy_category, $locked_fields)) {
5441
										$post_category = !empty( $franchise_post_category ) ? implode( ',', $franchise_post_category ) : '';
5442
									}
5443
									if (in_array('post_tags', $locked_fields)) {
5444
										$post_tags = !empty( $franchise_post_tags ) ? implode( ',', $franchise_post_tags ) : '';
5445
									}
5446
								}
5447
							}
5448
						}
5449
					}
5450
				}
5451
			}
5452
						
5453
			$post_images = geodir_get_images( $post_id );
5454
			$current_images = array();
5455
			if ( !empty( $post_images ) ) {
5456
				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...
5457
					$post_image = (array)$post_image;
5458
					$image = !empty( $post_image ) && isset( $post_image['path'] ) && $wp_filesystem->is_file( $post_image['path'] ) && $wp_filesystem->exists( $post_image['path'] ) ? $post_image['src'] : '';
5459
					if ( $image ) {
5460
						$current_images[] = $image;
5461
					}
5462
				}
5463
				
5464
				$images_count = max( $images_count, count( $current_images ) );
5465
			}
5466
5467
			$csv_row = array();
5468
			$csv_row[] = $post_id; // post_id
5469
			$csv_row[] = $post_info['post_title']; // post_title
5470
			$csv_row[] = $post_info['post_author']; // post_author
5471
			$csv_row[] = $post_info['post_content']; // post_content
5472
			$csv_row[] = $post_category; // post_category
5473
			$csv_row[] = $default_category; // default_category
5474
			$csv_row[] = $post_tags; // post_tags
5475
			$csv_row[] = $post_type; // post_type
5476
			if ( $post_type == 'gd_event' ) {
5477
				$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 5371 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...
5478
				$csv_row[] = $event_data['event_date']; // event_date
5479
				$csv_row[] = $event_data['event_enddate']; // enddate
5480
				$csv_row[] = $event_data['starttime']; // starttime
5481
				$csv_row[] = $event_data['endtime']; // endtime
5482
				
5483
				$csv_row[] = $event_data['is_recurring_event']; // is_recurring
5484
				$csv_row[] = $event_data['event_duration_days']; // duration_x
5485
				$csv_row[] = $event_data['recurring_dates']; // recurring_dates
5486
				$csv_row[] = $event_data['is_whole_day_event']; // all_day
5487
				$csv_row[] = $event_data['event_starttimes']; // starttimes
5488
				$csv_row[] = $event_data['event_endtimes']; // endtimes
5489
				$csv_row[] = $event_data['recurring_type']; // repeat_type
5490
				$csv_row[] = $event_data['recurring_interval']; // repeat_x
5491
				$csv_row[] = $event_data['recurring_week_days']; // repeat_days
5492
				$csv_row[] = $event_data['recurring_week_nos']; // repeat_weeks
5493
				$csv_row[] = $event_data['max_recurring_count']; // max_repeat
5494
				$csv_row[] = $event_data['recurring_end_date']; // repeat_end
5495
			}
5496
			$csv_row[] = $post_info['post_status']; // post_status
5497
			$csv_row[] = (int)$post_info['is_featured'] == 1 ? 1 : ''; // is_featured
5498
			if ($is_payment_plugin) {
5499
				$csv_row[] = (int)$post_info['package_id']; // package_id
5500
				$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
5501
			}
5502
			$csv_row[] = $post_info['geodir_video']; // geodir_video
5503
			$csv_row[] = $post_info['post_address']; // post_address
5504
			$csv_row[] = $post_info['post_city']; // post_city
5505
			$csv_row[] = $post_info['post_region']; // post_region
5506
			$csv_row[] = $post_info['post_country']; // post_country
5507
			$csv_row[] = $post_info['post_zip']; // post_zip
5508
			$csv_row[] = $post_info['post_latitude']; // post_latitude
5509
			$csv_row[] = $post_info['post_longitude']; // post_longitude
5510
            if ($neighbourhood_active) {
5511
                $post_neighbourhood = '';
5512
                $neighbourhood_latitude = '';
5513
                $neighbourhood_longitude = '';
5514
                if (!empty($post_info['post_neighbourhood']) && ($hood_info = geodir_location_get_neighbourhood_by_id($post_info['post_neighbourhood'], true, $post_info['post_location_id']))) {
5515
                    if (!empty($hood_info)) {
5516
                        $post_neighbourhood = $hood_info->hood_name;
5517
                        $neighbourhood_latitude = $hood_info->hood_latitude;
5518
                        $neighbourhood_longitude = $hood_info->hood_longitude;
5519
                    }
5520
                }
5521
                $csv_row[] = $post_neighbourhood; // post_neighbourhood
5522
                $csv_row[] = $neighbourhood_latitude; // neighbourhood_latitude
5523
                $csv_row[] = $neighbourhood_longitude; // neighbourhood_longitude
5524
            }
5525
			$csv_row[] = $post_info['geodir_timing']; // geodir_timing
5526
			$csv_row[] = $post_info['geodir_contact']; // geodir_contact
5527
			$csv_row[] = $post_info['geodir_email']; // geodir_email
5528
			$csv_row[] = $post_info['geodir_website']; // geodir_website
5529
			$csv_row[] = $post_info['geodir_twitter']; // geodir_twitter
5530
			$csv_row[] = $post_info['geodir_facebook']; // geodir_facebook
5531
			$csv_row[] = $post_info['geodir_video']; // geodir_video
5532
			$csv_row[] = $post_info['geodir_special_offers']; // geodir_special_offers
5533
			// WPML
5534
			if ($is_wpml) {
5535
				$csv_row[] = geodir_get_language_for_element( $post_id, 'post_' . $post_type );
5536
				$csv_row[] = geodir_imex_original_post_id( $post_id, 'post_' . $post_type );
5537
			}
5538
			// WPML
5539
			
5540
			if ( !empty( $custom_fields ) ) {
5541
				foreach ( $custom_fields as $custom_field ) {
5542
					$csv_row[] = isset( $post_info[$custom_field->htmlvar_name] ) ? $post_info[$custom_field->htmlvar_name] : '';
5543
				}
5544
			}
5545
			
5546
			// Franchise data
5547
			if ($is_franchise_active) {
5548
				$gd_is_franchise = '';
5549
				$locaked_fields = '';
5550
				$franchise = '';
5551
					
5552
				if (geodir_franchise_pkg_is_active($gd_post_info)) {
5553
					$gd_is_franchise = (int)get_post_meta( $post_id, 'gd_is_franchise', true );
5554
					$locaked_fields = $gd_is_franchise ? get_post_meta( $post_id, 'gd_franchise_lock', true ) : '';
5555
					$locaked_fields = (is_array($locaked_fields) && !empty($locaked_fields) ? implode(",", $locaked_fields) : '');
5556
					$franchise = !$gd_is_franchise && isset($post_info['franchise']) && (int)$post_info['franchise'] > 0 ? (int)$post_info['franchise'] : 0; // franchise id
5557
				}
5558
				
5559
				$csv_row[] = (int)$gd_is_franchise; // gd_is_franchise
5560
				$csv_row[] = $locaked_fields; // gd_franchise_lock fields
5561
				$csv_row[] = (int)$franchise; // franchise id
5562
			}
5563
			
5564
			for ( $c = 0; $c < $images_count; $c++ ) {
5565
				$csv_row[] = isset( $current_images[$c] ) ? $current_images[$c] : ''; // IMAGE
5566
			}
5567
			
5568
			$csv_rows[] = $csv_row;
5569
5570
		}
5571
5572
		for ( $c = 0; $c < $images_count; $c++ ) {
5573
			$csv_rows[0][] = 'IMAGE';
5574
		}
5575
	}
5576
	return $csv_rows;
5577
}
5578
5579
/**
5580
 * Retrieves the posts for the current post type.
5581
 *
5582
 * @since 1.4.6
5583
 * @since 1.5.7 $per_page & $page_no parameters added.
5584
 * @package GeoDirectory
5585
 *
5586
 * @global object $wpdb WordPress Database object.
5587
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5588
 *
5589
 * @param string $post_type Post type.
5590
 * @param int $per_page Per page limit. Default 0.
5591
 * @param int $page_no Page number. Default 0.
5592
 * @return array Array of posts data.
5593
 */
5594
function geodir_get_export_posts( $post_type, $per_page = 0, $page_no = 0 ) {
5595
    global $wpdb, $plugin_prefix;
5596
5597
    if ( ! post_type_exists( $post_type ) )
5598
        return new stdClass;
5599
        
5600
    $table = $plugin_prefix . $post_type . '_detail';
5601
5602
    $limit = '';
5603
    if ( $per_page > 0 && $page_no > 0 ) {
5604
        $offset = ( $page_no - 1 ) * $per_page;
5605
        
5606
        if ( $offset > 0 ) {
5607
            $limit = " LIMIT " . $offset . "," . $per_page;
5608
        } else {
5609
            $limit = " LIMIT " . $per_page;
5610
        }
5611
    }
5612
5613
    // Skip listing with statuses trash, auto-draft etc...
5614
    $skip_statuses = geodir_imex_export_skip_statuses();
5615
    $where_statuses = '';
5616 View Code Duplication
    if ( !empty( $skip_statuses ) && is_array( $skip_statuses ) ) {
5617
        $where_statuses = "AND `" . $wpdb->posts . "`.`post_status` NOT IN('" . implode( "','", $skip_statuses ) . "')";
5618
    }
5619
5620
    $query = "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;
5621
    /**
5622
     * Modify returned posts SQL query for the current post type.
5623
     *
5624
     * @since 1.4.6
5625
     * @package GeoDirectory
5626
     *
5627
     * @param int $query The SQL query.
5628
     * @param string $post_type Post type.
5629
     */
5630
    $query = apply_filters( 'geodir_imex_export_posts_query', $query, $post_type );
5631
5632
    $results = (array)$wpdb->get_results( $wpdb->prepare( $query, $post_type ), ARRAY_A );
5633
5634
    /**
5635
     * Modify returned post results for the current post type.
5636
     *
5637
     * @since 1.4.6
5638
     * @package GeoDirectory
5639
     *
5640
     * @param object $results An object containing all post ids.
5641
     * @param string $post_type Post type.
5642
     */
5643
    return apply_filters( 'geodir_export_posts', $results, $post_type );
5644
}
5645
5646
/**
5647
 * Get the posts SQL query for the current post type.
5648
 *
5649
 * @since 1.4.6
5650
 * @since 1.5.1 Query updated to get distinct posts. 
5651
 * @package GeoDirectory
5652
 *
5653
 * @global object $wpdb WordPress Database object.
5654
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5655
 *
5656
 * @param string $query The SQL query.
5657
 * @param string $post_type Post type.
5658
 * @return string The SQL query.
5659
 */
5660
function geodir_imex_get_events_query( $query, $post_type ) {
5661
    if ( $post_type == 'gd_event' ) {
5662
        global $wpdb, $plugin_prefix;
5663
        
5664
        $table = $plugin_prefix . $post_type . '_detail';
5665
        $schedule_table = EVENT_SCHEDULE;
5666
        
5667
        // Skip listing with statuses trash, auto-draft etc...
5668
        $skip_statuses = geodir_imex_export_skip_statuses();
5669
        $where_statuses = '';
5670 View Code Duplication
        if ( !empty( $skip_statuses ) && is_array( $skip_statuses ) ) {
5671
            $where_statuses = "AND `" . $wpdb->posts . "`.`post_status` NOT IN('" . implode( "','", $skip_statuses ) . "')";
5672
        }
5673
5674
        $query = "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";
5675
    }
5676
5677
    return $query;
5678
}
5679
5680
/**
5681
 * Retrieve terms count for given post type.
5682
 *
5683
 * @since 1.4.6
5684
 * @package GeoDirectory
5685
 *
5686
 * @param  string $post_type Post type.
5687
 * @return int Total terms count.
5688
 */
5689
/**
5690
 * Retrieve terms count for given post type.
5691
 *
5692
 * @since 1.4.6
5693
 * @package GeoDirectory
5694
 *
5695
 * @param  string $post_type Post type.
5696
 * @return int Total terms count.
5697
 */
5698
function geodir_get_terms_count( $post_type ) {
5699 1
    $args = array( 'hide_empty' => 0 );
5700
5701 1
    remove_all_filters( 'get_terms' );
5702
5703 1
    $taxonomy = $post_type . 'category';
5704
5705
    // WPML
5706 1
    $is_wpml = geodir_is_wpml();
5707 1
    $active_lang = 'all';
5708 1
    if ( $is_wpml ) {
5709
        global $sitepress;
5710
        $active_lang = $sitepress->get_current_language();
5711
        
5712
        if ( $active_lang != 'all' ) {
5713
            $sitepress->switch_lang( 'all', true );
5714
        }
5715
    }
5716
    // WPML
5717
            
5718 1
    $count_terms = wp_count_terms( $taxonomy, $args );
5719
5720
    // WPML
5721 1
    if ( $is_wpml && $active_lang !== 'all' ) {
5722
        global $sitepress;
5723
        $sitepress->switch_lang( $active_lang, true );
5724
    }
5725
    // WPML
5726 1
    $count_terms = !is_wp_error( $count_terms ) ? $count_terms : 0;
5727
     
5728 1
    return $count_terms;
5729
}
5730
5731
/**
5732
 * Retrieve terms for given post type.
5733
 *
5734
 * @since 1.4.6
5735
 * @since 1.5.7 $per_page & $page_no parameters added.
5736
 * @package GeoDirectory
5737
 *
5738
 * @param  string $post_type The post type.
5739
 * @param int $per_page Per page limit. Default 0.
5740
 * @param int $page_no Page number. Default 0.
5741
 * @return array Array of terms data.
5742
 */
5743
function geodir_imex_get_terms( $post_type, $per_page = 0, $page_no = 0 ) {
5744
	$args = array( 'hide_empty' => 0, 'orderby' => 'id' );
5745
	
5746
	remove_all_filters( 'get_terms' );
5747
	
5748
	$taxonomy = $post_type . 'category';
5749
	
5750
	if ( $per_page > 0 && $page_no > 0 ) {
5751
		$args['offset'] = ( $page_no - 1 ) * $per_page;
5752
		$args['number'] = $per_page;
5753
	}
5754
	
5755
	$terms = get_terms( $taxonomy, $args );
5756
5757
	$csv_rows = array();
5758
	
5759
	if ( !empty( $terms ) ) {
5760
		$csv_row = array();
5761
		$csv_row[] = 'cat_id';
5762
		$csv_row[] = 'cat_name';
5763
		$csv_row[] = 'cat_slug';
5764
		$csv_row[] = 'cat_posttype';
5765
		$csv_row[] = 'cat_parent';
5766
		$csv_row[] = 'cat_schema';
5767
        // WPML
5768
		$is_wpml = geodir_is_wpml();
5769
		if ($is_wpml) {
5770
			$csv_row[] = 'cat_language';
5771
            $csv_row[] = 'cat_id_original';
5772
		}
5773
		// WPML
5774
		$csv_row[] = 'cat_description';
5775
		$csv_row[] = 'cat_top_description';
5776
		$csv_row[] = 'cat_image';
5777
		$csv_row[] = 'cat_icon';
5778
		
5779
		$csv_rows[] = $csv_row;
5780
		
5781
		foreach ( $terms as $term ) {
5782
			$cat_icon = get_tax_meta( $term->term_id, 'ct_cat_icon', false, $post_type );
5783
			$cat_icon = !empty( $cat_icon ) && isset( $cat_icon['src'] ) ? $cat_icon['src'] : '';
5784
			
5785
			$cat_image = geodir_get_default_catimage( $term->term_id, $post_type );
5786
			$cat_image = !empty( $cat_image ) && isset( $cat_image['src'] ) ? $cat_image['src'] : ''; 
5787
			
5788
			$cat_parent = '';
5789
			if (isset($term->parent) && (int)$term->parent > 0 && term_exists((int)$term->parent, $taxonomy)) {
5790
				$parent_term = (array)get_term_by( 'id', (int)$term->parent, $taxonomy );
5791
				$cat_parent = !empty($parent_term) && isset($parent_term['name']) ? $parent_term['name'] : '';
5792
			}
5793
			
5794
			$csv_row = array();
5795
			$csv_row[] = $term->term_id;
5796
			$csv_row[] = $term->name;
5797
			$csv_row[] = $term->slug;
5798
			$csv_row[] = $post_type;
5799
			$csv_row[] = $cat_parent;
5800
			$csv_row[] = get_tax_meta( $term->term_id, 'ct_cat_schema', false, $post_type );
5801
            // WPML
5802
			if ($is_wpml) {
5803
				$csv_row[] = geodir_get_language_for_element( $term->term_id, 'tax_' . $taxonomy );
5804
                $csv_row[] = geodir_imex_original_post_id( $term->term_id, 'tax_' . $taxonomy );
5805
			}
5806
			// WPML
5807
			$csv_row[] = $term->description;
5808
			$csv_row[] = get_tax_meta( $term->term_id, 'ct_cat_top_desc', false, $post_type );
5809
			$csv_row[] = $cat_image;
5810
			$csv_row[] = $cat_icon;
5811
			
5812
			$csv_rows[] = $csv_row;
5813
		}
5814
	}
5815
	return $csv_rows;
5816
}
5817
5818
/**
5819
 * Get the path of cache directory.
5820
 *
5821
 * @since 1.4.6
5822
 * @package GeoDirectory
5823
 *
5824
 * @param  bool $relative True for relative path & False for absolute path.
5825
 * @return string Path to the cache directory.
5826
 */
5827
function geodir_path_import_export( $relative = true ) {
5828
	$upload_dir = wp_upload_dir();
5829
	
5830
	return $relative ? $upload_dir['baseurl'] . '/cache' : $upload_dir['basedir'] . '/cache';
5831
}
5832
5833
/**
5834
 * Save the data in CSV file to export.
5835
 *
5836
 * @since 1.4.6
5837
 * @package GeoDirectory
5838
 *
5839
 * @global null|object $wp_filesystem WP_Filesystem object.
5840
 *
5841
 * @param  string $file_path Full path to file.
5842
 * @param  array $csv_data Array of csv data.
5843
 * @param  bool $clear If true then it overwrite data otherwise add rows at the end of file.
5844
 * @return bool true if success otherwise false.
5845
 */
5846
function geodir_save_csv_data( $file_path, $csv_data = array(), $clear = true ) {
5847
	if ( empty( $csv_data ) ) {
5848
		return false;
5849
	}
5850
	
5851
	global $wp_filesystem;
5852
	
5853
	$mode = $clear ? 'w+' : 'a+';
5854
	
5855
	if ( function_exists( 'fputcsv' ) ) {
5856
		$file = fopen( $file_path, $mode );
5857
		foreach( $csv_data as $csv_row ) {
5858
			//$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...
5859
			$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...
5860
		}
5861
		fclose( $file );
5862
	} else {
5863
		foreach( $csv_data as $csv_row ) {
5864
			//$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...
5865
			$wp_filesystem->put_contents( $file_path, $csv_row );
5866
		}
5867
	}
5868
		
5869
	return true;
5870
}
5871
5872
/**
5873
 * Count the number of line from file.
5874
 *
5875
 * @since 1.4.6
5876
 * @package GeoDirectory
5877
 *
5878
 * @global null|object $wp_filesystem WP_Filesystem object.
5879
 *
5880
 * @param  string $file Full path to file.
5881
 * @return int No of file rows.
5882
 */
5883
function geodir_import_export_line_count( $file ) {
5884
	global $wp_filesystem;
5885
	
5886
	if ( $wp_filesystem->is_file( $file ) && $wp_filesystem->exists( $file ) ) {
5887
		$contents = $wp_filesystem->get_contents_array( $file );
5888
		
5889
		if ( !empty( $contents ) && is_array( $contents ) ) {
5890
			return count( $contents ) - 1;
5891
		}
5892
	}
5893
	
5894
	return NULL;
5895
}
5896
5897
/**
5898
 * Returns queried data from custom fields table.
5899
 *
5900
 * @since 1.0.0
5901
 * @since 1.5.4 Modified to fix empty columns in export csv file.
5902
 * @package GeoDirectory
5903
 * @global object $wpdb WordPress Database object.
5904
 * @param string $post_type The post type.
5905
 * @return object Queried object.
5906
 */
5907
function geodir_imex_get_custom_fields( $post_type ) {
5908
	global $wpdb;
5909
	 
5910
	$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 ) );
5911
	$rows = $wpdb->get_results( $sql );
5912
	 
5913
	return $rows;
5914
}
5915
5916
/**
5917
 * Check wpml active or not.
5918
 *
5919
 * @since 1.5.0
5920
 *
5921
 * @return True if WPML is active else False.
5922
 */
5923
function geodir_is_wpml() {
5924 1
	if (function_exists('icl_object_id')) {
5925
		return true;
5926
	}
5927
	
5928 1
	return false;
5929
}
5930
5931
/**
5932
 * Get WPML language code for current term.
5933
 *
5934
 * @since 1.5.0
5935
 *
5936
 * @global object $sitepress Sitepress WPML object.
5937
 *
5938
 * @param int $element_id Post ID or Term id.
5939
 * @param string $element_type Element type. Ex: post_gd_place or tax_gd_placecategory.
5940
 * @return Language code.
5941
 */
5942
function geodir_get_language_for_element($element_id, $element_type) {
5943
	global $sitepress;
5944
	
5945
	return $sitepress->get_language_for_element($element_id, $element_type);
5946
}
5947
5948
/**
5949
 * Duplicate post details for WPML translation post.
5950
 *
5951
 * @since 1.5.0
5952
 *
5953
 * @param int $master_post_id Original Post ID.
5954
 * @param string $lang Language code for translating post.
5955
 * @param array $postarr Array of post data.
5956
 * @param int $tr_post_id Translation Post ID.
5957
 */
5958
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...
5959
	$post_type = get_post_type($master_post_id);
5960
5961
	if (in_array($post_type, geodir_get_posttypes())) {				
5962
		// Duplicate post details
5963
		geodir_icl_duplicate_post_details($master_post_id, $tr_post_id, $lang);
5964
		
5965
		// Duplicate taxonomies
5966
		geodir_icl_duplicate_taxonomies($master_post_id, $tr_post_id, $lang);
5967
		
5968
		// Duplicate post images
5969
		geodir_icl_duplicate_post_images($master_post_id, $tr_post_id, $lang);
5970
	}
5971
}
5972
5973
/**
5974
 * Duplicate post general details for WPML translation post.
5975
 *
5976
 * @since 1.5.0
5977
 *
5978
 * @global object $wpdb WordPress Database object.
5979
 * @global string $plugin_prefix Geodirectory plugin table prefix.
5980
 *
5981
 * @param int $master_post_id Original Post ID.
5982
 * @param int $tr_post_id Translation Post ID.
5983
 * @param string $lang Language code for translating post.
5984
 * @return bool True for success, False for fail.
5985
 */
5986
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...
5987
	global $wpdb, $plugin_prefix;
5988
	
5989
	$post_type = get_post_type($master_post_id);
5990
	$post_table = $plugin_prefix . $post_type . '_detail';
5991
	
5992
	$query = $wpdb->prepare("SELECT * FROM " . $post_table . " WHERE post_id = %d", array($master_post_id));
5993
	$data = (array)$wpdb->get_row($query);
5994
	
5995
	if ( !empty( $data ) ) {
5996
		$data['post_id'] = $tr_post_id;
5997
		unset($data['default_category'], $data['marker_json'], $data['featured_image'], $data[$post_type . 'category'], $data['overall_rating'], $data['rating_count'], $data['ratings']);
5998
		
5999
		$wpdb->update($post_table, $data, array('post_id' => $tr_post_id));		
6000
		return true;
6001
	}
6002
	
6003
	return false;
6004
}
6005
6006
/**
6007
 * Duplicate post taxonomies for WPML translation post.
6008
 *
6009
 * @since 1.5.0
6010
 *
6011
 * @global object $sitepress Sitepress WPML object.
6012
 * @global object $wpdb WordPress Database object.
6013
 *
6014
 * @param int $master_post_id Original Post ID.
6015
 * @param int $tr_post_id Translation Post ID.
6016
 * @param string $lang Language code for translating post.
6017
 * @return bool True for success, False for fail.
6018
 */
6019
function geodir_icl_duplicate_taxonomies($master_post_id, $tr_post_id, $lang) {
6020
	global $sitepress, $wpdb;
6021
	$post_type = get_post_type($master_post_id);
6022
	
6023
	remove_filter('get_term', array($sitepress,'get_term_adjust_id')); // AVOID filtering to current language
6024
6025
	$taxonomies = get_object_taxonomies($post_type);
6026
	foreach ($taxonomies as $taxonomy) {
6027
		$terms = get_the_terms($master_post_id, $taxonomy);
6028
		$terms_array = array();
6029
		
6030
		if ($terms) {
6031
			foreach ($terms as $term) {
6032
				$tr_id = apply_filters( 'translate_object_id',$term->term_id, $taxonomy, false, $lang);
6033
				
6034
				if (!is_null($tr_id)){
6035
					// not using get_term - unfiltered get_term
6036
					$translated_term = $wpdb->get_row($wpdb->prepare("
6037
						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));
6038
6039
					$terms_array[] = $translated_term->term_id;
6040
				}
6041
			}
6042
6043
			if (!is_taxonomy_hierarchical($taxonomy)){
6044
				$terms_array = array_unique( array_map( 'intval', $terms_array ) );
6045
			}
6046
6047
			wp_set_post_terms($tr_post_id, $terms_array, $taxonomy);
6048
			
6049
			if ($taxonomy == $post_type . 'category') {
6050
				geodir_set_postcat_structure($tr_post_id, $post_type . 'category');
6051
			}
6052
		}
6053
	}
6054
}
6055
6056
/**
6057
 * Duplicate post images for WPML translation post.
6058
 *
6059
 * @since 1.5.0
6060
 *
6061
 * @global object $wpdb WordPress Database object.
6062
 *
6063
 * @param int $master_post_id Original Post ID.
6064
 * @param int $tr_post_id Translation Post ID.
6065
 * @param string $lang Language code for translating post.
6066
 * @return bool True for success, False for fail.
6067
 */
6068
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...
6069
	global $wpdb;
6070
	
6071
	$query = $wpdb->prepare("DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE mime_type like %s AND post_id = %d", array('%image%', $tr_post_id));
6072
	$wpdb->query($query);
6073
	
6074
	$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));
6075
	$post_images = $wpdb->get_results($query);
6076
	
6077
	if ( !empty( $post_images ) ) {
6078
		foreach ( $post_images as $post_image) {
6079
			$image_data = (array)$post_image;
6080
			unset($image_data['ID']);
6081
			$image_data['post_id'] = $tr_post_id;
6082
			
6083
			$wpdb->insert(GEODIR_ATTACHMENT_TABLE, $image_data);
6084
			
6085
			geodir_set_wp_featured_image($tr_post_id);
6086
		}
6087
		
6088
		return true;
6089
	}
6090
	
6091
	return false;
6092
}
6093
6094
/**
6095
 * Retrieves the event data to export.
6096
 *
6097
 * @since 1.5.1
6098
 * @package GeoDirectory
6099
 *
6100
 * @param array $post Post array.
6101
 * @param object $gd_post_info Geodirectory Post object.
6102
 * @return array Event data array.
6103
 */
6104
function geodir_imex_get_event_data($post, $gd_post_info) {
6105
	$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'] ) ) : '';
6106
	$event_enddate = $event_date;
6107
	$starttime = isset( $post['starttime'] ) && $post['starttime'] != '' && $post['starttime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $post['starttime'] ) ) : '';
6108
	$endtime = isset( $post['endtime'] ) && $post['endtime'] != '' && $post['endtime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $post['endtime'] ) ) : '';
6109
	
6110
	$is_recurring_event = '';
6111
	$event_duration_days = '';
6112
	$is_whole_day_event = '';
6113
	$recurring_dates = '';
6114
	$event_starttimes = '';
6115
	$event_endtimes = '';
6116
	$recurring_type = '';
6117
	$recurring_interval = '';
6118
	$recurring_week_days = '';
6119
	$recurring_week_nos = '';
6120
	$max_recurring_count = '';
6121
	$recurring_end_date = '';
6122
		
6123
	$recurring_data = isset($gd_post_info->recurring_dates) ? maybe_unserialize($gd_post_info->recurring_dates) : array();
6124
	if (!empty($recurring_data)) {
6125
		$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;
6126
		$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;
6127
		$starttime = isset( $recurring_data['starttime'] ) && $recurring_data['starttime'] != '' && $recurring_data['starttime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $recurring_data['starttime'] ) ) : $starttime;
6128
		$endtime = isset( $recurring_data['endtime'] ) && $recurring_data['endtime'] != '' && $recurring_data['endtime'] != '00:00:00' ? date_i18n( 'H:i', strtotime( $recurring_data['endtime'] ) ) : $endtime;
6129
		$is_whole_day_event = !empty($recurring_data['all_day']) ? 1 : '';
6130
		$different_times = !empty($recurring_data['different_times']) ? true : false;
6131
	
6132
		$recurring_pkg = geodir_event_recurring_pkg( $gd_post_info );
6133
		$is_recurring = isset( $gd_post_info->is_recurring ) && (int)$gd_post_info->is_recurring == 0 ? false : true;
6134
			
6135
		if ($recurring_pkg && $is_recurring) {
6136
			$recurring_dates = $event_date;
6137
			$event_enddate = '';
6138
			$is_recurring_event = 1;
6139
						
6140
			$recurring_type = !empty($recurring_data['repeat_type']) && in_array($recurring_data['repeat_type'], array('day', 'week', 'month', 'year', 'custom')) ? $recurring_data['repeat_type'] : 'custom';
6141
			
6142
			if (!empty($recurring_data['event_recurring_dates'])) {
6143
				$event_recurring_dates = explode( ',', $recurring_data['event_recurring_dates'] );
6144
				
6145
				if (!empty($event_recurring_dates)) {
6146
					$recurring_dates = array();
6147
					
6148
					foreach ($event_recurring_dates as $date) {
6149
						$recurring_dates[] = date_i18n( 'd/m/Y', strtotime( $date ) );
6150
					}
6151
					
6152
					$recurring_dates = implode(",", $recurring_dates);
6153
				}
6154
			}
6155
			
6156
			if ($recurring_type == 'custom') {
6157
				if (!$is_whole_day_event) {
6158
					$event_starttimes = $starttime;
6159
					$event_endtimes = $endtime;
6160
			
6161 View Code Duplication
					if (!empty($recurring_data['starttimes'])) {
6162
						$times = array();
6163
						
6164
						foreach ($recurring_data['starttimes'] as $time) {
6165
							$times[] = $time != '00:00:00' ? date_i18n( 'H:i', strtotime( $time ) ) : '00:00';
6166
						}
6167
						
6168
						$event_starttimes = implode(",", $times);
6169
					}
6170
					
6171 View Code Duplication
					if (!empty($recurring_data['endtimes'])) {
6172
						$times = array();
6173
						
6174
						foreach ($recurring_data['endtimes'] as $time) {
6175
							$times[] = $time != '00:00:00' ? date_i18n( 'H:i', strtotime( $time ) ) : '00:00';
6176
						}
6177
						
6178
						$event_endtimes = implode(",", $times);
6179
					}
6180
					
6181
					if (!$different_times) {
6182
						$event_starttimes = '';
6183
						$event_endtimes = '';
6184
					}
6185
				}
6186
			} else {
6187
				$event_duration_days = isset($recurring_data['duration_x']) ? (int)$recurring_data['duration_x'] : 1;
6188
				$recurring_interval = !empty($recurring_data['repeat_x']) && (int)$recurring_data['repeat_x'] > 0 ? $recurring_data['repeat_x'] : 1;
6189
				
6190
				if (($recurring_type == 'week' || $recurring_type == 'month') && !empty($recurring_data['repeat_days'])) {
6191
					$week_days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
6192
					
6193
					$days = array();
6194
					foreach ($recurring_data['repeat_days'] as $day) {
6195
						if (isset($week_days[$day])) {
6196
							$days[] = $week_days[$day];
6197
						}
6198
					}
6199
					
6200
					$recurring_week_days = implode(",", array_unique($days));
6201
				}
6202
				
6203
				$recurring_week_nos = $recurring_type == 'month' && !empty($recurring_data['repeat_weeks']) ? implode(",", $recurring_data['repeat_weeks']) : $recurring_week_nos;
6204
				if (!empty($recurring_data['repeat_end_type']) && (int)$recurring_data['repeat_end_type'] == 1) {
6205
					$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'] ) ) : '';
6206
					$max_recurring_count = empty($recurring_end_date) ? 1 : '';
6207
				} else {
6208
					$max_recurring_count = (!empty($recurring_data['max_repeat']) && (int)$recurring_data['max_repeat'] > 0 ? (int)$recurring_data['max_repeat'] : 1);
6209
				}
6210
			}
6211
		}
6212
	}
6213
	if ($is_whole_day_event) {
6214
		$starttime = '';
6215
		$endtime = '';
6216
		$event_starttimes = '';
6217
		$event_endtimes = '';
6218
	}
6219
	
6220
	$data = array();
6221
	$data['event_date'] = $event_date;
6222
	$data['event_enddate'] = $event_enddate;
6223
	$data['starttime'] = $starttime;
6224
	$data['endtime'] = $endtime;
6225
	$data['is_recurring_event'] = $is_recurring_event;
6226
	$data['recurring_dates'] = $recurring_dates;
6227
	$data['event_duration_days'] = $event_duration_days;
6228
	$data['is_whole_day_event'] = $is_whole_day_event;
6229
	$data['event_starttimes'] = $event_starttimes;
6230
	$data['event_endtimes'] = $event_endtimes;
6231
	$data['recurring_type'] = $recurring_type;
6232
	$data['recurring_interval'] = $recurring_interval;
6233
	$data['recurring_week_days'] = $recurring_week_days;
6234
	$data['recurring_week_nos'] = $recurring_week_nos;
6235
	$data['max_recurring_count'] = $max_recurring_count;
6236
	$data['recurring_end_date'] = $recurring_end_date;
6237
	
6238
	return $data;
6239
}
6240
6241
/**
6242
 * Convert date format to store in database.
6243
 *
6244
 * PHP date() function doesn't work well with d/m/Y format
6245
 * so this function validate and convert date to store in db.
6246
 *
6247
 * @since 1.5.1
6248
 * @package GeoDirectory
6249
 *
6250
 * @param string $date Date in Y-m-d or d/m/Y format.
6251
 * @return string Date in Y-m-d format.
6252
 */
6253
function geodir_imex_get_date_ymd($date) {
6254
	if (strpos($date, '/') !== false) {
6255
		$date = str_replace('/', '-', $date); // PHP doesn't work well with dd/mm/yyyy format.
6256
	}
6257
	
6258
	$date = date_i18n('Y-m-d', strtotime($date));
6259
	return $date;
6260
}
6261
6262
/**
6263
 * Validate the event data.
6264
 *
6265
 * @since 1.5.1
6266
 * @package GeoDirectory
6267
 *
6268
 * @param array $gd_post Post array.
6269
 * @return array Event data array.
6270
 */
6271
function geodir_imex_process_event_data($gd_post) {
6272
	$recurring_pkg = geodir_event_recurring_pkg( (object)$gd_post );
6273
6274
	$is_recurring = isset( $gd_post['is_recurring_event'] ) && (int)$gd_post['is_recurring_event'] == 0 ? false : true;
6275
	$event_date = isset($gd_post['event_date']) && $gd_post['event_date'] != '' ? geodir_imex_get_date_ymd($gd_post['event_date']) : '';
6276
	$event_enddate = isset($gd_post['event_enddate']) && $gd_post['event_enddate'] != '' ? geodir_imex_get_date_ymd($gd_post['event_enddate']) : $event_date;
6277
	$all_day = isset($gd_post['is_whole_day_event']) && !empty($gd_post['is_whole_day_event']) ? true : false;
6278
	$starttime = isset($gd_post['starttime']) && !$all_day ? $gd_post['starttime'] : '';
6279
	$endtime = isset($gd_post['endtime']) && !$all_day ? $gd_post['endtime'] : '';
6280
	
6281
	$repeat_type = '';
6282
	$different_times = '';
6283
	$starttimes = '';
6284
	$endtimes = '';
6285
	$repeat_days = '';
6286
	$repeat_weeks = '';
6287
	$event_recurring_dates = '';
6288
	$repeat_x = '';
6289
	$duration_x = '';
6290
	$repeat_end_type = '';
6291
	$max_repeat = '';
6292
	$repeat_end = '';
6293
	
6294
	if ($recurring_pkg && $is_recurring) {
6295
		$repeat_type = $gd_post['recurring_type'];
6296
		
6297
		if ($repeat_type == 'custom') {
6298
			$starttimes = !$all_day && !empty($gd_post['event_starttimes']) ? explode(",", $gd_post['event_starttimes']) : array();
6299
			$endtimes = !$all_day && !empty($gd_post['event_endtimes']) ? explode(",", $gd_post['event_endtimes']) : array();
6300
			
6301
			if (!empty($starttimes) || !empty($endtimes)) {
6302
				$different_times = true;
6303
			}
6304
			
6305
			$recurring_dates = isset($gd_post['recurring_dates']) && $gd_post['recurring_dates'] != '' ? explode(",", $gd_post['recurring_dates']) : array();
6306
			if (!empty($recurring_dates)) {
6307
				$event_recurring_dates = array();
6308
				
6309
				foreach ($recurring_dates as $recurring_date) {
6310
					$recurring_date = trim($recurring_date);
6311
					
6312
					if ($recurring_date != '') {
6313
						$event_recurring_dates[] = geodir_imex_get_date_ymd($recurring_date);
6314
					}
6315
				}
6316
				
6317
				$event_recurring_dates = array_unique($event_recurring_dates);
6318
				$event_recurring_dates = implode(",", $event_recurring_dates);
6319
			}
6320
		} else {
6321
			$duration_x = !empty( $gd_post['event_duration_days'] ) ? (int)$gd_post['event_duration_days'] : 1;
6322
			$repeat_x = !empty( $gd_post['recurring_interval'] ) ? (int)$gd_post['recurring_interval'] : 1;
6323
			$max_repeat = !empty( $gd_post['max_recurring_count'] ) ? (int)$gd_post['max_recurring_count'] : 1;
6324
			$repeat_end = !empty( $gd_post['recurring_end_date'] ) ? geodir_imex_get_date_ymd($gd_post['recurring_end_date']) : '';
6325
			
6326
			$repeat_end_type = $repeat_end != '' ? 1 : 0;
6327
			$max_repeat = $repeat_end != '' ? '' : $max_repeat;
6328
			
6329
			$week_days = array_flip(array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'));
6330
			
6331
			$a_repeat_days = isset($gd_post['recurring_week_days']) && trim($gd_post['recurring_week_days'])!='' ? explode(',', trim($gd_post['recurring_week_days'])) : array();
6332
			$repeat_days = array();
6333
			if (!empty($a_repeat_days)) {
6334
				foreach ($a_repeat_days as $repeat_day) {
6335
					$repeat_day = geodir_strtolower(trim($repeat_day));
6336
					
6337
					if ($repeat_day != '' && isset($week_days[$repeat_day])) {
6338
						$repeat_days[] = $week_days[$repeat_day];
6339
					}
6340
				}
6341
				
6342
				$repeat_days = array_unique($repeat_days);
6343
			}
6344
			
6345
			$a_repeat_weeks = isset($gd_post['recurring_week_nos']) && trim($gd_post['recurring_week_nos']) != '' ? explode(",", trim($gd_post['recurring_week_nos'])) : array();
6346
			$repeat_weeks = array();
6347
			if (!empty($a_repeat_weeks)) {
6348
				foreach ($a_repeat_weeks as $repeat_week) {
6349
					$repeat_weeks[] = (int)$repeat_week;
6350
				}
6351
				
6352
				$repeat_weeks = array_unique($repeat_weeks);
6353
			}
6354
		}
6355
	}
6356
	
6357
	if (isset($gd_post['recurring_dates'])) {
6358
		unset($gd_post['recurring_dates']);
6359
	}
6360
6361
	$gd_post['is_recurring'] = $is_recurring;
6362
	$gd_post['event_date'] = $event_date;
6363
	$gd_post['event_start'] = $event_date;
6364
	$gd_post['event_end'] = $event_enddate;
6365
	$gd_post['all_day'] = $all_day;
6366
	$gd_post['starttime'] = $starttime;
6367
	$gd_post['endtime'] = $endtime;
6368
	
6369
	$gd_post['repeat_type'] = $repeat_type;
6370
	$gd_post['different_times'] = $different_times;
6371
	$gd_post['starttimes'] = $starttimes;
6372
	$gd_post['endtimes'] = $endtimes;
6373
	$gd_post['repeat_days'] = $repeat_days;
6374
	$gd_post['repeat_weeks'] = $repeat_weeks;
6375
	$gd_post['event_recurring_dates'] = $event_recurring_dates;
6376
	$gd_post['repeat_x'] = $repeat_x;
6377
	$gd_post['duration_x'] = $duration_x;
6378
	$gd_post['repeat_end_type'] = $repeat_end_type;
6379
	$gd_post['max_repeat'] = $max_repeat;
6380
	$gd_post['repeat_end'] = $repeat_end;
6381
6382
	return $gd_post;
6383
}
6384
6385
/**
6386
 * Create a page.
6387
 *
6388
 * @since 1.0.0
6389
 * @package GeoDirectory
6390
 * @global object $wpdb WordPress Database object.
6391
 * @global object $current_user Current user object.
6392
 * @param string $slug The page slug.
6393
 * @param string $option The option meta key.
6394
 * @param string $page_title The page title.
6395
 * @param string $page_content The page description.
6396
 * @param int $post_parent Parent page ID.
6397
 * @param string $status Post status.
6398
 */
6399
function geodir_create_page($slug, $option, $page_title = '', $page_content = '', $post_parent = 0, $status = 'publish') {
6400 1
    global $wpdb, $current_user;
6401
6402 1
    $option_value = get_option($option);
6403
6404 1
    if ($option_value > 0) :
6405
        if (get_post($option_value)) :
6406
            // Page exists
6407
            return;
6408
        endif;
6409
    endif;
6410
6411 1
    $page_found = $wpdb->get_var(
6412 1
        $wpdb->prepare(
6413 1
            "SELECT ID FROM " . $wpdb->posts . " WHERE post_name = %s LIMIT 1;",
6414 1
            array($slug)
6415 1
        )
6416 1
    );
6417
6418 1
    if ($page_found) :
6419
        // Page exists
6420 1
        if (!$option_value) update_option($option, $page_found);
6421 1
        return;
6422
    endif;
6423
6424
    $page_data = array(
6425
        'post_status' => $status,
6426
        'post_type' => 'page',
6427
        'post_author' => $current_user->ID,
6428
        'post_name' => $slug,
6429
        'post_title' => $page_title,
6430
        'post_content' => $page_content,
6431
        'post_parent' => $post_parent,
6432
        'comment_status' => 'closed'
6433
    );
6434
    $page_id = wp_insert_post($page_data);
6435
6436
    add_option($option, $page_id);
6437
6438
}
6439
6440
/**
6441
 * Get WPML original translation element id.
6442
 *
6443
 * @since 1.5.3
6444
 *
6445
 * @global object $sitepress Sitepress WPML object.
6446
 *
6447
 * @param int $element_id Post ID or Term id.
6448
 * @param string $element_type Element type. Ex: post_gd_place or tax_gd_placecategory.
6449
 * @return Original element id.
6450
 */
6451
function geodir_imex_original_post_id($element_id, $element_type) {
6452
	global $sitepress;
6453
	
6454
	$original_element_id = $sitepress->get_original_element_id($element_id, $element_type);
6455
	$element_id = $element_id != $original_element_id ? $original_element_id : '';
6456
	
6457
	return $element_id;
6458
}
6459
6460
/*
6461
 * Show admin notice if core is out of date for the current addons.
6462
 *
6463
 * @since 1.5.4
6464
 * @package GeoDirectory
6465
 */
6466
function geodir_admin_upgrade_notice() {
6467
    $class = "error";
6468
    $message = __("Please update core GeoDirectory or some addons may not function correctly.","geodirectory");
6469
    echo"<div class=\"$class\"> <p>$message</p></div>";
6470
}
6471
6472
/**
6473
 * Displays an update message for plugin list screens.
6474
 * Shows only the version updates from the current until the newest version
6475
 *
6476
 * @param (array) $plugin_data
6477
 * @param (object) $r
6478
 * @return (string) $output
6479
 */
6480
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...
6481
{
6482
    // readme contents
6483
    $args = array(
6484
        'timeout'     => 15,
6485
        'redirection' => 5
6486
    );
6487
    $url = "http://plugins.svn.wordpress.org/geodirectory/trunk/readme.txt";
6488
    $data       = wp_remote_get( $url, $args );
6489
6490
    if (!is_wp_error($data) && $data['response']['code'] == 200) {
6491
6492
        geodir_in_plugin_update_message($data['body']);
6493
    }
6494
}
6495
6496
6497
/*
6498
* @param string $content http response body
6499
*/
6500
function geodir_in_plugin_update_message($content) {
6501
    // Output Upgrade Notice
6502
    $matches        = null;
6503
    $regexp         = '~==\s*Upgrade Notice\s*==\s*=\s*(.*)\s*=(.*)(=\s*' . preg_quote( GEODIRECTORY_VERSION ) . '\s*=|$)~Uis';
6504
    $upgrade_notice = '';
6505
    if ( preg_match( $regexp, $content, $matches ) ) {
6506
        if(empty($matches)){return;}
6507
6508
        $version = trim( $matches[1] );
6509
        if($version && $version>GEODIRECTORY_VERSION){
6510
6511
6512
        $notices = (array) preg_split('~[\r\n]+~', trim( $matches[2] ) );
6513
        if ( version_compare( GEODIRECTORY_VERSION, $version, '<' ) ) {
6514
            $upgrade_notice .= '<div class="geodir_plugin_upgrade_notice">';
6515
            foreach ( $notices as $index => $line ) {
6516
                $upgrade_notice .= wp_kses_post( preg_replace( '~\[([^\]]*)\]\(([^\)]*)\)~', '<a href="${2}">${1}</a>', $line ) );
6517
            }
6518
            $upgrade_notice .= '</div> ';
6519
        }
6520
        }
6521
    }
6522
    echo $upgrade_notice;
6523
}
6524
6525
/**
6526
 * Display notice on geodirectory permalink settings page to don't pages settings on a different language when wpml is active.
6527
 *
6528
 * @package GeoDirectory
6529
 * @since 1.5.7
6530
 *
6531
 * @global object $sitepress Sitepress WPML object.
6532
 */
6533
function geodir_wpml_permalink_setting_notice() {
6534
	if (geodir_is_wpml()) {
6535
		global $sitepress;
6536
		$current_language = $sitepress->get_current_language();
6537
		$default_language = $sitepress->get_default_language();
6538
		if ($current_language != 'all' && $current_language != $default_language) {
6539
	?>
6540
	<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>
6541
	<?php
6542
		}
6543
	}
6544
}
6545
6546
/**
6547
 * Get the statuses to skip during GD export listings.
6548
 *
6549
 * @package GeoDirectory
6550
 * @since 1.6.0
6551
 *
6552
 * @param array Listing statuses to be skipped.
6553
 */
6554
function geodir_imex_export_skip_statuses() {
6555 1
    $statuses = array( 'trash', 'auto-draft' );
6556
    
6557
    /**
6558
     * Filter the statuses to skip during GD export listings.
6559
     *
6560
     * @since 1.6.0
6561
     * @package GeoDirectory
6562
     *
6563
     * @param array $statuses Listing statuses to be skipped.
6564
     */
6565 1
    $statuses = apply_filters( 'geodir_imex_export_skip_statuses', $statuses );
6566
     
6567 1
    return $statuses;
6568
}
6569
6570
/*
6571
 * Look at doing menu items this way, must be customiser ready
6572
 * @todo research below
6573
 */
6574
// 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...
6575
/*
6576
6577
function geodir_register_menu_metabox() {
6578
    $custom_param = array( 0 => 'This param will be passed to my_render_menu_metabox' );
6579
6580
    add_meta_box( 'geodir-menu-metabox', 'GeoDirectory Items', 'geodir_render_menu_metabox', 'nav-menus', 'side', 'default', $custom_param );
6581
}
6582
add_action( 'admin_head-nav-menus.php', 'geodir_register_menu_metabox' );
6583
if(is_admin()){
6584
6585
    //add_action( 'customize_register', 'geodir_register_menu_metabox' );
6586
}
6587
*/
6588
/**
6589
 * Displays a menu metabox
6590
 *
6591
 * @param string $object Not used.
6592
 * @param array $args Parameters and arguments. If you passed custom params to add_meta_box(),
6593
 * they will be in $args['args']
6594
 */
6595
/*
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...
6596
function geodir_render_menu_metabox( $object, $args ) {
6597
    global $nav_menu_selected_id;
6598
6599
    // Create an array of objects that imitate Post objects
6600
    $my_items = array(
6601
        (object) array(
6602
            'ID' => 0,
6603
            'db_id' => 0,
6604
            'menu_item_parent' => 0,
6605
            'object_id' => 1,
6606
            'post_parent' => 0,
6607
            'type' => 'custom',
6608
            'object' => 'my-object-slug',
6609
            'type_label' => 'My Cool Plugin',
6610
            'title' => 'Custom Link 1',
6611
            'url' => home_url( '/jobs/' ),
6612
            'target' => '',
6613
            'attr_title' => '',
6614
            'description' => '123',
6615
            'classes' => array(),
6616
            'xfn' => '',
6617
        ),
6618
        (object) array(
6619
            'ID' => 2,
6620
            'db_id' => 0,
6621
            'menu_item_parent' => 0,
6622
            'object_id' => 1,
6623
            'post_parent' => 0,
6624
            'type' => 'custom',
6625
            'object' => 'my-object-slug',
6626
            'type_label' => 'My Cool Plugin',
6627
            'title' => 'Custom Link 2',
6628
            'url' => home_url( '/custom-link-2/' ),
6629
            'target' => '',
6630
            'attr_title' => '',
6631
            'description' => '123',
6632
            'classes' => array(),
6633
            'xfn' => '',
6634
        ),
6635
        (object) array(
6636
            'ID' => 3,
6637
            'db_id' => 0,
6638
            'menu_item_parent' => 0,
6639
            'object_id' => 1,
6640
            'post_parent' => 0,
6641
            'type' => 'custom',
6642
            'object' => 'my-object-slug',
6643
            'type_label' => 'My Cool Plugin',
6644
            'title' => 'Custom Link 3',
6645
            'url' => home_url( '/custom-link-3/' ),
6646
            'target' => '',
6647
            'attr_title' => '',
6648
            'description' => '123',
6649
            'classes' => array(),
6650
            'xfn' => '',
6651
        ),
6652
    );
6653
    $db_fields = false;
6654
    // If your links will be hierarchical, adjust the $db_fields array bellow
6655
    if ( false ) {
6656
        $db_fields = array( 'parent' => 'parent', 'id' => 'post_parent' );
6657
    }
6658
    $walker = new Walker_Nav_Menu_Checklist( $db_fields );
6659
6660
    $removed_args = array(
6661
        'action',
6662
        'customlink-tab',
6663
        'edit-menu-item',
6664
        'menu-item',
6665
        'page-tab',
6666
        '_wpnonce',
6667
    ); ?>
6668
    <div id="my-plugin-div">
6669
    <div id="tabs-panel-my-plugin-all" class="tabs-panel tabs-panel-active">
6670
        <ul id="my-plugin-checklist-pop" class="categorychecklist form-no-clear" >
6671
            <?php echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $my_items ), 0, (object) array( 'walker' => $walker ) ); ?>
6672
        </ul>
6673
6674
        <p class="button-controls">
6675
			<span class="list-controls">
6676
				<a href="<?php
6677
                echo esc_url(add_query_arg(
6678
                    array(
6679
                        'my-plugin-all' => 'all',
6680
                        'selectall' => 1,
6681
                    ),
6682
                    remove_query_arg( $removed_args )
6683
                ));
6684
                ?>#my-menu-test-metabox" class="select-all"><?php _e( 'Select All' ); ?></a>
6685
			</span>
6686
6687
			<span class="add-to-menu">
6688
				<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" />
6689
				<span class="spinner"></span>
6690
			</span>
6691
        </p>
6692
    </div>
6693
<?php
6694
}
6695
*/