Test Failed
Pull Request — master (#238)
by Kiran
09:22
created

admin_functions.php ➔ geodir_admin_scripts()   D

Complexity

Conditions 10
Paths 128

Size

Total Lines 135
Code Lines 84

Duplication

Lines 24
Ratio 17.78 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 4
Bugs 0 Features 3
Metric Value
cc 10
eloc 84
c 4
b 0
f 3
nc 128
nop 0
dl 24
loc 135
ccs 0
cts 76
cp 0
crap 110
rs 4.606

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