Test Failed
Push — master ( 64d34c...cb55f8 )
by Stiofan
18:24
created

post_functions.php ➔ geodir_favourite_html()   D

Complexity

Conditions 9
Paths 18

Size

Total Lines 97
Code Lines 30

Duplication

Lines 4
Ratio 4.12 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 30
nc 18
nop 2
dl 4
loc 97
ccs 0
cts 22
cp 0
crap 90
rs 4.9219
c 0
b 0
f 0

How to fix   Long Method   

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
 * Post Listing functions.
4
 *
5
 * @since 1.0.0
6
 * @package GeoDirectory
7
 */
8
9
10
/**
11
 * Set post category structure based on given parameters.
12
 *
13
 * @since 1.0.0
14
 * @package GeoDirectory
15
 * @param int $post_id The post ID.
16
 * @param string $taxonomy Name of the taxonomy e.g place_category.
17
 * @param string|int $default_cat Optional. The default category ID.
18
 * @param array|string $category_str Optional. Blank string if no categories. Else array of categories to set.
19
 */
20
function geodir_set_postcat_structure($post_id, $taxonomy, $default_cat = '', $category_str = '')
21
{
22
23
    $post_cat_ids = geodir_get_post_meta($post_id, $taxonomy);
24
    if (!empty($post_cat_ids))
25
        $post_cat_array = explode(",", trim($post_cat_ids, ","));
26
27
    if (!isset($default_cat) || empty($default_cat)) {
28
        $default_cat = isset($post_cat_array[0]) ? $post_cat_array[0] : '';
29
    }else{
30
        if(!is_int($default_cat)){
31
            $category = get_term_by('name', $default_cat, $taxonomy);
32
            if(isset($category->term_id)){
33
                $default_cat =  $category->term_id;
34
            }
35
        }
36
37
    }
38
39
40
    geodir_save_post_meta($post_id, 'default_category', $default_cat);
41
42
    if (isset($category_str) && empty($category_str)) {
43
44
        $post_cat_str = '';
45
        $post_categories = array();
46
        if (isset($post_cat_array) && is_array($post_cat_array) && !empty($post_cat_array)) {
47
            $post_cat_str = implode(",y:#", $post_cat_array);
48
            $post_cat_str .= ",y:";
49
            $post_cat_str = substr_replace($post_cat_str, ',y,d:', strpos($post_cat_str, ',y:'), strlen(',y:'));
50
        }
51
        $post_categories[$taxonomy] = $post_cat_str;
52
        $category_str = $post_categories;
53
    }
54
55
    $change_cat_str = $category_str[$taxonomy];
56
57
    $default_pos = strpos($change_cat_str, 'd:');
58
59
    if ($default_pos === false) {
60
61
        $change_cat_str = str_replace($default_cat . ',y:', $default_cat . ',y,d:', $change_cat_str);
62
63
    }
64
65
    $category_str[$taxonomy] = $change_cat_str;
66
67
    update_post_meta($post_id, 'post_categories', $category_str);
68
69
}
70
71
72
if (!function_exists('geodir_save_listing')) {
73
    /**
74
     * Saves listing in the database using given information.
75
     *
76
     * @since 1.0.0
77
     * @since 1.5.4 New parameter $wp_error added.
78
     * @since 1.6.18 Admin use only date field should not lost value if saved by user - FIXED
79
     * @package GeoDirectory
80
     * @global object $wpdb WordPress Database object.
81
     * @global object $post The current post object.
82
     * @global object $current_user Current user object.
83
     * @global object $gd_session GeoDirectory Session object.
84
     * @param array $request_info {
85
     *    Array of request info arguments.
86
     *
87
     *    @type string $action                                  Ajax action name.
88
     *    @type string $geodir_ajax                             Ajax type.
89
     *    @type string $ajax_action                             Ajax action.
90
     *    @type string $listing_type                            Listing type.
91
     *    @type string $pid                                     Default Post ID.
92
     *    @type string $preview                                 Todo Desc needed.
93
     *    @type string $add_listing_page_id                     Add listing page ID.
94
     *    @type string $post_title                              Listing title.
95
     *    @type string $post_desc                               Listing Description.
96
     *    @type string $post_tags                               Listing tags.
97
     *    @type array  $cat_limit                               Category limit.
98
     *    @type array  $post_category                           Category IDs.
99
     *    @type array  $post_category_str                       Category string.
100
     *    @type string $post_default_category                   Default category ID.
101
     *    @type string $post_address                            Listing address.
102
     *    @type string $geodir_location_add_listing_country_val Add listing country value.
103
     *    @type string $post_country                            Listing country.
104
     *    @type string $geodir_location_add_listing_region_val  Add listing region value.
105
     *    @type string $post_region                             Listing region.
106
     *    @type string $geodir_location_add_listing_city_val    Add listing city value.
107
     *    @type string $post_city                               Listing city.
108
     *    @type string $post_zip                                Listing zip.
109
     *    @type string $post_latitude                           Listing latitude.
110
     *    @type string $post_longitude                          Listing longitude.
111
     *    @type string $post_mapview                            Listing mapview. Default "ROADMAP".
112
     *    @type string $post_mapzoom                            Listing mapzoom Default "9".
113
     *    @type string $geodir_timing                           Business timing info.
114
     *    @type string $geodir_contact                          Contact number.
115
     *    @type string $geodir_email                            Business contact email.
116
     *    @type string $geodir_website                          Business website.
117
     *    @type string $geodir_twitter                          Twitter link.
118
     *    @type string $geodir_facebook                         Facebook link.
119
     *    @type string $geodir_video                            Video link.
120
     *    @type string $geodir_special_offers                   Special offers.
121
     *    @type string $post_images                             Post image urls.
122
     *    @type string $post_imagesimage_limit                  Post images limit.
123
     *    @type string $post_imagestotImg                       Todo Desc needed.
124
     *    @type string $geodir_accept_term_condition            Has accepted terms and conditions?.
125
     *    @type string $geodir_spamblocker                      Todo Desc needed.
126
     *    @type string $geodir_filled_by_spam_bot               Todo Desc needed.
127
     *
128
     * }
129
     * @param bool $dummy Optional. Is this a dummy listing? Default false.
130
     * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
131
     * @return int|string|WP_Error Created post id or WP_Error on failure.
132
     */
133
    function geodir_save_listing($request_info = array(), $dummy = false, $wp_error = false)
134
    {
135 3
        global $wpdb, $current_user, $gd_session;
136
137 3
        $last_post_id = '';
0 ignored issues
show
Unused Code introduced by
$last_post_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...
138
139 3
        if ($gd_session->get('listing') && !$dummy) {
140
            $request_info = array();
0 ignored issues
show
Unused Code introduced by
$request_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...
141
            $request_session = $gd_session->get('listing');
142
            $request_info = array_merge($_REQUEST, $request_session);
143 3
        } else if (!$gd_session->get('listing') && !$dummy) {
144
            global $post;
145
            
146
            $gd_post = $post;
147
            if (!empty($gd_post) && is_array($gd_post)) {
148
                $gd_post = (object)$post;
149
                
150
                // Fix WPML duplicate.
151
                if (geodir_is_wpml() && !empty($request_info['action']) && $request_info['action'] == 'editpost' && !empty($request_info['icl_trid']) && !isset($post['post_date'])) {
152
                    return false;
153
                }
154
            }
155
            
156
            $request_info['pid'] = !empty($gd_post->ID) ? $gd_post->ID : (!empty($request_info['post_id']) ? $request_info['post_id'] : NULL);
157
            $request_info['post_title'] = $request_info['post_title'];
158
            $request_info['listing_type'] = !empty($gd_post->post_type) ? $gd_post->post_type : (!empty($request_info['post_type']) ? $request_info['post_type'] : get_post_type($request_info['pid']));
159
            $request_info['post_desc'] = $request_info['content'];
160 3
        } else if (!$dummy) {
161
            return false;
162
        }
163
164
        /**
165
         * Filter the request_info array.
166
         *
167
         * You can use this filter to modify request_info array.
168
         *
169
         * @since 1.0.0
170
         * @package GeoDirectory
171
         * @param array $request_info See {@see geodir_save_listing()} for accepted args.
172
         */
173 3
        $request_info = apply_filters('geodir_action_get_request_info', $request_info);
174
175
        // Check if we need to save post location as new location
176 3
        $location_result = geodir_get_default_location();
177
178 3
        if ($location_result->location_id > 0) {
179
            if (isset($request_info['post_city']) && isset($request_info['post_region'])) {
180
                $request_info['post_location'] = array(
181
                    'city' => $request_info['post_city'],
182
                    'region' => isset($request_info['post_region']) ? $request_info['post_region'] : '',
183
                    'country' => isset($request_info['post_country']) ? $request_info['post_country'] : '',
184
                    'geo_lat' => isset($request_info['post_latitude']) ? $request_info['post_latitude'] : '',
185
                    'geo_lng' => isset($request_info['post_longitude']) ? $request_info['post_longitude'] : ''
186
                );
187
188
                $post_location_info = $request_info['post_location'];
189
190
                if ($location_id = geodir_add_new_location($post_location_info)) {
191
                    $post_location_id = $location_id;
192
                }
193
            } else {
194
                $post_location_id = $location_result->location_id;
195
            }
196
        } else {
197 3
            $post_location_id = $location_result->location_id;
198
        }
199
200 3
        if ($dummy) {
201 3
            $post_status = 'publish';
202 3
        } else {
203
            $post_status = geodir_new_post_default_status();
204
        }
205
206 3
        if (isset($request_info['pid']) && $request_info['pid'] != '') {
207
            $post_status = get_post_status($request_info['pid']);
208
        }
209
210
        /* fix change of slug on every title edit */
211 3
        if (!isset($request_info['post_name'])) {
212 3
            $request_info['post_name'] = $request_info['post_title'];
213
214 3
            if (!empty($request_info['pid'])) {
215
                $post_info = get_post($request_info['pid']);
216
217
                if (!empty($post_info) && isset($post_info->post_name)) {
218
                    $request_info['post_name'] = $post_info->post_name;
219
                }
220
            }
221 3
        }
222
223
        $post = array(
224 3
            'post_content' => $request_info['post_desc'],
225 3
            'post_status' => $post_status,
226 3
            'post_title' => $request_info['post_title'],
227 3
            'post_name' => $request_info['post_name'],
228 3
            'post_type' => $request_info['listing_type']
229 3
        );
230
231
        /**
232
         * Called before a listing is saved to the database.
233
         *
234
         * @since 1.0.0
235
         * @param object $post The post object.
236
         */
237 3
        do_action_ref_array('geodir_before_save_listing', $post);
238
239 3
        $send_post_submit_mail = false;
240
241
        // unhook this function so it doesn't loop infinitely
242 3
        remove_action('save_post', 'geodir_post_information_save',10,2);
243
244 3
        if (isset($request_info['pid']) && $request_info['pid'] != '') {
245
            $post['ID'] = $request_info['pid'];
246
247
            $last_post_id = wp_update_post($post, $wp_error);
248
        } else {
249 3
            $last_post_id = wp_insert_post($post, $wp_error);
250
251 3
            if (!$dummy && $last_post_id) {
252
                $send_post_submit_mail = true; // we move post_submit email from here so the rest of the variables are added to the db first(was breaking permalink in email)
253
                //geodir_sendEmail('','',$current_user->user_email,$current_user->display_name,'','',$request_info,'post_submit',$last_post_id,$current_user->ID);
0 ignored issues
show
Unused Code Comprehensibility introduced by
87% 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...
254
            }
255
        }
256
257 3
        if ($wp_error && is_wp_error($last_post_id)) {
258
            return $last_post_id; // Return WP_Error on save failure.
259
        }
260
261 3
        if (!$last_post_id) {
262
            return false; // Save failure.
263
        }
264
265
        // re-hook this function
266 3
        add_action('save_post', 'geodir_post_information_save',10,2);
267
268 3
        $post_tags = '';
269 3
        if (!isset($request_info['post_tags'])) {
270
271
            $post_type = $request_info['listing_type'];
272
            $post_tags = implode(",", wp_get_object_terms($last_post_id, $post_type . '_tags', array('fields' => 'names')));
273
274
        }
275
276
        $gd_post_info = array(
277 3
            "post_title" => $request_info['post_title'],
278 3
            "post_tags" => isset($request_info['post_tags']) ? $request_info['post_tags'] : $post_tags,
279 3
            "post_status" => $post_status,
280 3
            "post_location_id" => $post_location_id,
0 ignored issues
show
Bug introduced by
The variable $post_location_id 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...
281 3
            "claimed" => isset($request_info['claimed']) ? $request_info['claimed'] : '',
282 3
            "businesses" => isset($request_info['a_businesses']) ? $request_info['a_businesses'] : '',
283 3
            "submit_time" => time(),
284 3
            "submit_ip" => $_SERVER['REMOTE_ADDR'],
285 3
        );
286
287 3
        $payment_info = array();
288 3
        $package_info = array();
289
290 3
        $package_info = (array)geodir_post_package_info($package_info, $post);
291
292 3
        $post_package_id = geodir_get_post_meta($last_post_id, 'package_id');
293
294 3
        if (!empty($package_info) && !$post_package_id) {
295 3
            if (isset($package_info['days']) && $package_info['days'] != 0) {
296
                $payment_info['expire_date'] = date('Y-m-d', strtotime("+" . $package_info['days'] . " days"));
297
            } else {
298 3
                $payment_info['expire_date'] = 'Never';
299
            }
300
301 3
            $payment_info['package_id'] = $package_info['pid'];
302 3
            $payment_info['alive_days'] = $package_info['days'];
303 3
            $payment_info['is_featured'] = $package_info['is_featured'];
304
305 3
            $gd_post_info = array_merge($gd_post_info, $payment_info);
306 3
        }
307
308 3
        $custom_metaboxes = geodir_post_custom_fields('', 'all', $request_info['listing_type']);
309
310 3
        foreach ($custom_metaboxes as $key => $val):
311
312 3
            $name = $val['name'];
313 3
            $type = $val['type'];
314 3
            $extrafields = $val['extra_fields'];
315
316 3
            if (trim($type) == 'address') {
317 3
                $prefix = $name . '_';
318 3
                $address = $prefix . 'address';
319
320 3
                if (isset($request_info[$address]) && $request_info[$address] != '') {
321 3
                    $gd_post_info[$address] = wp_slash($request_info[$address]);
322 3
                }
323
324 3
                if ($extrafields != '') {
325 3
                    $extrafields = unserialize($extrafields);
326
327
328 3
                    if (!isset($request_info[$prefix . 'city']) || $request_info[$prefix . 'city'] == '') {
329
330 3
                        $location_result = geodir_get_default_location();
331
332 3
                        $gd_post_info[$prefix . 'city'] = $location_result->city;
333 3
                        $gd_post_info[$prefix . 'region'] = $location_result->region;
334 3
                        $gd_post_info[$prefix . 'country'] = $location_result->country;
335
336 3
                        $gd_post_info['post_locations'] = '[' . $location_result->city_slug . '],[' . $location_result->region_slug . '],[' . $location_result->country_slug . ']'; // set all overall post location
337
338 3
                    } else {
339
340
                        $gd_post_info[$prefix . 'city'] = $request_info[$prefix . 'city'];
341
                        $gd_post_info[$prefix . 'region'] = $request_info[$prefix . 'region'];
342
                        $gd_post_info[$prefix . 'country'] = $request_info[$prefix . 'country'];
343
344
                        //----------set post locations when import dummy data-------
345
                        $location_result = geodir_get_default_location();
346
347
                        $gd_post_info['post_locations'] = '[' . $location_result->city_slug . '],[' . $location_result->region_slug . '],[' . $location_result->country_slug . ']'; // set all overall post location
348
                        //-----------------------------------------------------------------
349
350
                    }
351
352
353 3 View Code Duplication
                    if (isset($extrafields['show_zip']) && $extrafields['show_zip'] && isset($request_info[$prefix . 'zip'])) {
354 3
                        $gd_post_info[$prefix . 'zip'] = $request_info[$prefix . 'zip'];
355 3
                    }
356
357
358 3
                    if (isset($extrafields['show_map']) && $extrafields['show_map']) {
359
360 3 View Code Duplication
                        if (isset($request_info[$prefix . 'latitude']) && $request_info[$prefix . 'latitude'] != '') {
361 1
                            $gd_post_info[$prefix . 'latitude'] = $request_info[$prefix . 'latitude'];
362 1
                        }
363
364 3 View Code Duplication
                        if (isset($request_info[$prefix . 'longitude']) && $request_info[$prefix . 'longitude'] != '') {
365 1
                            $gd_post_info[$prefix . 'longitude'] = $request_info[$prefix . 'longitude'];
366 1
                        }
367
368 3 View Code Duplication
                        if (isset($request_info[$prefix . 'mapview']) && $request_info[$prefix . 'mapview'] != '') {
369 3
                            $gd_post_info[$prefix . 'mapview'] = $request_info[$prefix . 'mapview'];
370 3
                        }
371
372 3 View Code Duplication
                        if (isset($request_info[$prefix . 'mapzoom']) && $request_info[$prefix . 'mapzoom'] != '') {
373 3
                            $gd_post_info[$prefix . 'mapzoom'] = $request_info[$prefix . 'mapzoom'];
374 3
                        }
375
376 3
                    }
377
378
                    // show lat lng
379 3 View Code Duplication
                    if (isset($extrafields['show_latlng']) && $extrafields['show_latlng'] && isset($request_info[$prefix . 'latlng'])) {
380
                        $gd_post_info[$prefix . 'latlng'] = $request_info[$prefix . 'latlng'];
381
                    }
382 3
                }
383
384 3
            } elseif (trim($type) == 'file') {
385
                if (isset($request_info[$name])) {
386
                    $request_files = array();
387
                    if ($request_info[$name] != '')
388
                        $request_files = explode(",", $request_info[$name]);
389
390
                    $extrafields = $extrafields != '' ? maybe_unserialize($extrafields) : NULL;
391
                    geodir_save_post_file_fields($last_post_id, $name, $request_files, $extrafields);
392
                }
393 3
            } elseif (trim($type) == 'datepicker') {
394
                if (isset($request_info[$name])) {
395
                    $datetime = '';
396
                    
397
                    if (!empty($request_info[$name])) {
398
                        $date_format = geodir_default_date_format();
399
                        if (isset($val['extra_fields']) && $val['extra_fields'] != '') {
400
                            $extra_fields = unserialize($val['extra_fields']);
401
                            $date_format = isset($extra_fields['date_format']) && $extra_fields['date_format'] != '' ? $extra_fields['date_format'] : $date_format;
402
                        }
403
404
                        // check if we need to change the format or not
405
                        $date_format_len = strlen(str_replace(' ', '', $date_format));
406
                        if($date_format_len>5){// if greater then 5 then it's the old style format.
407
408
                            $search = array('dd','d','DD','mm','m','MM','yy'); //jQuery UI datepicker format
409
                            $replace = array('d','j','l','m','n','F','Y');//PHP date format
410
411
                            $date_format = str_replace($search, $replace, $date_format);
412
413
                            $post_htmlvar_value = $date_format == 'd/m/Y' ? str_replace('/', '-', $request_info[$name]) : $request_info[$name];
414
415
                        }else{
416
                            $post_htmlvar_value = $request_info[$name];
417
                        }
418
419
                        $post_htmlvar_value = geodir_date($post_htmlvar_value, 'Y-m-d', $date_format); // save as sql format Y-m-d
420
                        $datetime = geodir_maybe_untranslate_date($post_htmlvar_value); // maybe untranslate date string if it was translated
421
                    }
422
423
                    $gd_post_info[$name] = $datetime;
424
                }
425 3
            } else if ($type == 'multiselect') {
426
                if (isset($request_info[$name])) {
427
                    $gd_post_info[$name] = $request_info[$name];
428
                } else {
429
                    if (isset($request_info['gd_field_' . $name])) {
430
                        $gd_post_info[$name] = ''; /* fix de-select for multiselect */
431
                    }
432
                }
433 3
            } else if (isset($request_info[$name])) {
434 3
                $gd_post_info[$name] = $request_info[$name];
435 3
            }
436
437 3
        endforeach;
438
439 3
        if (isset($request_info['post_dummy']) && $request_info['post_dummy'] != '') {
440
            $gd_post_info['post_dummy'] = $request_info['post_dummy'];
441
        }
442
443
        // Save post detail info in detail table
444 3
        if (!empty($gd_post_info)) {
445 3
            geodir_save_post_info($last_post_id, $gd_post_info);
446 3
        }
447
448
449
        // Set categories to the listing
450 3
        if (isset($request_info['post_category']) && !empty($request_info['post_category'])) {
451
            $post_category = array();
452
453
            foreach ($request_info['post_category'] as $taxonomy => $cat) {
454
455
                if ($dummy)
456
                    $post_category = $cat;
457
                else {
458
459
                    if (!is_array($cat) && strstr($cat, ','))
460
                        $cat = explode(',', $cat);
461
462
                    if (!empty($cat) && is_array($cat))
463
                        $post_category = array_map('intval', $cat);
464
                }
465
466
                wp_set_object_terms($last_post_id, $post_category, $taxonomy);
467
            }
468
469
            $post_default_category = isset($request_info['post_default_category']) ? $request_info['post_default_category'] : '';
470
471
            $post_category_str = isset($request_info['post_category_str']) ? $request_info['post_category_str'] : '';
472
            geodir_set_postcat_structure($last_post_id, $taxonomy, $post_default_category, $post_category_str);
0 ignored issues
show
Bug introduced by
The variable $taxonomy seems to be defined by a foreach iteration on line 453. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
473
474
        }
475
476 3
        $post_tags = '';
477
        // Set tags to the listing
478 3
        if (isset($request_info['post_tags']) && !is_array($request_info['post_tags']) && !empty($request_info['post_tags'])) {
479 3
            $post_tags = explode(",", $request_info['post_tags']);
480 3
        } elseif (isset($request_info['post_tags']) && is_array($request_info['post_tags'])) {
481
            if ($dummy)
482
                $post_tags = $request_info['post_tags'];
483
        } else {
484
            if ($dummy)
485
                $post_tags = array($request_info['post_title']);
486
        }
487
488 3
        if (is_array($post_tags)) {
489 3
            $taxonomy = $request_info['listing_type'] . '_tags';
490 3
            wp_set_object_terms($last_post_id, $post_tags, $taxonomy);
491 3
        }
492
493
494
        // Insert attachment
495
496 3
        if (isset($request_info['post_images']) && !is_wp_error($last_post_id)) {
497
            if (!$dummy) {
498
                $tmpimgArr = trim($request_info['post_images'], ",");
499
                $tmpimgArr = explode(",", $tmpimgArr);
500
                geodir_save_post_images($last_post_id, $tmpimgArr, $dummy);
501
            } else{
502
                geodir_save_post_images($last_post_id, $request_info['post_images'], $dummy);
503
            }
504
505
506 3
        } elseif (!isset($request_info['post_images']) || $request_info['post_images'] == '') {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
507
508
            /* Delete Attachments
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...
509
			$postcurr_images = geodir_get_images($last_post_id);
510
511
			$wpdb->query(
512
				$wpdb->prepare(
513
					"DELETE FROM ".GEODIR_ATTACHMENT_TABLE." WHERE `post_id` = %d",
514
					array($last_post_id)
515
				)
516
			);
517
			geodir_remove_attachments($postcurr_images);
518
519
			$gd_post_featured_img = array();
520
			$gd_post_featured_img['featured_image'] = '';
521
			geodir_save_post_info($last_post_id, $gd_post_featured_img);
522
			*/
523
524 3
        }
525
526 3
        geodir_remove_temp_images();
527 3
        geodir_set_wp_featured_image($last_post_id);
528
529
        /**
530
         * Called after a listing is saved to the database and before any email have been sent.
531
         *
532
         * @since 1.0.0
533
         * @param int $last_post_id The saved post ID.
534
         * @param array $request_info The post details in an array.
535
         * @see 'geodir_after_save_listinginfo'
536
         */
537 3
        do_action('geodir_after_save_listing', $last_post_id, $request_info);
538
539
        //die;
540
541 3
        if ($send_post_submit_mail) { // if new post send out email
542
            $to_name = geodir_get_client_name($current_user->ID);
543
            geodir_sendEmail('', '', $current_user->user_email, $to_name, '', '', $request_info, 'post_submit', $last_post_id, $current_user->ID);
544
        }
545
        /*
546
         * Unset the session so we don't loop.
547
         */
548 3
        $gd_session->un_set('listing');
549 3
        return $last_post_id;
550
551
    }
552
553
}
554
555
556
/**
557
 * Get post custom fields.
558
 *
559
 * @since 1.0.0
560
 * @package GeoDirectory
561
 * @global object $wpdb WordPress Database object.
562
 * @global object $post The current post object.
563
 * @global string $plugin_prefix Geodirectory plugin table prefix.
564
 * @param int|string $post_id Optional. The post ID.
565
 * @return object|bool Returns full post details as an object. If no details returns false.
566
 */
567
function geodir_get_post_info($post_id = '')
568
{
569
570 3
    global $wpdb, $plugin_prefix, $post, $post_info;
571
572 3
    if ($post_id == '' && !empty($post))
573 3
        $post_id = $post->ID;
574
575 3
    $post_type = get_post_type($post_id);
576
577 3
    $all_postypes = geodir_get_posttypes();
578
579 3
    if (!in_array($post_type, $all_postypes))
580 3
        return false;
581
582 3
    $table = $plugin_prefix . $post_type . '_detail';
583
584
    /**
585
     * Apply Filter to change Post info
586
     *
587
     * You can use this filter to change Post info.
588
     *
589
     * @since 1.0.0
590
     * @package GeoDirectory
591
     */
592 3
    $query = apply_filters('geodir_post_info_query', $wpdb->prepare("SELECT p.*,pd.* FROM " . $wpdb->posts . " p," . $table . " pd
593
			  WHERE p.ID = pd.post_id
594 3
			  AND pd.post_id = %d", $post_id));
595
596 3
    $post_detail = $wpdb->get_row($query);
597
598 3
    return (!empty($post_detail)) ? $post_info = $post_detail : $post_info = false;
599
600
}
601
602
603
if (!function_exists('geodir_save_post_info')) {
604
    /**
605
     * Saves post detail info in detail table.
606
     *
607
     * @since 1.0.0
608
     * @package GeoDirectory
609
     * @global object $wpdb WordPress Database object.
610
     * @global string $plugin_prefix Geodirectory plugin table prefix.
611
     * @param int $post_id The post ID.
612
     * @param array $postinfo_array {
613
     *    Post info that needs to be saved in detail table.
614
     *
615
     *    @type string $post_title              Listing title.
616
     *    @type string $post_tags               Listing tags.
617
     *    @type string $post_status             Listing post status.
618
     *    @type string $post_location_id        Listing location ID.
619
     *    @type string $claimed                 Todo Desc needed.
620
     *    @type string $businesses              Todo Desc needed.
621
     *    @type int    $submit_time             Submitted time in unix timestamp.
622
     *    @type string $submit_ip               Submitted IP.
623
     *    @type string $expire_date             Listing expiration date.
624
     *    @type int    $package_id              Listing package ID.
625
     *    @type int    $alive_days              Todo Desc needed.
626
     *    @type int    $is_featured             Is this a featured listing?.
627
     *    @type string $post_address            Listing address.
628
     *    @type string $post_city               Listing city.
629
     *    @type string $post_region             Listing region.
630
     *    @type string $post_country            Listing country.
631
     *    @type string $post_locations          Listing locations.
632
     *    @type string $post_zip                Listing zip.
633
     *    @type string $post_latitude           Listing latitude.
634
     *    @type string $post_longitude          Listing longitude.
635
     *    @type string $post_mapview            Listing mapview. Default "ROADMAP".
636
     *    @type string $post_mapzoom            Listing mapzoom Default "9".
637
     *    @type string $geodir_timing           Business timing info.
638
     *    @type string $geodir_contact          Contact number.
639
     *    @type string $geodir_email            Business contact email.
640
     *    @type string $geodir_website          Business website.
641
     *    @type string $geodir_twitter          Twitter link.
642
     *    @type string $geodir_facebook         Facebook link.
643
     *    @type string $geodir_video            Video link.
644
     *    @type string $geodir_special_offers   Special offers.
645
     *
646
     * }
647
     * @return bool
648
     */
649
    function geodir_save_post_info($post_id, $postinfo_array = array())
650
    {
651 3
        global $wpdb, $plugin_prefix;
652
653 3
        $post_type = get_post_type($post_id);
654
655 3
        $table = $plugin_prefix . $post_type . '_detail';
656
657
        /**
658
         * Filter to change Post info
659
         *
660
         * You can use this filter to change Post info.
661
         *
662
         * @since 1.0.0
663
         * @package GeoDirectory
664
         * @param array $postinfo_array See {@see geodir_save_post_info()} for accepted args.
665
         * @param int $post_id The post ID.
666
         */
667 3
        $postmeta = apply_filters('geodir_listinginfo_request', $postinfo_array, $post_id);
668
669 3
        $query_string_escaped = '';
670 3
        $query_string_array = array();
671
672 3
        if (!empty($postmeta) && $post_id) {
673
674 3
            $columns = $wpdb->get_col("show columns from $table");
675 3
            foreach ($postmeta as $mkey => $mval) {
676 3
                if(in_array($mkey,$columns)) {
677 3
                    if (is_array($mval)) {
678
                        $mval = implode(",", $mval);
679
                    }
680 3
                    $query_string_escaped .= " $mkey = %s, "; // we can set the key here as we check if the column exists above
681 3
                    $query_string_array[] = stripslashes($mval); // we strip slashes as we are using wpdb prepare
682
683 3
                }
684 3
            }
685
686 3
            $query_string_escaped = trim($query_string_escaped, ", ");
687
688 3
            if (empty($query_string_array) || trim($query_string_escaped) == '') {
689
                return false;
690
            }
691
692 3
            $query_string_array = str_replace(array("'%", "%'"), array("'%%", "%%'"), $query_string_array);
693
694
695
            /**
696
             * Called before saving the listing info.
697
             *
698
             * @since 1.0.0
699
             * @package GeoDirectory
700
             * @param array $postinfo_array See {@see geodir_save_post_info()} for accepted args.
701
             * @param int $post_id The post ID.
702
             */
703 3
            do_action('geodir_before_save_listinginfo', $postinfo_array, $post_id);
704
705 3
            if ($wpdb->get_var($wpdb->prepare("SELECT post_id from " . $table . " where post_id = %d", array($post_id)))) {
706
707
                $query_string_array[] = $post_id;
708
                $wpdb->query(
709
                    $wpdb->prepare(
710
                        "UPDATE " . $table . " SET " . $query_string_escaped . " where post_id =%d",
711
                        $query_string_array
712
                    )
713
                );
714
715
716
            } else {
717
718 3
                array_unshift($query_string_array, $post_id);
719 3
                $wpdb->query(
720 3
                    $wpdb->prepare(
721 3
                        "INSERT INTO " . $table . " SET post_id = %d," . $query_string_escaped,
722
                        $query_string_array
723 3
                    )
724 3
                );
725
                
726
            }
727
728
            /**
729
             * Called after saving the listing info.
730
             *
731
             * @since 1.0.0
732
             * @package GeoDirectory
733
             * @param array $postinfo_array Post info that needs to be saved in detail table.
734
             * @param int $post_id The post ID.
735
             * @see 'geodir_after_save_listing'
736
             */
737 3
            do_action('geodir_after_save_listinginfo', $postinfo_array, $post_id);
738
739 3
            return true;
740
        } else
741
            return false;
742
743
    }
744
}
745
746
747
if (!function_exists('geodir_save_post_meta')) {
748
    /**
749
     * Save or update post custom fields.
750
     *
751
     * @since 1.0.0
752
     * @package GeoDirectory
753
     * @global object $wpdb WordPress Database object.
754
     * @global string $plugin_prefix Geodirectory plugin table prefix.
755
     * @param int $post_id The post ID.
756
     * @param string $postmeta Detail table column name.
757
     * @param string $meta_value Detail table column value.
758
     * @return void|bool
759
     */
760
    function geodir_save_post_meta($post_id, $postmeta = '', $meta_value = '')
761
    {
762
763
        global $wpdb, $plugin_prefix;
764
765
        $post_type = get_post_type($post_id);
766
767
        $table = $plugin_prefix . $post_type . '_detail';
768
769
        if ($postmeta != '' && geodir_column_exist($table, $postmeta) && $post_id) {
770
771
            if (is_array($meta_value)) {
772
                $meta_value = implode(",", $meta_value);
773
            }
774
775
            if ($wpdb->get_var($wpdb->prepare("SELECT post_id from " . $table . " where post_id = %d", array($post_id)))) {
776
777
                $wpdb->query(
778
                    $wpdb->prepare(
779
                        "UPDATE " . $table . " SET " . $postmeta . " = '" . $meta_value . "' where post_id =%d",
780
                        array($post_id)
781
                    )
782
                );
783
784
            } else {
785
786
                $wpdb->query(
787
                    $wpdb->prepare(
788
                        "INSERT INTO " . $table . " SET post_id = %d, " . $postmeta . " = '" . $meta_value . "'",
789
                        array($post_id)
790
                    )
791
                );
792
            }
793
794
795
        } else
796
            return false;
797
    }
798
}
799
800
if (!function_exists('geodir_delete_post_meta')) {
801
    /**
802
     * Delete post custom fields.
803
     *
804
     * @since 1.0.0
805
     * @package GeoDirectory
806
     * @global object $wpdb WordPress Database object.
807
     * @global string $plugin_prefix Geodirectory plugin table prefix.
808
     * @param int $post_id The post ID.
809
     * @param string $postmeta Detail table column name.
810
     * @todo check if this is depreciated
811
     * @todo Fix unknown variable mval
812
     * @return bool
813
     */
814
    function geodir_delete_post_meta($post_id, $postmeta)
815
    {
816
817
        global $wpdb, $plugin_prefix;
818
819
        $post_type = get_post_type($post_id);
820
821
        $table = $plugin_prefix . $post_type . '_detail';
822
823
        if (is_array($postmeta) && !empty($postmeta) && $post_id) {
824
            $post_meta_set_query = '';
825
826
            foreach ($postmeta as $mkey) {
827
                if ($mval != '')
0 ignored issues
show
Bug introduced by
The variable $mval does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
828
                    $post_meta_set_query .= $mkey . " = '', ";
829
            }
830
831
            $post_meta_set_query = trim($post_meta_set_query, ", ");
832
            
833
            if (empty($post_meta_set_query) || trim($post_meta_set_query) == '') {
834
                return false;
835
            }
836
837 View Code Duplication
            if ($wpdb->get_var("SHOW COLUMNS FROM " . $table . " WHERE field = '" . $postmeta . "'") != '') {
838
839
                $wpdb->query(
840
                    $wpdb->prepare(
841
                        "UPDATE " . $table . " SET " . $post_meta_set_query . " where post_id = %d",
842
                        array($post_id)
843
                    )
844
                );
845
846
                return true;
847
            }
848
849 View Code Duplication
        } elseif ($postmeta != '' && $post_id) {
850
            if ($wpdb->get_var("SHOW COLUMNS FROM " . $table . " WHERE field = '" . $postmeta . "'") != '') {
851
852
                $wpdb->query(
853
                    $wpdb->prepare(
854
                        "UPDATE " . $table . " SET " . $postmeta . "= '' where post_id = %d",
855
                        array($post_id)
856
                    )
857
                );
858
859
                return true;
860
            }
861
862
        } else
863
            return false;
864
    }
865
}
866
867
868
if (!function_exists('geodir_get_post_meta')) {
869
    /**
870
     * Get post custom meta.
871
     *
872
     * @since 1.0.0
873
     * @since 1.6.20 Hook added to filter value.
874
     * @package GeoDirectory
875
     * @global object $wpdb WordPress Database object.
876
     * @global string $plugin_prefix Geodirectory plugin table prefix.
877
     * @param int $post_id The post ID.
878
     * @param string $meta_key The meta key to retrieve.
879
     * @param bool $single Optional. Whether to return a single value. Default false.
880
     * @todo single variable not yet implemented.
881
     * @return bool|mixed|null|string Will be an array if $single is false. Will be value of meta data field if $single is true.
882
     */
883
    function geodir_get_post_meta($post_id, $meta_key, $single = false) {
884 3
        if (!$post_id) {
885
            return false;
886
        }
887 3
        global $wpdb, $plugin_prefix;
888
889 3
        $all_postypes = geodir_get_posttypes();
890
891 3
        $post_type = get_post_type($post_id);
892
893 3
        if (!in_array($post_type, $all_postypes))
894 3
            return false;
895
896 3
        $table = $plugin_prefix . $post_type . '_detail';
897
898 3
        if ($wpdb->get_var("SHOW COLUMNS FROM " . $table . " WHERE field = '" . $meta_key . "'") != '') {
899 3
            $meta_value = $wpdb->get_var($wpdb->prepare("SELECT " . $meta_key . " from " . $table . " where post_id = %d", array($post_id)));
900
            
901 3
            if ($meta_value && $meta_value !== '') {
902
                $meta_value = maybe_serialize($meta_value);
903
            }
904 3
        } else {
905
            $meta_value = false;
906
        }
907
        
908
        /**
909
         * Filter the listing custom meta.
910
         *
911
         * @since 1.6.20
912
         * 
913
         * @param bool|mixed|null|string $meta_value Will be an array if $single is false. Will be value of meta data field if $single is true.
914
         * @param int $post_id The post ID.
915
         * @param string $meta_key The meta key to retrieve.
916
         * @param bool $single Optional. Whether to return a single value. Default false.
917
         */
918 3
        return apply_filters( 'geodir_get_post_meta', $meta_value, $post_id, $meta_key, $single );
919
    }
920
}
921
922
923
if (!function_exists('geodir_save_post_images')) {
924
    /**
925
     * Save post attachments.
926
     *
927
     * @since 1.0.0
928
     * @package GeoDirectory
929
     * @global object $wpdb WordPress Database object.
930
     * @global string $plugin_prefix Geodirectory plugin table prefix.
931
     * @global object $current_user Current user object.
932
     * @param int $post_id The post ID.
933
     * @param array $post_image Post image urls as an array.
934
     * @param bool $dummy Optional. Is this a dummy listing? Default false.
935
     */
936
    function geodir_save_post_images($post_id = 0, $post_image = array(), $dummy = false)
937
    {
938
939
940
        global $wpdb, $plugin_prefix, $current_user;
941
942
        $post_type = get_post_type($post_id);
943
944
        $table = $plugin_prefix . $post_type . '_detail';
945
946
        $post_images = geodir_get_images($post_id);
947
948
        $wpdb->query(
949
            $wpdb->prepare(
950
                "UPDATE " . $table . " SET featured_image = '' where post_id =%d",
951
                array($post_id)
952
            )
953
        );
954
955
        $invalid_files = $post_images;
956
        $valid_file_ids = array();
957
        $valid_files_condition = '';
958
        $geodir_uploaddir = '';
959
960
        $remove_files = array();
961
962
        if (!empty($post_image)) {
963
964
            $uploads = wp_upload_dir();
965
            $uploads_dir = $uploads['path'];
966
967
            $geodir_uploadpath = $uploads['path'];
968
            $geodir_uploadurl = $uploads['url'];
969
            $sub_dir = isset($uploads['subdir']) ? $uploads['subdir'] : '';
970
971
            $invalid_files = array();
972
            $postcurr_images = array();
973
974
            for ($m = 0; $m < count($post_image); $m++) {
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...
975
                $menu_order = $m + 1;
976
977
                $file_path = '';
978
                /* --------- start ------- */
979
980
                $split_img_path = explode(str_replace(array('http://','https://'),'',$uploads['baseurl']), str_replace(array('http://','https://'),'',$post_image[$m]));
981
982
                $split_img_file_path = isset($split_img_path[1]) ? $split_img_path[1] : '';
983
984
985
                if (!$find_image = $wpdb->get_var($wpdb->prepare("SELECT ID FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE file=%s AND post_id = %d", array($split_img_file_path, $post_id)))) {
986
987
                    /* --------- end ------- */
988
                    $curr_img_url = $post_image[$m];
989
990
                    $image_name_arr = explode('/', $curr_img_url);
991
992
                    $count_image_name_arr = count($image_name_arr) - 2;
993
994
                    $count_image_name_arr = ($count_image_name_arr >= 0) ? $count_image_name_arr : 0;
995
996
                    $curr_img_dir = $image_name_arr[$count_image_name_arr];
0 ignored issues
show
Unused Code introduced by
$curr_img_dir 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...
997
998
                    $filename = end($image_name_arr);
999
                    if (strpos($filename, '?') !== false) {
1000
                        list($filename) = explode('?', $filename);
1001
                    }
1002
1003
                    $curr_img_dir = str_replace($uploads['baseurl'], "", $curr_img_url);
1004
                    $curr_img_dir = str_replace($filename, "", $curr_img_dir);
1005
1006
                    $img_name_arr = explode('.', $filename);
1007
1008
                    $file_title = isset($img_name_arr[0]) ? $img_name_arr[0] : $filename;
1009
                    if (!empty($img_name_arr) && count($img_name_arr) > 2) {
1010
                        $new_img_name_arr = $img_name_arr;
1011
                        if (isset($new_img_name_arr[count($img_name_arr) - 1])) {
1012
                            unset($new_img_name_arr[count($img_name_arr) - 1]);
1013
                            $file_title = implode('.', $new_img_name_arr);
1014
                        }
1015
                    }
1016
                    $file_title = sanitize_file_name($file_title);
1017
                    $file_name = sanitize_file_name($filename);
1018
1019
                    $arr_file_type = wp_check_filetype($filename);
1020
1021
                    $uploaded_file_type = $arr_file_type['type'];
1022
1023
                    // Set an array containing a list of acceptable formats
1024
                    $allowed_file_types = array('image/jpg', 'image/jpeg', 'image/gif', 'image/png');
1025
1026
                    // If the uploaded file is the right format
1027
                    if (in_array($uploaded_file_type, $allowed_file_types)) {
1028
                        if (!function_exists('wp_handle_upload')) {
1029
                            require_once(ABSPATH . 'wp-admin/includes/file.php');
1030
                        }
1031
1032
                        if (!is_dir($geodir_uploadpath)) {
1033
                            mkdir($geodir_uploadpath);
1034
                        }
1035
1036
                        $external_img = false;
1037
                        if (strpos( str_replace( array('http://','https://'),'',$curr_img_url ), str_replace(array('http://','https://'),'',$uploads['baseurl'] ) ) !== false) {
1038
                        } else {
1039
                            $external_img = true;
1040
                        }
1041
1042
                        if ($dummy || $external_img) {
1043
                            $uploaded_file = array();
0 ignored issues
show
Unused Code introduced by
$uploaded_file 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...
1044
                            $uploaded = (array)fetch_remote_file($curr_img_url);
1045
1046
                            if (isset($uploaded['error']) && empty($uploaded['error'])) {
1047
                                $new_name = basename($uploaded['file']);
1048
                                $uploaded_file = $uploaded;
1049
                            }else{
1050
                                print_r($uploaded);exit;
1051
                            }
1052
                            $external_img = false;
0 ignored issues
show
Unused Code introduced by
$external_img 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...
1053
                        } else {
1054
                            $new_name = $post_id . '_' . $file_name;
1055
1056 View Code Duplication
                            if ($curr_img_dir == $sub_dir) {
1057
                                $img_path = $geodir_uploadpath . '/' . $filename;
1058
                                $img_url = $geodir_uploadurl . '/' . $filename;
0 ignored issues
show
Unused Code introduced by
$img_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...
1059
                            } else {
1060
                                $img_path = $uploads_dir . '/temp_' . $current_user->data->ID . '/' . $filename;
1061
                                $img_url = $uploads['url'] . '/temp_' . $current_user->data->ID . '/' . $filename;
0 ignored issues
show
Unused Code introduced by
$img_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...
1062
                            }
1063
1064
                            $uploaded_file = '';
1065
1066
                            if (file_exists($img_path)) {
1067
                                $uploaded_file = copy($img_path, $geodir_uploadpath . '/' . $new_name);
1068
                                $file_path = '';
1069
                            } else if (file_exists($uploads['basedir'] . $curr_img_dir . $filename)) {
1070
                                $uploaded_file = true;
1071
                                $file_path = $curr_img_dir . '/' . $filename;
1072
                            }
1073
1074
                            if ($curr_img_dir != $geodir_uploaddir && file_exists($img_path))
1075
                                unlink($img_path);
1076
                        }
1077
1078
                        if (!empty($uploaded_file)) {
1079
                            if (!isset($file_path) || !$file_path) {
1080
                                $file_path = $sub_dir . '/' . $new_name;
1081
                            }
1082
1083
                            $postcurr_images[] = str_replace(array('http://','https://'),'',$uploads['baseurl'] . $file_path);
1084
1085 View Code Duplication
                            if ($menu_order == 1) {
1086
1087
                                $wpdb->query($wpdb->prepare("UPDATE " . $table . " SET featured_image = %s where post_id =%d", array($file_path, $post_id)));
1088
1089
                            }
1090
1091
                            // Set up options array to add this file as an attachment
1092
                            $attachment = array();
1093
                            $attachment['post_id'] = $post_id;
1094
                            $attachment['title'] = $file_title;
1095
                            $attachment['content'] = '';
1096
                            $attachment['file'] = $file_path;
1097
                            $attachment['mime_type'] = $uploaded_file_type;
1098
                            $attachment['menu_order'] = $menu_order;
1099
                            $attachment['is_featured'] = 0;
1100
1101
                            $attachment_set = '';
1102
1103
                            foreach ($attachment as $key => $val) {
1104
                                if ($val != '')
1105
                                    $attachment_set .= $key . " = '" . $val . "', ";
1106
                            }
1107
1108
                            $attachment_set = trim($attachment_set, ", ");
1109
1110
                            $wpdb->query("INSERT INTO " . GEODIR_ATTACHMENT_TABLE . " SET " . $attachment_set);
1111
1112
                            $valid_file_ids[] = $wpdb->insert_id;
1113
                        }
1114
1115
                    }
1116
1117
1118
                } else {
1119
                    $valid_file_ids[] = $find_image;
1120
1121
                    $postcurr_images[] = str_replace(array('http://','https://'),'',$post_image[$m]);
1122
1123
                    $wpdb->query(
1124
                        $wpdb->prepare(
1125
                            "UPDATE " . GEODIR_ATTACHMENT_TABLE . " SET menu_order = %d where file =%s AND post_id =%d",
1126
                            array($menu_order, $split_img_path[1], $post_id)
1127
                        )
1128
                    );
1129
1130 View Code Duplication
                    if ($menu_order == 1)
1131
                        $wpdb->query($wpdb->prepare("UPDATE " . $table . " SET featured_image = %s where post_id =%d", array($split_img_path[1], $post_id)));
1132
1133
                }
1134
1135
1136
            }
1137
1138
            if (!empty($valid_file_ids)) {
1139
1140
                $remove_files = $valid_file_ids;
1141
1142
                $remove_files_length = count($remove_files);
1143
                $remove_files_format = array_fill(0, $remove_files_length, '%d');
1144
                $format = implode(',', $remove_files_format);
1145
                $valid_files_condition = " ID NOT IN ($format) AND ";
1146
1147
            }
1148
1149
            //Get and remove all old images of post from database to set by new order
1150
1151
            if (!empty($post_images)) {
1152
1153
                foreach ($post_images as $img) {
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...
1154
1155
                    if (!in_array(str_replace(array('http://','https://'),'',$img->src), $postcurr_images)) {
1156
1157
                        $invalid_files[] = (object)array('src' => $img->src);
1158
1159
                    }
1160
1161
                }
1162
1163
            }
1164
1165
            $invalid_files = (object)$invalid_files;
1166
        }
1167
1168
        $remove_files[] = $post_id;
1169
1170
        $wpdb->query($wpdb->prepare("DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE " . $valid_files_condition . " post_id = %d", $remove_files));
1171
1172
        if (!empty($invalid_files))
1173
            geodir_remove_attachments($invalid_files);
1174
    }
1175
1176
}
1177
1178
/**
1179
 * Remove current user's temporary images.
1180
 *
1181
 * @since 1.0.0
1182
 * @package GeoDirectory
1183
 * @global object $current_user Current user object.
1184
 **/
1185
function geodir_remove_temp_images()
1186
{
1187
1188 3
    global $current_user;
1189
1190 3
    $uploads = wp_upload_dir();
1191 3
    $uploads_dir = $uploads['path'];
1192
1193
    /*	if(is_dir($uploads_dir.'/temp_'.$current_user->data->ID)){
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...
1194
1195
			$dirPath = $uploads_dir.'/temp_'.$current_user->data->ID;
1196
			if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
1197
				$dirPath .= '/';
1198
			}
1199
			$files = glob($dirPath . '*', GLOB_MARK);
1200
			foreach ($files as $file) {
1201
				if (is_dir($file)) {
1202
					self::deleteDir($file);
1203
				} else {
1204
					unlink($file);
1205
				}
1206
			}
1207
			rmdir($dirPath);
1208
	}	*/
1209
1210 3
    $dirname = $uploads_dir . '/temp_' . $current_user->ID;
1211 3
    geodir_delete_directory($dirname);
1212 3
}
1213
1214
1215
/**
1216
 * Delete a directory.
1217
 *
1218
 * @since 1.0.0
1219
 * @package GeoDirectory
1220
 * @param string $dirname Directory name that needs to be deleted.
1221
 * @return bool
1222
 */
1223
function geodir_delete_directory($dirname)
1224
{
1225 3
    $dir_handle = '';
1226 3
    if (is_dir($dirname))
1227 3
        $dir_handle = opendir($dirname);
1228 3
    if (!$dir_handle)
1229 3
        return false;
1230
    while ($file = readdir($dir_handle)) {
1231
        if ($file != "." && $file != "..") {
1232
            if (!is_dir($dirname . "/" . $file))
1233
                unlink($dirname . "/" . $file);
1234
            else
1235
                geodir_delete_directory($dirname . '/' . $file);
1236
        }
1237
    }
1238
    closedir($dir_handle);
1239
    rmdir($dirname);
1240
    return true;
1241
1242
}
1243
1244
1245
if (!function_exists('geodir_remove_attachments')) {
1246
    /**
1247
     * Remove post attachments.
1248
     *
1249
     * @since 1.0.0
1250
     * @package GeoDirectory
1251
     * @param array $postcurr_images Array of image objects.
1252
     */
1253
    function geodir_remove_attachments($postcurr_images = array())
1254
    {
1255
        // Unlink all past images of post
1256
        if (!empty($postcurr_images)) {
1257
1258
            $uploads = wp_upload_dir();
1259
            $uploads_dir = $uploads['path'];
1260
1261
            foreach ($postcurr_images as $postimg) {
1262
                $image_name_arr = explode('/', $postimg->src);
1263
                $filename = end($image_name_arr);
1264
                if (file_exists($uploads_dir . '/' . $filename))
1265
                    unlink($uploads_dir . '/' . $filename);
1266
            }
1267
1268
        } // endif
1269
        // Unlink all past images of post end
1270
    }
1271
}
1272
1273
if (!function_exists('geodir_get_featured_image')) {
1274
    /**
1275
     * Gets the post featured image.
1276
     *
1277
     * @since 1.0.0
1278
     * @package GeoDirectory
1279
     * @global object $wpdb WordPress Database object.
1280
     * @global object $post The current post object.
1281
     * @global string $plugin_prefix Geodirectory plugin table prefix.
1282
     * @param int|string $post_id The post ID.
1283
     * @param string $size Optional. Thumbnail size. Default: thumbnail.
1284
     * @param bool $no_image Optional. Do you want to return the default image when no image is available? Default: false.
1285
     * @param bool|string $file Optional. The file path from which you want to get the image details. Default: false.
1286
     * @return bool|object Image details as an object.
1287
     */
1288
    function geodir_get_featured_image($post_id = '', $size = '', $no_image = false, $file = false)
1289
    {
1290
1291
        /*$img_arr['src'] = get_the_post_thumbnail_url( $post_id,  'medium');//medium/thumbnail
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
1292
        $img_arr['path'] = '';
1293
        $img_arr['width'] = '';
1294
        $img_arr['height'] = '';
1295
        $img_arr['title'] = '';
1296
        return (object)$img_arr;*/
1297
        global $wpdb, $plugin_prefix, $post;
1298
1299
        if (isset($post->ID) && isset($post->post_type) && $post->ID == $post_id) {
1300
            $post_type = $post->post_type;
1301
        } else {
1302
            $post_type = get_post_type($post_id);
1303
        }
1304
1305
        if (!in_array($post_type, geodir_get_posttypes())) {
1306
            return false;// if not a GD CPT return;
1307
        }
1308
1309
1310
        $list_img_size = get_option('geodir_listing_img_size','default');
1311
1312
        if( $size=='list-thumb' && $list_img_size != 'default' ){
1313
            $fimg = get_the_post_thumbnail_url($post_id,$list_img_size);
1314
            if($fimg){
1315
                $uploads = wp_upload_dir(); 
1316
                $uploads_baseurl = $uploads['baseurl'];
1317
                $file = str_replace($uploads_baseurl,'',$fimg);
1318
            }
1319
        }
1320
1321
        $table = $plugin_prefix . $post_type . '_detail';
1322
1323
        if (!$file) {
1324
            if (isset($post->featured_image)) {
1325
                $file = $post->featured_image;
1326
            } else {
1327
                $file = $wpdb->get_var($wpdb->prepare("SELECT featured_image FROM " . $table . " WHERE post_id = %d", array($post_id)));
1328
            }
1329
        }
1330
1331
        if ($file != NULL && $file != '' && (($uploads = wp_upload_dir()) && false === $uploads['error'])) {
1332
            $img_arr = array();
1333
1334
            $file_info = pathinfo($file);
1335
            $sub_dir = '';
1336 View Code Duplication
            if ($file_info['dirname'] != '.' && $file_info['dirname'] != '..') {
1337
                $sub_dir = stripslashes_deep($file_info['dirname']);
1338
            }
1339
1340
            $uploads = wp_upload_dir(trim($sub_dir, '/')); // Array of key => value pairs
1341
            $uploads_baseurl = $uploads['baseurl'];
1342
            $uploads_path = $uploads['path'];
1343
1344
            $file_name = $file_info['basename'];
1345
1346
            $uploads_url = $uploads_baseurl . $sub_dir;
1347
            /*
1348
             * Allows the filter of image src for such things as CDN change.
1349
             *
1350
             * @since 1.5.7
1351
             * @param string $url The full image url.
1352
             * @param string $file_name The image file name and directory path.
1353
             * @param string $uploads_url The server upload directory url.
1354
             * @param string $uploads_baseurl The uploads dir base url.
1355
             */
1356
            $img_arr['src'] = apply_filters('geodir_get_featured_image_src',$uploads_url . '/' . $file_name,$file_name,$uploads_url,$uploads_baseurl);
1357
            $img_arr['path'] = $uploads_path . '/' . $file_name;
1358
            $width = 0;
1359
            $height = 0;
1360 View Code Duplication
            if (is_file($img_arr['path']) && file_exists($img_arr['path'])) {
1361
                $imagesize = getimagesize($img_arr['path']);
1362
                $width = !empty($imagesize) && isset($imagesize[0]) ? $imagesize[0] : '';
1363
                $height = !empty($imagesize) && isset($imagesize[1]) ? $imagesize[1] : '';
1364
            }
1365
            $img_arr['width'] = $width;
1366
            $img_arr['height'] = $height;
1367
            $img_arr['title'] = $post->post_title;
1368
        } elseif ($post_images = geodir_get_images($post_id, $size, $no_image, 1)) {
0 ignored issues
show
Documentation introduced by
1 is of type integer, but the function expects a boolean.

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...
1369
            foreach ($post_images as $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...
1370
                return $image;
1371
            }
1372
        } else if ($no_image) {
1373
            $img_arr = array();
1374
1375
            $default_img = '';
1376
            if (isset($post->default_category) && $post->default_category) {
1377
                $default_cat = $post->default_category;
1378
            } else {
1379
                $default_cat = geodir_get_post_meta($post_id, 'default_category', true);
1380
            }
1381
1382 View Code Duplication
            if ($default_catimg = geodir_get_default_catimage($default_cat, $post_type))
1383
                $default_img = $default_catimg['src'];
1384
            elseif ($no_image) {
1385
                $default_img = get_option('geodir_listing_no_img');
1386
            }
1387
1388
            if (!empty($default_img)) {
1389
                $uploads = wp_upload_dir(); // Array of key => value pairs
1390
                $uploads_baseurl = $uploads['baseurl'];
0 ignored issues
show
Unused Code introduced by
$uploads_baseurl 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...
1391
                $uploads_path = $uploads['path'];
1392
1393
                $img_arr = array();
1394
1395
                $file_info = pathinfo($default_img);
1396
1397
                $file_name = $file_info['basename'];
1398
1399
                $img_arr['src'] = $default_img;
1400
                $img_arr['path'] = $uploads_path . '/' . $file_name;
1401
1402
                $width = 0;
1403
                $height = 0;
1404 View Code Duplication
                if (is_file($img_arr['path']) && file_exists($img_arr['path'])) {
1405
                    $imagesize = getimagesize($img_arr['path']);
1406
                    $width = !empty($imagesize) && isset($imagesize[0]) ? $imagesize[0] : '';
1407
                    $height = !empty($imagesize) && isset($imagesize[1]) ? $imagesize[1] : '';
1408
                }
1409
                $img_arr['width'] = $width;
1410
                $img_arr['height'] = $height;
1411
1412
                $img_arr['title'] = $post->post_title; // add the title to the array
1413
            }
1414
        }
1415
1416
        if (!empty($img_arr))
1417
            return (object)$img_arr;//return (object)array( 'src' => $file_url, 'path' => $file_path );
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
1418
        else
1419
            return false;
1420
    }
1421
}
1422
1423
if (!function_exists('geodir_show_featured_image')) {
1424
    /**
1425
     * Gets the post featured image.
1426
     *
1427
     * @since 1.0.0
1428
     * @package GeoDirectory
1429
     * @param int|string $post_id The post ID.
1430
     * @param string $size Optional. Thumbnail size. Default: thumbnail.
1431
     * @param bool $no_image Optional. Do you want to return the default image when no image is available? Default: false.
1432
     * @param bool $echo Optional. Do you want to print it instead of returning it? Default: true.
1433
     * @param bool|string $fimage Optional. The file path from which you want to get the image details. Default: false.
1434
     * @return bool|string Returns image html.
1435
     */
1436
    function geodir_show_featured_image($post_id = '', $size = 'thumbnail', $no_image = false, $echo = true, $fimage = false)
1437
    {
1438
        $image = geodir_get_featured_image($post_id, $size, $no_image, $fimage);
1439
1440
        $html = geodir_show_image($image, $size, $no_image, false);
0 ignored issues
show
Bug introduced by
It seems like $image defined by geodir_get_featured_imag...ze, $no_image, $fimage) on line 1438 can also be of type boolean; however, geodir_show_image() does only seem to accept array|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...
1441
1442 View Code Duplication
        if (!empty($html) && $echo) {
1443
            echo $html;
1444
        } elseif (!empty($html)) {
1445
            return $html;
1446
        } else
1447
            return false;
1448
    }
1449
}
1450
1451
if (!function_exists('geodir_get_images')) {
1452
    /**
1453
     * Gets the post images.
1454
     *
1455
     * @since 1.0.0
1456
     * @package GeoDirectory
1457
     * @global object $wpdb WordPress Database object.
1458
     * @param int $post_id The post ID.
1459
     * @param string $img_size Optional. Thumbnail size.
1460
     * @param bool $no_images Optional. Do you want to return the default image when no image is available? Default: false.
1461
     * @param bool $add_featured Optional. Do you want to include featured images too? Default: true.
1462
     * @param int|string $limit Optional. Number of images.
1463
     * @return array|bool Returns images as an array. Each item is an object.
1464
     */
1465
    function geodir_get_images($post_id = 0, $img_size = '', $no_images = false, $add_featured = true, $limit = '')
0 ignored issues
show
Unused Code introduced by
The parameter $img_size 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...
1466
    {
1467
        global $wpdb;
1468
        if ($limit) {
1469
            $limit_q = " LIMIT $limit ";
1470
        } else {
1471
            $limit_q = '';
1472
        }
1473
        $not_featured = '';
1474
        $sub_dir = '';
1475
        if (!$add_featured)
1476
            $not_featured = " AND is_featured = 0 ";
1477
1478
        $arrImages = $wpdb->get_results(
1479
            $wpdb->prepare(
1480
                "SELECT * FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE mime_type like %s AND post_id = %d" . $not_featured . " ORDER BY menu_order ASC, ID DESC $limit_q ",
1481
                array('%image%', $post_id)
1482
            )
1483
        );
1484
1485
        $counter = 0;
1486
        $return_arr = array();
1487
1488
        if (!empty($arrImages)) {
1489
            foreach ($arrImages as $attechment) {
1490
1491
                $img_arr = array();
1492
                $img_arr['id'] = $attechment->ID;
1493
                $img_arr['user_id'] = isset($attechment->user_id) ? $attechment->user_id : 0;
1494
1495
                $file_info = pathinfo($attechment->file);
1496
1497 View Code Duplication
                if ($file_info['dirname'] != '.' && $file_info['dirname'] != '..')
1498
                    $sub_dir = stripslashes_deep($file_info['dirname']);
1499
1500
                $uploads = wp_upload_dir(trim($sub_dir, '/')); // Array of key => value pairs
1501
                $uploads_baseurl = $uploads['baseurl'];
1502
                $uploads_path = $uploads['path'];
1503
1504
                $file_name = $file_info['basename'];
1505
1506
                $uploads_url = $uploads_baseurl . $sub_dir;
1507
                /*
1508
                * Allows the filter of image src for such things as CDN change.
1509
                *
1510
                * @since 1.5.7
1511
                * @param string $url The full image url.
1512
                * @param string $file_name The image file name and directory path.
1513
                * @param string $uploads_url The server upload directory url.
1514
                * @param string $uploads_baseurl The uploads dir base url.
1515
                */
1516
                $img_arr['src'] = apply_filters('geodir_get_images_src',$uploads_url . '/' . $file_name,$file_name,$uploads_url,$uploads_baseurl);
1517
                $img_arr['path'] = $uploads_path . '/' . $file_name;
1518
                $width = 0;
1519
                $height = 0;
1520 View Code Duplication
                if (is_file($img_arr['path']) && file_exists($img_arr['path'])) {
1521
                    $imagesize = getimagesize($img_arr['path']);
1522
                    $width = !empty($imagesize) && isset($imagesize[0]) ? $imagesize[0] : '';
1523
                    $height = !empty($imagesize) && isset($imagesize[1]) ? $imagesize[1] : '';
1524
                }
1525
                $img_arr['width'] = $width;
1526
                $img_arr['height'] = $height;
1527
1528
                $img_arr['file'] = $file_name; // add the title to the array
1529
                $img_arr['title'] = $attechment->title; // add the title to the array
1530
                $img_arr['caption'] = isset($attechment->caption) ? $attechment->caption : ''; // add the caption to the array
1531
                $img_arr['content'] = $attechment->content; // add the description to the array
1532
                $img_arr['is_approved'] = isset($attechment->is_approved) ? $attechment->is_approved : ''; // used for user image moderation. For backward compatibility Default value is 1.
1533
1534
                $return_arr[] = (object)$img_arr;
1535
1536
                $counter++;
1537
            }
1538
            //return (object)$return_arr;
1539
            /**
1540
             * Filter the images array so things can be changed.
1541
             *
1542
             * @since 1.6.20
1543
             * @param array $return_arr The array of image objects.
1544
             */
1545
            return apply_filters('geodir_get_images_arr',$return_arr);
1546
        } else if ($no_images) {
1547
            $default_img = '';
1548
            $default_cat = geodir_get_post_meta($post_id, 'default_category', true);
1549
            $post_type = get_post_type($post_id);
1550 View Code Duplication
            if ($default_catimg = geodir_get_default_catimage($default_cat, $post_type))
1551
                $default_img = $default_catimg['src'];
1552
            elseif ($no_images) {
1553
                $default_img = get_option('geodir_listing_no_img');
1554
            }
1555
1556
            if (!empty($default_img)) {
1557
                $uploads = wp_upload_dir(); // Array of key => value pairs
1558
                
1559
                $image_path = $default_img;
1560 View Code Duplication
                if (!path_is_absolute($image_path)) {
1561
                    $image_path = str_replace($uploads['baseurl'], $uploads['basedir'], $image_path);
1562
                }
1563
1564
                $file_info = pathinfo($default_img);
1565
                $file_name = $file_info['basename'];
1566
1567
                $width = '';
1568
                $height = '';
1569 View Code Duplication
                if (is_file($image_path) && file_exists($image_path)) {
1570
                    $imagesize = getimagesize($image_path);
1571
                    $width = !empty($imagesize) && isset($imagesize[0]) ? $imagesize[0] : '';
1572
                    $height = !empty($imagesize) && isset($imagesize[1]) ? $imagesize[1] : '';
1573
                }
1574
                
1575
                $img_arr = array();
1576
                $img_arr['src'] = $default_img;
1577
                $img_arr['path'] = $image_path;
1578
                $img_arr['width'] = $width;
1579
                $img_arr['height'] = $height;
1580
                $img_arr['file'] = $file_name; // add the title to the array
1581
                $img_arr['title'] = $file_info['filename']; // add the title to the array
1582
                $img_arr['content'] = $file_info['filename']; // add the description to the array
1583
1584
                $return_arr[] = (object)$img_arr;
1585
1586
                /**
1587
                 * Filter the images array so things can be changed.
1588
                 * 
1589
                 * @since 1.6.20
1590
                 * @param array $return_arr The array of image objects.
1591
                 */
1592
                return apply_filters('geodir_get_images_arr',$return_arr);
1593
            } else
1594
                return false;
1595
        }
1596
    }
1597
}
1598
1599
if (!function_exists('geodir_show_image')) {
1600
    /**
1601
     * Show image using image details.
1602
     *
1603
     * @since 1.0.0
1604
     * @package GeoDirectory
1605
     * @param array|object $request Image info either as an array or object.
1606
     * @param string $size Optional. Thumbnail size. Default: thumbnail.
1607
     * @param bool $no_image Optional. Do you want to return the default image when no image is available? Default: false.
1608
     * @param bool $echo Optional. Do you want to print it instead of returning it? Default: true.
1609
     * @return bool|string Returns image html.
1610
     */
1611
    function geodir_show_image($request = array(), $size = 'thumbnail', $no_image = false, $echo = true)
0 ignored issues
show
Unused Code introduced by
The parameter $no_image 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...
1612
    {
1613
        $image = new stdClass();
1614
1615
        $html = '';
1616
        if (!empty($request)) {
1617
            if (!is_object($request)){
1618
                $request = (object)$request;
1619
            }
1620
1621
            if (isset($request->src) && !isset($request->path)) {
1622
                $request->path = $request->src;
1623
            }
1624
1625
            /*
1626
             * getimagesize() works faster from path than url so we try and get path if we can.
1627
             */
1628
            $upload_dir = wp_upload_dir();
1629
            $img_no_http = str_replace(array("http://", "https://"), "", $request->path);
1630
            $upload_no_http = str_replace(array("http://", "https://"), "", $upload_dir['baseurl']);
1631
            if (strpos($img_no_http, $upload_no_http) !== false) {
1632
                $request->path = str_replace( $img_no_http,$upload_dir['basedir'], $request->path);
1633
            }
1634
            
1635
            $width = 0;
1636
            $height = 0;
1637 View Code Duplication
            if (is_file($request->path) && file_exists($request->path)) {
1638
                $imagesize = getimagesize($request->path);
1639
                $width = !empty($imagesize) && isset($imagesize[0]) ? $imagesize[0] : '';
1640
                $height = !empty($imagesize) && isset($imagesize[1]) ? $imagesize[1] : '';
1641
            }
1642
1643
1644
            $image->src = $request->src;
1645
            $image->width = $width;
1646
            $image->height = $height;
1647
            $image->title = isset($request->title) ? $request->title : '';
1648
1649
            $max_size = (object)geodir_get_imagesize($size);
1650
1651
            if (!is_wp_error($max_size)) {
1652
                if ($image->width) {
1653
                    if ($image->height >= $image->width) {
1654
                        $width_per = round(((($image->width * ($max_size->h / $image->height)) / $max_size->w) * 100), 2);
0 ignored issues
show
Unused Code introduced by
$width_per 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...
1655
                    } else if ($image->width < ($max_size->h)) {
1656
                        $width_per = round((($image->width / $max_size->w) * 100), 2);
0 ignored issues
show
Unused Code introduced by
$width_per 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...
1657
                    } else
1658
                        $width_per = 100;
0 ignored issues
show
Unused Code introduced by
$width_per 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...
1659
                }
1660
1661
                if (is_admin() && !isset($_REQUEST['geodir_ajax'])){
1662
                    $html = '<div class="geodir_thumbnail"><img style="max-height:' . $max_size->h . 'px;" alt="place image" src="' . $image->src . '"  /></div>';
1663
                } else {
1664
                    if($size=='widget-thumb' || !get_option('geodir_lazy_load',1)){
1665
                        $html = '<div class="geodir_thumbnail" style="background-image:url(\'' . $image->src . '\');" title="'.$image->title.'" aria-label="'.$image->title.'" ></div>';
1666
                    }else{
1667
                        $html = '<div data-src="'.str_replace(' ','%20',$image->src).'" class="geodir_thumbnail geodir_lazy_load_thumbnail" title="'.$image->title.'" aria-label="'.$image->title.'"></div>';
1668
                    }
1669
1670
                }
1671
            }
1672
        }
1673
1674 View Code Duplication
        if (!empty($html) && $echo) {
1675
            echo $html;
1676
        } elseif (!empty($html)) {
1677
            return $html;
1678
        } else
1679
            return false;
1680
    }
1681
}
1682
1683
if (!function_exists('geodir_set_post_terms')) {
1684
    /**
1685
     * Set post Categories.
1686
     *
1687
     * @since 1.0.0
1688
     * @package GeoDirectory
1689
     * @global object $wpdb WordPress Database object.
1690
     * @global string $plugin_prefix Geodirectory plugin table prefix.
1691
     * @param int $post_id The post ID.
1692
     * @param array $terms An array of term objects.
1693
     * @param array $tt_ids An array of term taxonomy IDs.
1694
     * @param string $taxonomy Taxonomy slug.
1695
     */
1696
    function geodir_set_post_terms($post_id, $terms, $tt_ids, $taxonomy)
1697
    {
1698 3
        global $wpdb, $plugin_prefix;
1699
1700 3
        $post_type = get_post_type($post_id);
1701
1702 3
        $table = $plugin_prefix . $post_type . '_detail';
1703
1704 3
        if (in_array($post_type, geodir_get_posttypes()) && !wp_is_post_revision($post_id)) {
1705
1706 3
            if ($taxonomy == $post_type . '_tags') {
1707 3
                if (isset($_POST['action']) && $_POST['action'] == 'inline-save') {
1708
                    geodir_save_post_meta($post_id, 'post_tags', $terms);
0 ignored issues
show
Documentation introduced by
$terms is of type array, 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...
1709
                }
1710 3
            } elseif ($taxonomy == $post_type . 'category') {
1711
                $srcharr = array('"', '\\');
1712
                $replarr = array("&quot;", '');
1713
1714
                $post_obj = get_post($post_id);
1715
1716
                $cat_ids = array('0');
1717
                if (is_array($tt_ids))
1718
                    $cat_ids = $tt_ids;
1719
1720
1721
                if (!empty($cat_ids)) {
1722
                    $cat_ids_array = $cat_ids;
1723
                    $cat_ids_length = count($cat_ids_array);
1724
                    $cat_ids_format = array_fill(0, $cat_ids_length, '%d');
1725
                    $format = implode(',', $cat_ids_format);
1726
1727
                    $cat_ids_array_del = $cat_ids_array;
1728
                    $cat_ids_array_del[] = $post_id;
1729
1730
                    $wpdb->get_var(
1731
                        $wpdb->prepare(
1732
                            "DELETE from " . GEODIR_ICON_TABLE . " WHERE cat_id NOT IN ($format) AND post_id = %d ",
1733
                            $cat_ids_array_del
1734
                        )
1735
                    );
1736
1737
1738
                    $post_term = $wpdb->get_col(
1739
                        $wpdb->prepare(
1740
                            "SELECT term_id FROM " . $wpdb->term_taxonomy . " WHERE term_taxonomy_id IN($format) GROUP BY term_id",
1741
                            $cat_ids_array
1742
                        )
1743
                    );
1744
1745
                }
1746
1747
                $post_marker_json = '';
1748
1749
                if (!empty($post_term)):
1750
1751
                    foreach ($post_term as $cat_id):
1752
1753
                        $term_icon_url = geodir_get_tax_meta($cat_id, 'ct_cat_icon', false, $post_type);
1754
                        $term_icon = isset($term_icon_url['src']) ? $term_icon_url['src'] : '';
1755
1756
                        $post_title = $post_obj->title;
1757
                        $title = str_replace($srcharr, $replarr, $post_title);
0 ignored issues
show
Unused Code introduced by
$title 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...
1758
1759
                        $lat = geodir_get_post_meta($post_id, 'post_latitude', true);
1760
                        $lng = geodir_get_post_meta($post_id, 'post_longitude', true);
1761
1762
                        $timing = ' - ' . date('D M j, Y', strtotime(geodir_get_post_meta($post_id, 'st_date', true)));
1763
                        $timing .= ' - ' . geodir_get_post_meta($post_id, 'st_time', true);
1764
1765
                        $json = '{';
1766
                        $json .= '"id":"' . $post_id . '",';
1767
                        $json .= '"lat_pos": "' . $lat . '",';
1768
                        $json .= '"long_pos": "' . $lng . '",';
1769
                        $json .= '"marker_id":"' . $post_id . '_' . $cat_id . '",';
1770
                        $json .= '"icon":"' . $term_icon . '",';
1771
                        $json .= '"group":"catgroup' . $cat_id . '"';
1772
                        $json .= '}';
1773
1774
1775
                        if ($cat_id == geodir_get_post_meta($post_id, 'default_category', true))
1776
                            $post_marker_json = $json;
1777
1778
1779
                        if ($wpdb->get_var($wpdb->prepare("SELECT post_id from " . GEODIR_ICON_TABLE . " WHERE post_id = %d AND cat_id = %d", array($post_id, $cat_id)))) {
1780
1781
                            $json_query = $wpdb->prepare("UPDATE " . GEODIR_ICON_TABLE . " SET
1782
										post_title = %s,
1783
										json = %s
1784
										WHERE post_id = %d AND cat_id = %d ",
1785
                                array($post_title, $json, $post_id, $cat_id));
1786
1787
                        } else {
1788
1789
                            $json_query = $wpdb->prepare("INSERT INTO " . GEODIR_ICON_TABLE . " SET
1790
										post_id = %d,
1791
										post_title = %s,
1792
										cat_id = %d,
1793
										json = %s",
1794
                                array($post_id, $post_title, $cat_id, $json));
1795
1796
                        }
1797
1798
                        $wpdb->query($json_query);
1799
1800
                    endforeach;
1801
1802
                endif;
1803
1804
                if (!empty($post_term) && is_array($post_term)) {
1805
                    $categories = implode(',', $post_term);
1806
1807
                    if ($categories != '' && $categories != 0) $categories = ',' . $categories . ',';
1808
1809
                    if (empty($post_marker_json))
1810
                        $post_marker_json = isset($json) ? $json : '';
1811
1812
                    if ($wpdb->get_var($wpdb->prepare("SELECT post_id from " . $table . " where post_id = %d", array($post_id)))) {
1813
1814
                        $wpdb->query(
1815
                            $wpdb->prepare(
1816
                                "UPDATE " . $table . " SET
1817
								" . $taxonomy . " = %s,
1818
								marker_json = %s
1819
								where post_id = %d",
1820
                                array($categories, $post_marker_json, $post_id)
1821
                            )
1822
                        );
1823
1824
                        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'inline-save') {
1825
1826
                            $categories = trim($categories, ',');
1827
1828
                            if ($categories) {
1829
1830
                                $categories = explode(',', $categories);
1831
1832
                                $default_category = geodir_get_post_meta($post_id, 'default_category', true);
1833
1834
                                if (!in_array($default_category, $categories)) {
1835
1836
                                    $wpdb->query(
1837
                                        $wpdb->prepare(
1838
                                            "UPDATE " . $table . " SET
1839
											default_category = %s
1840
											where post_id = %d",
1841
                                            array($categories[0], $post_id)
1842
                                        )
1843
                                    );
1844
1845
                                    $default_category = $categories[0];
1846
1847
                                }
1848
1849
                                if ($default_category == '')
1850
                                    $default_category = $categories[0];
1851
1852
                                geodir_set_postcat_structure($post_id, $taxonomy, $default_category, '');
1853
1854
                            }
1855
1856
                        }
1857
1858
1859
                    } else {
1860
1861
                        $wpdb->query(
1862
                            $wpdb->prepare(
1863
                                "INSERT INTO " . $table . " SET
1864
								post_id = %d,
1865
								" . $taxonomy . " = %s,
1866
								marker_json = %s ",
1867
1868
                                array($post_id, $categories, $post_marker_json)
1869
                            )
1870
                        );
1871
                    }
1872
                }
1873
            }
1874 3
        }
1875 3
    }
1876
}
1877
1878
if (!function_exists('geodir_get_infowindow_html')) {
1879
    /**
1880
     * Set post Map Marker info html.
1881
     *
1882
     * @since 1.0.0
1883
     * @since 1.5.4 Modified to add new action "geodir_infowindow_meta_before".
1884
     * @since 1.6.16 Changes for disable review stars for certain post type.
1885
     * @since 1.6.18 Fix: Map marker not showing custom fields in bubble info.
1886
     * @package GeoDirectory
1887
     * @global array $geodir_addon_list List of active GeoDirectory extensions.
1888
     * @global object $gd_session GeoDirectory Session object.
1889
     * @param object $postinfo_obj The post details object.
1890
     * @param string $post_preview Is this a post preview?.
1891
     * @global object $post WordPress Post object.
1892
     * @return mixed|string|void
1893
     */
1894
    function geodir_get_infowindow_html($postinfo_obj, $post_preview = '') {
1895
        global $preview, $post, $gd_session;
1896
        $srcharr = array("'", "/", "-", '"', '\\');
1897
        $replarr = array("&prime;", "&frasl;", "&ndash;", "&ldquo;", '');
1898
1899
        if ($gd_session->get('listing') && isset($post_preview) && $post_preview != '') {
1900
            $ID = '';
1901
            $plink = '';
1902
1903
            if (isset($postinfo_obj->pid)) {
1904
                $ID = $postinfo_obj->pid;
1905
                $plink = get_permalink($ID);
1906
            }
1907
1908
            $title = str_replace($srcharr, $replarr, ($postinfo_obj->post_title));
1909
            $lat = $postinfo_obj->post_latitude;
1910
            $lng = $postinfo_obj->post_longitude;
1911
        } else {
1912
            $ID = $postinfo_obj->post_id;
1913
            $title = str_replace($srcharr, $replarr, htmlentities($postinfo_obj->post_title, ENT_COMPAT, 'UTF-8')); // fix by Stiofan
1914
            $title = wp_specialchars_decode($title); // Fixed #post-320722 on 2016-12-08
1915
            $plink = get_permalink($ID);
1916
            $lat = htmlentities(geodir_get_post_meta($ID, 'post_latitude', true));
1917
            $lng = htmlentities(geodir_get_post_meta($ID, 'post_longitude', true));
1918
        }
1919
        
1920
        // Some theme overwrites global gd listing $post
1921
        if (!empty($ID) && (!empty($post->ID) && $post->ID != $ID) || empty($post)) {
1922
            $post = geodir_get_post_info($ID);
1923
        }
1924
        
1925
        $post_type = $ID ? get_post_type($ID) : '';
1926
1927
        // filter field as per price package
1928
        global $geodir_addon_list;
1929
        if ($post_type && defined('GEODIRPAYMENT_VERSION')) {
1930
            $package_id = isset($postinfo_obj->package_id) && $postinfo_obj->package_id ? $postinfo_obj->package_id : NULL;
1931
            $field_name = 'geodir_contact';
1932
            if (!check_field_visibility($package_id, $field_name, $post_type)) {
1933
                $contact = '';
0 ignored issues
show
Unused Code introduced by
$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...
1934
            }
1935
1936
            $field_name = 'geodir_timing';
1937
            if (!check_field_visibility($package_id, $field_name, $post_type)) {
1938
                $timing = '';
0 ignored issues
show
Unused Code introduced by
$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...
1939
            }
1940
        }
1941
1942
        if ($lat && $lng) {
1943
            ob_start(); ?>
1944
            <div class="gd-bubble" style="">
1945
                <div class="gd-bubble-inside">
1946
                    <?php
1947
                    $comment_count = '';
0 ignored issues
show
Unused Code introduced by
$comment_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...
1948
                    $rating_star = '';
1949
                    if ($ID != '' && $post_type != '' && !geodir_cpt_has_rating_disabled($post_type)) {
1950
                        $rating_star = '';
1951
                        $comment_count = geodir_get_review_count_total($ID);
0 ignored issues
show
Unused Code introduced by
$comment_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...
1952
1953
                        if (!$preview) {
1954
                            $post_avgratings = geodir_get_post_rating($ID);
1955
1956
                            $rating_star = geodir_get_rating_stars($post_avgratings, $ID, false);
1957
1958
                            /**
1959
                             * Filter to change rating stars
1960
                             *
1961
                             * You can use this filter to change Rating stars.
1962
                             *
1963
                             * @since 1.0.0
1964
                             * @package GeoDirectory
1965
                             * @param string $rating_star Rating stars.
1966
                             * @param float $post_avgratings Average ratings of the post.
1967
                             * @param int $ID The post ID.
1968
                             */
1969
                            $rating_star = apply_filters('geodir_review_rating_stars_on_infowindow', $rating_star, $post_avgratings, $ID);
1970
                        }
1971
                    }
1972
                    ?>
1973
                    <div class="geodir-bubble_desc">
1974
                        <h4>
1975
                            <a href="<?php if ($plink != '') {
1976
                                echo $plink;
1977
                            } else {
1978
                                echo 'javascript:void(0);';
1979
                            } ?>"><?php echo $title; ?></a>
1980
                        </h4>
1981
                        <?php
1982
                        if ($gd_session->get('listing') && isset($post_preview) && $post_preview != '') {
1983
                            $post_images = array();
1984
                            if (!empty($postinfo_obj->post_images)) {
1985
                                $post_images = explode(",", $postinfo_obj->post_images);
1986
                            }
1987
1988
                            if (!empty($post_images)) {
1989
                                ?>
1990
                                <div class="geodir-bubble_image"><a href="<?php if ($plink != '') {
1991
                                        echo $plink;
1992
                                    } else {
1993
                                        echo 'javascript:void(0);';
1994
                                    } ?>"><img alt="bubble image" style="max-height:50px;"
1995
                                               src="<?php echo $post_images[0]; ?>"/></a></div>
1996
                            <?php
1997
                            }else{
1998
                                echo '<div class="geodir-bubble_image"></div>';
1999
                            }
2000
                        } else {
2001
                            if ($image = geodir_show_featured_image($ID, 'widget-thumb', true, false, $postinfo_obj->featured_image)) {
2002
                                ?>
2003
                                <div class="geodir-bubble_image"><a href="<?php echo $plink; ?>"><?php echo $image; ?></a></div>
2004
                            <?php
2005
                            }else{
2006
                                echo '<div class="geodir-bubble_image"></div>';
2007
                            }
2008
                        }
2009
                        ?>
2010
                        <div class="geodir-bubble-meta-side">
2011
                            <?php
2012
                            /**
2013
                             * Fires before the meta info in the map info window.
2014
                             *
2015
                             * This can be used to add more info to the map info window before the normal meta info.
2016
                             *
2017
                             * @since 1.5.4
2018
                             * @param int $ID The post id.
2019
                             * @param object $postinfo_obj The posts info as an object.
2020
                             * @param bool|string $post_preview True if currently in post preview page. Empty string if not.                           *
2021
                             */
2022
                            do_action('geodir_infowindow_meta_before', $ID, $postinfo_obj, $post_preview);
2023
2024
                            echo geodir_show_listing_info('mapbubble');
2025
2026
                            /**
2027
                             * Fires after the meta info in the map info window.
2028
                             *
2029
                             * This can be used to add more info to the map info window after the normal meta info.
2030
                             *
2031
                             * @since 1.4.2
2032
                             * @param object $postinfo_obj The posts info as an object.
2033
                             * @param bool|string $post_preview True if currently in post preview page. Empty string if not.                           *
2034
                             */
2035
                            do_action('geodir_infowindow_meta_after',$postinfo_obj,$post_preview );
2036
                            ?>
2037
                        </div>
2038
                        <?php
2039
                        if ($ID) {
2040
                            $post_author = isset($postinfo_obj->post_author) ? $postinfo_obj->post_author : get_post_field('post_author', $ID);
2041
                            ?>
2042
                            <div class="geodir-bubble-meta-fade"></div>
2043
                            <div class="geodir-bubble-meta-bottom">
2044
                                <?php if ($rating_star != '') { ?>
2045
                                <span class="geodir-bubble-rating"><?php echo $rating_star;?></span>
2046
                                <?php } ?>
2047
                                <span class="geodir-bubble-fav"><?php echo geodir_favourite_html($post_author, $ID);?></span>
2048
                                <span class="geodir-bubble-reviews">
2049
                                    <a href="<?php echo get_comments_link($ID); ?>" class="geodir-pcomments"><i class="fa fa-comments"></i> <?php echo get_comments_number($ID); ?></a>
2050
                                </span>
2051
                            </div>
2052
                        <?php } ?>
2053
                    </div>
2054
                </div>
2055
            </div>
2056
            <?php
2057
            $html = ob_get_clean();
2058
            /**
2059
             * Filter to change infowindow html
2060
             *
2061
             * You can use this filter to change infowindow html.
2062
             *
2063
             * @since 1.0.0
2064
             * @package GeoDirectory
2065
             * @param string $html Infowindow html.
2066
             * @param object $postinfo_obj The Post object.
2067
             * @param bool|string $post_preview Is this a post preview?
2068
             */
2069
            $html = apply_filters('geodir_custom_infowindow_html', $html, $postinfo_obj, $post_preview);
2070
            return $html;
2071
        }
2072
    }
2073
}
2074
2075
2076
/**
2077
 * Default post status for new posts.
2078
 *
2079
 * @since 1.0.0
2080
 * @package GeoDirectory
2081
 * @return string Returns the default post status for new posts. Ex: draft, publish etc.
2082
 */
2083
function geodir_new_post_default_status()
2084
{
2085
2086
    $status = get_option( 'geodir_new_post_default_status' );
2087
2088
    if ( empty( $status ) ) {
2089
        $status = 'publish';
2090
    }
2091
2092
    /**
2093
     * Filter the new post status.
2094
     *
2095
     * @since 1.6.23
2096
     */
2097
    return apply_filters( 'geodir_new_post_default_status', $status );
2098
2099
}
2100
2101
if (!function_exists('geodir_change_post_status')) {
2102
    /**
2103
     * Change post status of a post.
2104
     *
2105
     * @global object $wpdb WordPress Database object.
2106
     * @global string $plugin_prefix Geodirectory plugin table prefix.
2107
     * @param int|string $post_id The post ID.
2108
     * @param string $status New post status. Ex: draft, publish etc.
2109
     */
2110
    function geodir_change_post_status($post_id = '', $status = '')
2111
    {
2112 3
        global $wpdb, $plugin_prefix;
2113
2114 3
        $post_type = get_post_type($post_id);
2115
2116 3
        $table = $plugin_prefix . $post_type . '_detail';
2117
2118 3
        $wpdb->query(
2119 3
            $wpdb->prepare(
2120 3
                "UPDATE " . $table . " SET post_status=%s WHERE post_id=%d",
2121 3
                array($status, $post_id)
2122 3
            )
2123 3
        );
2124
2125
2126 3
    }
2127
}
2128
2129
/**
2130
 * Set post status of a post.
2131
 *
2132
 * @since 1.0.0
2133
 * @package GeoDirectory
2134
 * @global object $wpdb WordPress Database object.
2135
 * @param int $pid The post ID.
2136
 * @param string $status Post status. Ex: draft, publish etc.
2137
 */
2138
function geodir_set_post_status($pid, $status)
2139
{
2140
    if ($pid) {
2141
        global $wpdb;
2142
        $my_post = array();
2143
        $my_post['post_status'] = $status;
2144
        $my_post['ID'] = $pid;
2145
        $last_postid = wp_update_post($my_post);
0 ignored issues
show
Unused Code introduced by
$last_postid 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...
2146
    }
2147
}
2148
2149
2150
/**
2151
 * Update post status of a post.
2152
 *
2153
 * @since 1.0.0
2154
 * @package GeoDirectory
2155
 * @global object $wpdb WordPress Database object.
2156
 * @param string $new_status New post status. Ex: draft, publish etc.
2157
 * @param string $old_status Old post status. Ex: draft, publish etc.
2158
 * @param object $post The post object.
2159
 */
2160
function geodir_update_poststatus($new_status, $old_status, $post)
0 ignored issues
show
Unused Code introduced by
The parameter $old_status 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...
2161
{
2162 3
    global $wpdb;
2163
2164 3
    $geodir_posttypes = geodir_get_posttypes();
2165
2166 3
    if (!wp_is_post_revision($post->ID) && in_array($post->post_type, $geodir_posttypes)) {
2167
2168 3
        geodir_change_post_status($post->ID, $new_status);
2169 3
    }
2170 3
}
2171
2172
2173
if (!function_exists('geodir_update_listing_info')) {
2174
    /**
2175
     * Update post info.
2176
     *
2177
     * @since 1.0.0
2178
     * @package GeoDirectory
2179
     * @global object $wpdb WordPress Database object.
2180
     * @global string $plugin_prefix Geodirectory plugin table prefix.
2181
     * @param int $updatingpost The updating post ID.
2182
     * @param int $temppost The temporary post ID.
2183
     * @todo fix post_id variable
2184
     */
2185
    function geodir_update_listing_info($updatingpost, $temppost)
2186
    {
2187
2188
        global $wpdb, $plugin_prefix;
2189
2190
        $post_type = get_post_type($post_id);
0 ignored issues
show
Bug introduced by
The variable $post_id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
2191
2192
        $table = $plugin_prefix . $post_type . '_detail';
2193
2194
        $wpdb->query(
2195
            $wpdb->prepare(
2196
                "UPDATE " . $table . " SET `post_id` = %d WHERE `post_id` = %d",
2197
                array($updatingpost, $temppost)
2198
            )
2199
        );
2200
2201
        $wpdb->query(
2202
            $wpdb->prepare(
2203
                "UPDATE " . GEODIR_ICON_TABLE . " SET `post_id` = %d WHERE `post_id` = %d",
2204
                array($updatingpost, $temppost)
2205
            )
2206
        );
2207
2208
        /* Update Attachments*/
2209
2210
        $wpdb->query(
2211
            $wpdb->prepare(
2212
                "UPDATE " . GEODIR_ATTACHMENT_TABLE . " SET `post_id` = %d WHERE `post_id` = %d",
2213
                array($updatingpost, $temppost)
2214
            )
2215
        );
2216
2217
    }
2218
}
2219
2220
2221
if (!function_exists('geodir_delete_listing_info')) {
2222
    /**
2223
     * Delete Listing info from details table for the given post id.
2224
     *
2225
     * @since 1.0.0
2226
     * @package GeoDirectory
2227
     * @global object $wpdb WordPress Database object.
2228
     * @global string $plugin_prefix Geodirectory plugin table prefix.
2229
     * @param int $deleted_postid The post ID.
2230
     * @param bool $force Optional. Do you want to force delete it? Default: false.
2231
     * @return bool|void
2232
     */
2233
    function geodir_delete_listing_info($deleted_postid, $force = false)
0 ignored issues
show
Unused Code introduced by
The parameter $force 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...
2234
    {
2235
        global $wpdb, $plugin_prefix;
2236
2237
        // check for multisite deletions
2238
        if (strpos($plugin_prefix, $wpdb->prefix) !== false) {
2239
        } else {
2240
            return;
2241
        }
2242
2243
        $post_type = get_post_type($deleted_postid);
2244
2245
        $all_postypes = geodir_get_posttypes();
2246
2247
        if (!in_array($post_type, $all_postypes))
2248
            return false;
2249
2250
        $table = $plugin_prefix . $post_type . '_detail';
2251
2252
        /* Delete custom post meta*/
2253
        $wpdb->query(
2254
            $wpdb->prepare(
2255
                "DELETE FROM " . $table . " WHERE `post_id` = %d",
2256
                array($deleted_postid)
2257
            )
2258
        );
2259
2260
        /* Delete post map icons*/
2261
2262
        $wpdb->query(
2263
            $wpdb->prepare(
2264
                "DELETE FROM " . GEODIR_ICON_TABLE . " WHERE `post_id` = %d",
2265
                array($deleted_postid)
2266
            )
2267
        );
2268
2269
        /* Delete Attachments*/
2270
        $postcurr_images = geodir_get_images($deleted_postid);
2271
2272
        $wpdb->query(
2273
            $wpdb->prepare(
2274
                "DELETE FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE `post_id` = %d",
2275
                array($deleted_postid)
2276
            )
2277
        );
2278
        geodir_remove_attachments($postcurr_images);
0 ignored issues
show
Bug introduced by
It seems like $postcurr_images defined by geodir_get_images($deleted_postid) on line 2270 can also be of type boolean; however, geodir_remove_attachments() does only seem to accept array, 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...
2279
2280
    }
2281
}
2282
2283
2284
if (!function_exists('geodir_add_to_favorite')) {
2285
    /**
2286
     * This function would add listing to favorite listing.
2287
     *
2288
     * @since 1.0.0
2289
     * @package GeoDirectory
2290
     * @global object $current_user Current user object.
2291
     * @param int $post_id The post ID.
2292
     */
2293
    function geodir_add_to_favorite($post_id)
2294
    {
2295
2296
        global $current_user;
2297
2298
        /**
2299
         * Filter to modify "Unfavorite" text
2300
         *
2301
         * You can use this filter to rename "Unfavorite" text to something else.
2302
         *
2303
         * @since 1.0.0
2304
         * @package GeoDirectory
2305
         */
2306
        $remove_favourite_text = apply_filters('geodir_remove_favourite_text', REMOVE_FAVOURITE_TEXT);
2307
2308
        /**
2309
         * Filter to modify "Remove from Favorites" text
2310
         *
2311
         * You can use this filter to rename "Remove from Favorites" text to something else.
2312
         *
2313
         * @since 1.0.0
2314
         * @package GeoDirectory
2315
         */
2316
        $unfavourite_text = apply_filters('geodir_unfavourite_text', UNFAVOURITE_TEXT);
2317
2318
        /**
2319
         * Filter to modify "fa fa-heart" icon
2320
         *
2321
         * You can use this filter to change "fa fa-heart" icon to something else.
2322
         *
2323
         * @since 1.0.0
2324
         * @package GeoDirectory
2325
         */
2326
        $favourite_icon = apply_filters('geodir_favourite_icon', 'fa fa-heart');
2327
2328
        $site_id = '';
2329 View Code Duplication
        if ( is_multisite() ) {
2330
            $blog_id = get_current_blog_id();
2331
            if($blog_id && $blog_id!='1'){$site_id  = '_' . $blog_id ;}
2332
        }
2333
2334
        $user_meta_data = geodir_get_user_favourites($current_user->data->ID);
2335
        $user_meta_data = !empty($user_meta_data) && is_array($user_meta_data) ? $user_meta_data : array();
2336
2337
        if (empty($user_meta_data) || (!empty($user_meta_data) && !in_array($post_id, $user_meta_data))) {
2338
            $user_meta_data[] = $post_id;
2339
        }
2340
2341
        update_user_meta($current_user->data->ID, 'gd_user_favourite_post'.$site_id, $user_meta_data);
2342
2343
        /**
2344
         * Called before adding the post from favourites.
2345
         *
2346
         * @since 1.0.0
2347
         * @package GeoDirectory
2348
         * @param int $post_id The post ID.
2349
         */
2350
        do_action('geodir_before_add_from_favorite', $post_id);
2351
2352
        echo '<a href="javascript:void(0);" title="' . $remove_favourite_text . '" class="geodir-removetofav-icon" onclick="javascript:addToFavourite(\'' . $post_id . '\',\'remove\');"><i class="'. $favourite_icon .'"></i> ' . $unfavourite_text . '</a>';
2353
2354
        /**
2355
         * Called after adding the post from favourites.
2356
         *
2357
         * @since 1.0.0
2358
         * @package GeoDirectory
2359
         * @param int $post_id The post ID.
2360
         */
2361
        do_action('geodir_after_add_from_favorite', $post_id);
2362
2363
    }
2364
}
2365
2366
if (!function_exists('geodir_remove_from_favorite')) {
2367
    /**
2368
     * This function would remove the favourited property earlier.
2369
     *
2370
     * @since 1.0.0
2371
     * @package GeoDirectory
2372
     * @global object $current_user Current user object.
2373
     * @param int $post_id The post ID.
2374
     */
2375
    function geodir_remove_from_favorite($post_id)
2376
    {
2377
        global $current_user;
2378
2379
        /**
2380
         * Filter to modify "Add to Favorites" text
2381
         *
2382
         * You can use this filter to rename "Add to Favorites" text to something else.
2383
         *
2384
         * @since 1.0.0
2385
         * @package GeoDirectory
2386
         */
2387
        $add_favourite_text = apply_filters('geodir_add_favourite_text', ADD_FAVOURITE_TEXT);
2388
2389
        /**
2390
         * Filter to modify "Favourite" text
2391
         *
2392
         * You can use this filter to rename "Favourite" text to something else.
2393
         *
2394
         * @since 1.0.0
2395
         * @package GeoDirectory
2396
         */
2397
        $favourite_text = apply_filters('geodir_favourite_text', FAVOURITE_TEXT);
2398
2399
        /**
2400
         * Filter to modify "fa fa-heart" icon
2401
         *
2402
         * You can use this filter to change "fa fa-heart" icon to something else.
2403
         *
2404
         * @since 1.0.0
2405
         * @package GeoDirectory
2406
         */
2407
        $favourite_icon = apply_filters('geodir_favourite_icon', 'fa fa-heart');
2408
2409
        $site_id = '';
2410 View Code Duplication
        if ( is_multisite() ) {
2411
            $blog_id = get_current_blog_id();
2412
            if($blog_id && $blog_id!='1'){$site_id  = '_' . $blog_id ;}
2413
        }
2414
2415
        $user_meta_data = array();
0 ignored issues
show
Unused Code introduced by
$user_meta_data 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...
2416
        $user_meta_data = geodir_get_user_favourites($current_user->data->ID);
2417
2418
        if (!empty($user_meta_data)) {
2419
2420
            if (($key = array_search($post_id, $user_meta_data)) !== false) {
2421
                unset($user_meta_data[$key]);
2422
            }
2423
2424
        }
2425
2426
        update_user_meta($current_user->data->ID, 'gd_user_favourite_post'.$site_id, $user_meta_data);
2427
2428
        /**
2429
         * Called before removing the post from favourites.
2430
         *
2431
         * @since 1.0.0
2432
         * @package GeoDirectory
2433
         * @param int $post_id The post ID.
2434
         */
2435
        do_action('geodir_before_remove_from_favorite', $post_id);
2436
2437
        echo '<a href="javascript:void(0);"  title="' . $add_favourite_text . '" class="geodir-addtofav-icon" onclick="javascript:addToFavourite(\'' . $post_id . '\',\'add\');"><i class="'. $favourite_icon .'"></i> ' . $favourite_text . '</a>';
2438
2439
        /**
2440
         * Called after removing the post from favourites.
2441
         *
2442
         * @since 1.0.0
2443
         * @package GeoDirectory
2444
         * @param int $post_id The post ID.
2445
         */
2446
        do_action('geodir_after_remove_from_favorite', $post_id);
2447
2448
    }
2449
}
2450
2451
if (!function_exists('geodir_favourite_html')) {
2452
    /**
2453
     * This function would display the html content for add to favorite or remove from favorite.
2454
     *
2455
     * @since 1.0.0
2456
     * @package GeoDirectory
2457
     * @global object $current_user Current user object.
2458
     * @global object $post The current post object.
2459
     * @param int $user_id The user ID.
2460
     * @param int $post_id The post ID.
2461
     */
2462
    function geodir_favourite_html($user_id, $post_id)
0 ignored issues
show
Unused Code introduced by
The parameter $user_id 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
    {
2464
2465
        global $current_user, $post;
2466
2467
        /**
2468
         * Filter to modify "Add to Favorites" text
2469
         *
2470
         * You can use this filter to rename "Add to Favorites" text to something else.
2471
         *
2472
         * @since 1.0.0
2473
         * @package GeoDirectory
2474
         */
2475
        $add_favourite_text = apply_filters('geodir_add_favourite_text', ADD_FAVOURITE_TEXT);
2476
2477
        /**
2478
         * Filter to modify "Favourite" text
2479
         *
2480
         * You can use this filter to rename "Favourite" text to something else.
2481
         *
2482
         * @since 1.0.0
2483
         * @package GeoDirectory
2484
         */
2485
        $favourite_text = apply_filters('geodir_favourite_text', FAVOURITE_TEXT);
2486
2487
        /**
2488
         * Filter to modify "Unfavorite" text
2489
         *
2490
         * You can use this filter to rename "Unfavorite" text to something else.
2491
         *
2492
         * @since 1.0.0
2493
         * @package GeoDirectory
2494
         */
2495
        $remove_favourite_text = apply_filters('geodir_remove_favourite_text', REMOVE_FAVOURITE_TEXT);
2496
2497
        /**
2498
         * Filter to modify "Remove from Favorites" text
2499
         *
2500
         * You can use this filter to rename "Remove from Favorites" text to something else.
2501
         *
2502
         * @since 1.0.0
2503
         * @package GeoDirectory
2504
         */
2505
        $unfavourite_text = apply_filters('geodir_unfavourite_text', UNFAVOURITE_TEXT);
2506
2507
        /**
2508
         * Filter to modify "fa fa-heart" icon
2509
         *
2510
         * You can use this filter to change "fa fa-heart" icon to something else.
2511
         *
2512
         * @since 1.0.0
2513
         * @package GeoDirectory
2514
         */
2515
        $favourite_icon = apply_filters('geodir_favourite_icon', 'fa fa-heart');
2516
2517
        /**
2518
         * Filter to modify "fa fa-heart" icon for "remove from favorites" link
2519
         *
2520
         * You can use this filter to change "fa fa-heart" icon to something else.
2521
         *
2522
         * @since 1.0.0
2523
         * @package GeoDirectory
2524
         */
2525
        $unfavourite_icon = apply_filters('geodir_unfavourite_icon', 'fa fa-heart');
2526
2527
2528
        $site_id = '';
0 ignored issues
show
Unused Code introduced by
$site_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...
2529 View Code Duplication
        if ( is_multisite() ) {
2530
            $blog_id = get_current_blog_id();
2531
            if($blog_id && $blog_id!='1'){$site_id  = '_' . $blog_id ;}
0 ignored issues
show
Unused Code introduced by
$site_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...
2532
        }
2533
2534
        $user_meta_data = '';
2535
        if (isset($current_user->data->ID))
2536
            $user_meta_data = geodir_get_user_favourites($current_user->data->ID);
2537
2538
        if (!empty($user_meta_data) && in_array($post_id, $user_meta_data)) {
2539
            ?><span class="geodir-addtofav favorite_property_<?php echo $post_id;?>"  ><a
2540
                class="geodir-removetofav-icon" href="javascript:void(0);"
2541
                onclick="javascript:addToFavourite(<?php echo $post_id;?>,'remove');"
2542
                title="<?php echo $remove_favourite_text;?>"><i class="<?php echo $unfavourite_icon; ?>"></i> <?php echo $unfavourite_text;?>
2543
            </a>   </span><?php
2544
2545
        } else {
2546
2547
            if (!isset($current_user->data->ID) || $current_user->data->ID == '') {
2548
                $script_text = 'javascript:window.location.href=\'' . geodir_login_url() . '\'';
2549
            } else
2550
                $script_text = 'javascript:addToFavourite(' . $post_id . ',\'add\')';
2551
2552
            ?><span class="geodir-addtofav favorite_property_<?php echo $post_id;?>"><a class="geodir-addtofav-icon"
2553
                                                                                        href="javascript:void(0);"
2554
                                                                                        onclick="<?php echo $script_text;?>"
2555
                                                                                        title="<?php echo $add_favourite_text;?>"><i
2556
                    class="<?php echo $favourite_icon; ?>"></i> <?php echo $favourite_text;?></a></span>
2557
        <?php }
2558
    }
2559
}
2560
2561
2562
/**
2563
 * Get post count for the given category / term.
2564
 *
2565
 * @since 1.0.0
2566
 * @package GeoDirectory
2567
 * @global object $wpdb WordPress Database object.
2568
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2569
 * @param object|array $term category / term object that need to be processed.
2570
 * @return bool|int|null|string Post count.
2571
 */
2572
function geodir_get_cat_postcount($term = array())
2573
{
2574
2575
    if (!empty($term)) {
2576
2577
        global $wpdb, $plugin_prefix;
2578
2579
        $where = '';
2580
        $join = '';
2581
        if (get_query_var('gd_country') != '' || get_query_var('gd_region') != '' || get_query_var('gd_city') != '') {
2582
            $taxonomy_obj = get_taxonomy($term->taxonomy);
2583
2584
            $post_type = $taxonomy_obj->object_type[0];
2585
2586
            $table = $plugin_prefix . $post_type . '_detail';
2587
2588
            /**
2589
             * Filter to modify the 'join' query
2590
             *
2591
             * @since 1.0.0
2592
             * @package GeoDirectory
2593
             * @param object|array $term category / term object that need to be processed.
2594
             * @param string $join The join query.
2595
             */
2596
            $join = apply_filters('geodir_cat_post_count_join', $join, $term);
2597
2598
            /**
2599
             * Filter to modify the 'where' query
2600
             *
2601
             * @since 1.0.0
2602
             * @package GeoDirectory
2603
             * @param object|array $term category / term object that need to be processed.
2604
             * @param string $where The where query.
2605
             */
2606
            $where = apply_filters('geodir_cat_post_count_where', $where, $term);
2607
2608
            $count_query = "SELECT count(post_id) FROM
2609
							" . $table . " as pd " . $join . "
2610
							WHERE pd.post_status='publish' AND FIND_IN_SET('" . $term->term_id . "'," . $term->taxonomy . ") " . $where;
2611
2612
            $cat_post_count = $wpdb->get_var($count_query);
2613
            if (empty($cat_post_count) || is_wp_error($cat_post_count))
2614
                $cat_post_count = 0;
2615
2616
            return $cat_post_count;
2617
2618
        } else
2619
2620
            return $term->count;
2621
    }
2622
    return false;
2623
2624
}
2625
2626
2627
/**
2628
 * Allow add post type from front end
2629
 *
2630
 * @since 1.0.0
2631
 * @package GeoDirectory
2632
 */
2633
function geodir_allow_post_type_frontend()
2634
{
2635
    $geodir_allow_posttype_frontend = get_option('geodir_allow_posttype_frontend');
2636
2637
    if (!is_admin() && isset($_REQUEST['listing_type'])
2638
        && !empty($geodir_allow_posttype_frontend)
2639
        && !in_array($_REQUEST['listing_type'], $geodir_allow_posttype_frontend)
2640
    ) {
2641
2642
        wp_redirect(home_url());
2643
        exit;
2644
2645
    }
2646
2647
}
2648
2649
/**
2650
 * Changing excerpt length.
2651
 *
2652
 * @since 1.0.0
2653
 * @since 1.5.7 Hide description when description word limit is 0.
2654
 * @package GeoDirectory
2655
 * @global object $wp_query WordPress Query object.
2656
 * @global bool $geodir_is_widget_listing Is this a widget listing?
2657
 * @param int $length Optional. Old length.
2658
 * @return mixed|void Returns length.
2659
 */
2660
function geodir_excerpt_length($length)
2661
{
2662
    global $wp_query, $geodir_is_widget_listing;
2663
	if ($geodir_is_widget_listing) {
2664
		return $length;
2665
	}
2666
	
2667
    if (isset($wp_query->query_vars['is_geodir_loop']) && $wp_query->query_vars['is_geodir_loop'] && get_option('geodir_desc_word_limit'))
2668
        $length = get_option('geodir_desc_word_limit');
2669
    elseif (get_query_var('excerpt_length'))
2670
        $length = get_query_var('excerpt_length');
2671
2672
    if (geodir_is_page('author') && get_option('geodir_author_desc_word_limit'))
2673
        $length = get_option('geodir_author_desc_word_limit');
2674
2675
    return $length;
2676
}
2677
2678
/**
2679
 * Changing excerpt more.
2680
 *
2681
 * @since 1.0.0
2682
 * @since 1.5.4 Now only applied to GD post types.
2683
 * @package GeoDirectory
2684
 * @global object $post The current post object.
2685
 * @param string $more Optional. Old string.
2686
 * @return string Returns read more link.
2687
 */
2688
function geodir_excerpt_more($more)
2689
{
2690
    global $post;
2691
    $all_postypes = geodir_get_posttypes();
2692
    if (is_array($all_postypes) && in_array($post->post_type, $all_postypes)) {
2693
        $out = ' <a class="excerpt-read-more" href="' .  get_permalink($post->ID) . '" title="' . get_the_title($post->ID) . '">';
2694
        /**
2695
         * Filter excerpt read more text.
2696
         *
2697
         * @since 1.0.0
2698
         */
2699
        $out .= apply_filters( 'geodir_max_excerpt_end', __( 'Read more [...]', 'geodirectory' ) );
2700
        $out .= '</a>';
2701
        return $out;
2702
    }
2703
2704
    return $more;
2705
}
2706
2707
2708
/**
2709
 * Update markers on category Edit.
2710
 *
2711
 * @since 1.0.0
2712
 * @package GeoDirectory
2713
 * @global object $wpdb WordPress Database object.
2714
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2715
 * @param string $term_id The term ID as string.
2716
 * @param int $tt_id The term taxonomy ID.
2717
 * @param string $taxonomy The taxonomy slug.
2718
 */
2719
function geodir_update_markers_oncatedit($term_id, $tt_id, $taxonomy)
0 ignored issues
show
Unused Code introduced by
The parameter $tt_id 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...
2720
{
2721
    global $plugin_prefix, $wpdb;
2722
2723
    $gd_taxonomies = geodir_get_taxonomies();
2724
2725
    if (is_array($gd_taxonomies) && in_array($taxonomy, $gd_taxonomies)) {
2726
2727
        $geodir_post_type = geodir_get_taxonomy_posttype($taxonomy);
2728
        $table = $plugin_prefix . $geodir_post_type . '_detail';
2729
2730
        $path_parts = pathinfo($_REQUEST['ct_cat_icon']['src']);
2731
        $term_icon = $path_parts['dirname'] . '/cat_icon_' . $term_id . '.png';
2732
2733
        $posts = $wpdb->get_results(
2734
            $wpdb->prepare(
2735
                "SELECT post_id,post_title,post_latitude,post_longitude,default_category FROM " . $table . " WHERE FIND_IN_SET(%s,%1\$s ) ",
2736
                array($term_id, $taxonomy)
2737
            )
2738
        );
2739
2740
        if (!empty($posts)):
2741
            foreach ($posts as $post_obj) {
2742
2743
                $lat = $post_obj->post_latitude;
2744
                $lng = $post_obj->post_longitude;
2745
2746
                $json = '{';
2747
                $json .= '"id":"' . $post_obj->post_id . '",';
2748
                $json .= '"lat_pos": "' . $lat . '",';
2749
                $json .= '"long_pos": "' . $lng . '",';
2750
                $json .= '"marker_id":"' . $post_obj->post_id . '_' . $term_id . '",';
2751
                $json .= '"icon":"' . $term_icon . '",';
2752
                $json .= '"group":"catgroup' . $term_id . '"';
2753
                $json .= '}';
2754
2755
                if ($post_obj->default_category == $term_id) {
2756
2757
                    $wpdb->query(
2758
                        $wpdb->prepare(
2759
                            "UPDATE " . $table . " SET marker_json = %s where post_id = %d",
2760
                            array($json, $post_obj->post_id)
2761
                        )
2762
                    );
2763
                }
2764
2765
                $wpdb->query(
2766
                    $wpdb->prepare(
2767
                        "UPDATE " . GEODIR_ICON_TABLE . " SET json = %s WHERE post_id = %d AND cat_id = %d",
2768
                        array($json, $post_obj->post_id, $term_id)
2769
                    )
2770
                );
2771
2772
            }
2773
2774
2775
        endif;
2776
2777
    }
2778
2779
}
2780
2781
/**
2782
 * Get listing author id.
2783
 *
2784
 * @since 1.0.0
2785
 * @package GeoDirectory
2786
 * @param int|string $listing_id The post ID.
2787
 * @return string|int The author ID.
2788
 */
2789
function geodir_get_listing_author($listing_id = '')
2790
{
2791
    if ($listing_id == '') {
2792
        if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
2793
            $listing_id = $_REQUEST['pid'];
2794
        }
2795
    }
2796
    $listing = get_post(strip_tags($listing_id));
2797
    $listing_author_id = $listing->post_author;
2798
    return $listing_author_id;
2799
}
2800
2801
2802
/**
2803
 * Check whether a listing belongs to a user or not.
2804
 *
2805
 * @since 1.0.0
2806
 * @package GeoDirectory
2807
 * @param int|string $listing_id The post ID.
2808
 * @param int $user_id The user ID.
2809
 * @return bool
2810
 */
2811
function geodir_lisiting_belong_to_user($listing_id, $user_id)
2812
{
2813
    $listing_author_id = geodir_get_listing_author($listing_id);
2814
    if ($listing_author_id == $user_id)
2815
        return true;
2816
    else
2817
        return false;
2818
2819
}
2820
2821
/**
2822
 * Check whether a listing belongs to current user or not.
2823
 *
2824
 * @since 1.0.0
2825
 * @package GeoDirectory
2826
 * @global object $current_user Current user object.
2827
 * @param int|string $listing_id The post ID.
2828
 * @param bool $exclude_admin Optional. Do you want to exclude admin from the check?. Default true.
2829
 * @return bool
2830
 */
2831
function geodir_listing_belong_to_current_user($listing_id = '', $exclude_admin = true)
2832
{
2833
    global $current_user;
2834
    if ($exclude_admin) {
2835
        foreach ($current_user->caps as $key => $caps) {
2836
            if (geodir_strtolower($key) == 'administrator') {
2837
                return true;
2838
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2839
            }
2840
        }
2841
    }
2842
2843
    $result = geodir_lisiting_belong_to_user($listing_id, $current_user->ID);
2844
2845
    /**
2846
     * Filter if the listing belongs to a user.
2847
     *
2848
     * @since 1.6.23
2849
     * @param bool $result The result, true:false
2850
     * @param int $listing_id The post ID.
2851
     * @param int $current_user->ID The current user ID.
2852
     * @param bool $exclude_admin Do you want to exclude admin from the check?. Default true.
2853
     * return bool
2854
     */
2855
    return apply_filters('geodir_listing_belong_to_current_user',$result,$listing_id,$current_user->ID,$exclude_admin);
2856
}
2857
2858
2859
/**
2860
 * Delete only supported attachments. This function is hooked to wp_delete_file filter.
2861
 *
2862
 * @since 1.0.0
2863
 * @package GeoDirectory
2864
 * @global object $wpdb WordPress Database object.
2865
 * @param string $file. The File path.
0 ignored issues
show
Bug introduced by
There is no parameter named $file.. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
2866
 * @return string File path if valid. Else empty string.
2867
 */
2868
function geodir_only_supportable_attachments_remove($file)
2869
{
2870
2871
    global $wpdb;
2872
2873
    $matches = array();
2874
2875
    $pattern = '/-\d+x\d+\./';
2876
    preg_match($pattern, $file, $matches, PREG_OFFSET_CAPTURE);
2877
2878
    if (empty($matches))
2879
        return '';
2880
    else
2881
        return $file;
2882
2883
}
2884
2885
2886
/**
2887
 * Set first image as post's featured image.
2888
 *
2889
 * @since 1.0.0
2890
 * @package GeoDirectory
2891
 * @global object $wpdb WordPress Database object.
2892
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2893
 * @param int $post_id The post ID.
2894
 */
2895
function geodir_set_wp_featured_image($post_id)
2896
{
2897
2898 3
    global $wpdb, $plugin_prefix;
2899 3
    $uploads = wp_upload_dir();
2900
//	print_r($uploads ) ;
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...
2901 3
    $post_first_image = $wpdb->get_results(
2902 3
        $wpdb->prepare(
2903 3
            "SELECT * FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE post_id = %d and menu_order = 1  ", array($post_id)
2904 3
        )
2905 3
    );
2906
2907 3
    $old_attachment_name = '';
2908 3
    $post_thumbnail_id = '';
2909 3
    if (has_post_thumbnail($post_id)) {
2910
2911
        if (has_post_thumbnail($post_id)) {
2912
2913
            $post_thumbnail_id = get_post_thumbnail_id($post_id);
2914
2915
            $old_attachment_name = basename(get_attached_file($post_thumbnail_id));
2916
2917
        }
2918
    }
2919
2920 3
    if (!empty($post_first_image)) {
2921
2922
        $post_type = get_post_type($post_id);
2923
2924
        $table_name = $plugin_prefix . $post_type . '_detail';
2925
2926
        $wpdb->query("UPDATE " . $table_name . " SET featured_image='" . $post_first_image[0]->file . "' WHERE post_id =" . $post_id);
2927
2928
        $new_attachment_name = basename($post_first_image[0]->file);
2929
2930
        if (geodir_strtolower($new_attachment_name) != geodir_strtolower($old_attachment_name)) {
2931
2932
            if (has_post_thumbnail($post_id) && $post_thumbnail_id != '' && (!isset($_REQUEST['action']) || $_REQUEST['action'] != 'delete')) {
2933
2934
                add_filter('wp_delete_file', 'geodir_only_supportable_attachments_remove');
2935
2936
                wp_delete_attachment($post_thumbnail_id);
2937
2938
            }
2939
            $filename = $uploads['basedir'] . $post_first_image[0]->file;
2940
2941
            $attachment = array(
2942
                'post_mime_type' => $post_first_image[0]->mime_type,
2943
                'guid' => $uploads['baseurl'] . $post_first_image[0]->file,
2944
                'post_parent' => $post_id,
2945
                'post_title' => preg_replace('/\.[^.]+$/', '', $post_first_image[0]->title),
2946
                'post_content' => ''
2947
            );
2948
2949
2950
            $id = wp_insert_attachment($attachment, $filename, $post_id);
2951
2952
            if (!is_wp_error($id)) {
2953
2954
                set_post_thumbnail($post_id, $id);
2955
2956
                require_once(ABSPATH . 'wp-admin/includes/image.php');
2957
                wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $filename));
2958
2959
            }
2960
2961
        }
2962
2963
    } else {
2964
        //set_post_thumbnail($post_id,-1);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
2965
2966 3
        if (has_post_thumbnail($post_id) && $post_thumbnail_id != '' && (!isset($_REQUEST['action']) || $_REQUEST['action'] != 'delete'))
2967 3
            wp_delete_attachment($post_thumbnail_id);
2968
2969
    }
2970 3
}
2971
2972
2973
/**
2974
 * Function to copy custom meta info on WPML copy.
2975
 *
2976
 * @since 1.0.0
2977
 * @package GeoDirectory
2978
 * @global object $wpdb WordPress Database object.
2979
 * @global string $table_prefix WordPress Database Table prefix.
2980
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2981
 */
2982
function gd_copy_original_translation()
2983
{
2984
    if (geodir_is_wpml()) {
2985
        global $wpdb, $table_prefix, $plugin_prefix;
2986
        $post_id = absint($_POST['post_id']);
2987
        $upload_dir = wp_upload_dir();
2988
        $post_type = get_post_type($_POST['post_id']);
2989
        $table = $plugin_prefix . $post_type . '_detail';
2990
2991
        $post_arr = $wpdb->get_results($wpdb->prepare(
2992
            "SELECT * FROM $wpdb->posts p JOIN " . $table . " gd ON gd.post_id=p.ID WHERE p.ID=%d LIMIT 1",
2993
            array($post_id)
2994
        )
2995
            , ARRAY_A);
2996
2997
        $arrImages = $wpdb->get_results(
2998
            $wpdb->prepare(
2999
                "SELECT * FROM " . GEODIR_ATTACHMENT_TABLE . " WHERE mime_type like %s AND post_id = %d ORDER BY menu_order ASC, ID DESC ",
3000
                array('%image%', $post_id)
3001
            )
3002
        );
3003
        if ($arrImages) {
3004
            $image_arr = array();
3005
            foreach ($arrImages as $img) {
3006
                $image_arr[] = $upload_dir['baseurl'] . $img->file;
3007
            }
3008
            $comma_separated = implode(",", $image_arr);
3009
            $post_arr[0]['post_images'] = $comma_separated;
3010
        }
3011
3012
3013
        $cats = $post_arr[0][$post_arr[0]['post_type'] . 'category'];
3014
        $cat_arr = array_filter(explode(",", $cats));
3015
        $trans_cat = array();
3016
        foreach ($cat_arr as $cat) {
3017
            $trans_cat[] = geodir_wpml_object_id($cat, $post_arr[0]['post_type'] . 'category', false);
3018
        }
3019
3020
3021
        $post_arr[0]['categories'] = array_filter($trans_cat);
3022
//print_r($image_arr);
3023
        //print_r($arrImages);
3024
        //echo $_REQUEST['lang'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
3025
//print_r($post_arr);
3026
//print_r($trans_cat);
3027
        echo json_encode($post_arr[0]);
3028
3029
    }
3030
    die();
3031
}
3032
3033
3034
add_action('wp_ajax_gd_copy_original_translation', 'gd_copy_original_translation');
3035
//add_action('wp_ajax_nopriv_dc_update_profile', 'dc_update_profile_callback');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
3036
3037
3038
/**
3039
 * Get custom fields info using listing post type.
3040
 *
3041
 * @since 1.0.0
3042
 * @package GeoDirectory
3043
 * @global object $wpdb WordPress Database object.
3044
 * @param string $listing_type The listing post type.
3045
 * @return mixed|void|array custom fields info as an array.
3046
 */
3047
function geodir_get_custom_fields_type($listing_type = '')
3048
{
3049
3050
    global $wpdb;
3051
3052
    if ($listing_type == '')
3053
        $listing_type = 'gd_place';
3054
3055
    $fields_info = array();
3056
3057
    $get_data = $wpdb->get_results(
3058
        $wpdb->prepare(
3059
            "SELECT htmlvar_name, field_type, extra_fields FROM " . GEODIR_CUSTOM_FIELDS_TABLE . " WHERE post_type=%s AND is_active='1'",
3060
            array($listing_type)
3061
        )
3062
    );
3063
3064
    if (!empty($get_data)) {
3065
3066
        foreach ($get_data as $data) {
3067
3068
            if ($data->field_type == 'address') {
3069
3070
                $extra_fields = unserialize($data->extra_fields);
3071
3072
                $prefix = $data->htmlvar_name . '_';
3073
3074
                $fields_info[$prefix . 'address'] = $data->field_type;
3075
3076
                if (isset($extra_fields['show_zip']) && $extra_fields['show_zip'])
3077
                    $fields_info[$prefix . 'zip'] = $data->field_type;
3078
3079
            } else {
3080
3081
                $fields_info[$data->htmlvar_name] = $data->field_type;
3082
3083
            }
3084
3085
        }
3086
3087
    }
3088
3089
    /**
3090
     * Filter to modify custom fields info using listing post type.
3091
     *
3092
     * @since 1.0.0
3093
     * @package GeoDirectory
3094
     * @return array $fields_info Custom fields info.
3095
     * @param string $listing_type The listing post type.
3096
     */
3097
    return apply_filters('geodir_get_custom_fields_type', $fields_info, $listing_type);
3098
}
3099
3100
3101
/**
3102
 * Called when post updated.
3103
 *
3104
 * @since 1.0.0
3105
 * @package GeoDirectory
3106
 * @param int $post_ID The post ID.
3107
 * @param object $post_after The post object after update.
3108
 * @param object $post_before The post object before update.
3109
 */
3110
function geodir_function_post_updated($post_ID, $post_after, $post_before)
3111
{
3112
    $post_type = get_post_type($post_ID);
3113
3114
    if ($post_type != '' && in_array($post_type, geodir_get_posttypes())) {
3115
        // send notification to client when post moves from draft to publish
3116
        if (!empty($post_after->post_status) && $post_after->post_status == 'publish' && !empty($post_before->post_status) && ($post_before->post_status == 'draft' || $post_before->post_status == 'auto-draft' || $post_before->post_status == 'pending')) {
3117
            $post_author_id = !empty($post_after->post_author) ? $post_after->post_author : NULL;
3118
            $post_author_data = get_userdata($post_author_id);
3119
3120
            $to_name = geodir_get_client_name($post_author_id);
3121
3122
            $from_email = geodir_get_site_email_id();
3123
            $from_name = get_site_emailName();
3124
            $to_email = $post_author_data->user_email;
3125
3126
            if (!is_email($to_email) && !empty($post_author_data->user_email)) {
3127
                $to_email = $post_author_data->user_email;
3128
            }
3129
3130
            $message_type = 'listing_published';
3131
3132
            if (get_option('geodir_post_published_email_subject') == '') {
3133
                update_option('geodir_post_published_email_subject', __('Listing Published Successfully', 'geodirectory'));
3134
            }
3135
3136
            if (get_option('geodir_post_published_email_content') == '') {
3137
                update_option('geodir_post_published_email_content', __("<p>Dear [#client_name#],</p><p>Your listing [#listing_link#] has been published. This email is just for your information.</p><p>[#listing_link#]</p><br><p>Thank you for your contribution.</p><p>[#site_name#]</p>", 'geodirectory'));
3138
            }
3139
3140
            /**
3141
             * Called before sending the email when listing gets published.
3142
             *
3143
             * @since 1.0.0
3144
             * @package GeoDirectory
3145
             * @param object $post_after The post object after update.
3146
             * @param object $post_before The post object before update.
3147
             */
3148
            do_action('geodir_before_listing_published_email', $post_after, $post_before);
3149
            if (is_email($to_email)) {
3150
                geodir_sendEmail($from_email, $from_name, $to_email, $to_name, '', '', '', $message_type, $post_ID);
3151
            }
3152
3153
            /**
3154
             * Called after sending the email when listing gets published.
3155
             *
3156
             * @since 1.0.0
3157
             * @package GeoDirectory
3158
             * @param object $post_after The post object after update.
3159
             * @param object $post_before The post object before update.
3160
             */
3161
            do_action('geodir_after_listing_published_email', $post_after, $post_before);
3162
        }
3163
    }
3164
}
3165
3166
add_action('wp_head', 'geodir_fb_like_thumbnail');
3167
3168
3169
/**
3170
 * Adds the featured image to the place details page header so facebook can use it when sharing the link.
3171
 *
3172
 * @since 1.4.9
3173
 * @since 1.6.22 Added image from location page.
3174
 * @package GeoDirectory
3175
 */
3176
function geodir_fb_like_thumbnail(){
3177
3178
    $facebook_image = '';
3179
3180
    if(is_single()){// single post
3181
        global $post;
3182
        if(isset($post->featured_image) && $post->featured_image){
3183
            $upload_dir = wp_upload_dir();
3184
            $facebook_image = $upload_dir['baseurl'].$post->featured_image;
3185
3186
        }
3187
    }elseif(geodir_is_page('location')){// location page
3188
        if (function_exists('geodir_get_location_seo')) {
3189
            $seo = geodir_get_location_seo();
3190
            if (isset($seo->seo_image) && $seo->seo_image) {
3191
                $image = wp_get_attachment_image_src($seo->seo_image, 'full');
3192
                $facebook_image = isset($image[0]) ? $image[0] : '';
3193
            }
3194
        }
3195
3196
        if(!$facebook_image){
3197
            global $post;
3198
3199
            if (has_post_thumbnail( $post->ID ) ){
3200
                $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
3201
                $facebook_image = isset($image[0]) ? $image[0] : '';
3202
            }
3203
        }
3204
    }
3205
3206
3207
    /**
3208
     * Filter the facebook share image.
3209
     *
3210
     * @since 1.6.22
3211
     * @param string $facebook_image The image URL or blank.
3212
     */
3213
    $facebook_image = apply_filters('geodir_fb_share_image',$facebook_image);
3214
3215
    if($facebook_image){
3216
        echo "\n\n<!-- GD Facebook Like Thumbnail -->\n<link rel=\"image_src\" href=\"$facebook_image\" />\n<!-- End GD Facebook Like Thumbnail -->\n\n";
3217
    }
3218
3219
3220
}
3221
3222
add_action( 'save_post', 'geodir_clear_map_cache_on_save', 10,2 );
3223
3224
3225
/**
3226
 * Delete the map cache files.
3227
 *
3228
 * @since 1.6.22
3229
 */
3230
function geodir_delete_map_cache(){
3231
    $files = glob(realpath(dirname(__FILE__))."/map-functions/map-cache/*.json"); // get all file names
3232
    foreach($files as $file){ // iterate files
3233
        if(is_file($file))
3234
            unlink($file); // delete file
3235
    }
3236
}
3237
3238
3239
/**
3240
 * Clear the map cache on post save.
3241
 *
3242
 * @since 1.6.22
3243
 * @param object $post WordPress Post object.
3244
 * @param int $post_id The post ID.
3245
 */
3246
function geodir_clear_map_cache_on_save($post_id, $post) {
3247
3248 3
    if(!get_option('geodir_enable_map_cache')){
3249 3
        return;
3250
    }
3251
3252 View Code Duplication
    if ( isset( $post->post_type ) && ( $post->post_type == 'nav_menu_item' || $post->post_type == 'page' || $post->post_type == 'post' ) ) {
3253
        return;
3254
    }
3255
3256
    $geodir_posttypes = geodir_get_posttypes();
3257
3258
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
3259
        return;
3260
    }
3261
3262
    if ( ! wp_is_post_revision( $post_id ) && isset( $post->post_type ) && in_array( $post->post_type, $geodir_posttypes ) ) {
3263
        geodir_delete_map_cache();
3264
    }
3265
3266
}
3267
3268
/**
3269
 * Set the post name for the pending listing.
3270
 *
3271
 * @since 1.6.22
3272
 * @since 1.6.23 Fix post name for autosaved listing from backend.
3273
 *
3274
 * @param array $data    An array of slashed post data.
3275
 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3276
 * @return array Filtered post data.
3277
 */
3278
function geodir_fix_pending_listing_post_name( $data, $postarr ) {
3279
    // Dont' update post name for autosaves
3280 3
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
3281
        return $data;
3282
    }
3283
3284 3
    if ( !empty( $data['post_name'] ) || empty( $data['post_status'] ) || empty( $data['post_type'] ) || empty( $data['post_title'] ) ) {
3285 3
        return $data;
3286
    }
3287
3288
    if ( ( 'draft' == $data['post_status'] || 'pending' == $data['post_status'] ) && in_array( $data['post_type'], geodir_get_posttypes() ) ) {
3289
        $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), ( !empty( $postarr['ID'] ) ? $postarr['ID'] : 0 ), '', $data['post_type'], $data['post_parent'] );
3290
    }
3291
3292
    return $data;
3293
}
3294
add_filter( 'wp_insert_post_data', 'geodir_fix_pending_listing_post_name', 10, 2 );