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

general_functions.php ➔ sendEmail()   F

Complexity

Conditions 19
Paths 1920

Size

Total Lines 104
Code Lines 80

Duplication

Lines 16
Ratio 15.38 %

Code Coverage

Tests 0
CRAP Score 380
Metric Value
cc 19
eloc 80
nc 1920
nop 10
dl 16
loc 104
ccs 0
cts 92
cp 0
crap 380
rs 2

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * Plugin general functions
4
 *
5
 * @since 1.0.0
6
 * @package GeoDirectory
7
 */
8
9
10
/**
11
 * Get All Plugin functions from WordPress
12
 */
13
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
14
15
/*-----------------------------------------------------------------------------------*/
16
/* Helper functions */
17
/*-----------------------------------------------------------------------------------*/
18
19
/**
20
 * Return the plugin url.
21
 *
22
 * Return the plugin folder url WITHOUT TRAILING SLASH.
23
 *
24
 * @since 1.0.0
25
 * @package GeoDirectory
26
 * @return string example url eg: http://wpgeo.directory/wp-content/plugins/geodirectory
27
 */
28
function geodir_plugin_url()
29
{
30
31 16
    if (is_ssl()) :
32
        return str_replace('http://', 'https://', WP_PLUGIN_URL) . "/" . plugin_basename(dirname(dirname(__FILE__)));
33
    else :
34 16
        return WP_PLUGIN_URL . "/" . plugin_basename(dirname(dirname(__FILE__)));
35
    endif;
36
}
37
38
39
/**
40
 * Return the plugin path.
41
 *
42
 * Return the plugin folder path WITHOUT TRAILING SLASH.
43
 *
44
 * @since 1.0.0
45
 * @package GeoDirectory
46
 * @return string example url eg: /home/geo/public_html/wp-content/plugins/geodirectory
47
 */
48
function geodir_plugin_path()
49
{
50 27
    if ( defined( 'GD_TESTING_MODE' ) && GD_TESTING_MODE ) {
51 27
        return dirname(dirname(__FILE__));
52
    } else {
53
        return WP_PLUGIN_DIR . "/" . plugin_basename(dirname(dirname(__FILE__)));
54
    }
55
}
56
57
/**
58
 * Check if a GeoDirectory addon plugin is active.
59
 *
60
 * @since 1.0.0
61
 * @package GeoDirectory
62
 * @param string $plugin plugin uri.
63
 * @return bool true or false.
64
 * @todo check if this is faster than normal WP check and remove if not.
65
 */
66
function geodir_is_plugin_active($plugin)
67
{
68
    $active_plugins = get_option('active_plugins');
69
    foreach ($active_plugins as $key => $active_plugin) {
70
        if (strstr($active_plugin, $plugin)) return true;
71
    }
72
    return false;
73
}
74
75
76
/**
77
 * Return the formatted date.
78
 *
79
 * Return a formatted date from a date/time string according to WordPress date format. $date must be in format : 'Y-m-d H:i:s'.
80
 *
81
 * @since 1.0.0
82
 * @package GeoDirectory
83
 * @param string $date must be in format: 'Y-m-d H:i:s'.
84
 * @return bool|int|string the formatted date.
85
 */
86
function geodir_get_formated_date($date)
0 ignored issues
show
Best Practice introduced by
The function geodir_get_formated_date() has been defined more than once; this definition is ignored, only the first definition in geodirectory-functions/custom_fields_functions.php (L3202-3205) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
87
{
88
    return mysql2date(get_option('date_format'), $date);
89
}
90
91
/**
92
 * Return the formatted time.
93
 *
94
 * Return a formatted time from a date/time string according to WordPress time format. $time must be in format : 'Y-m-d H:i:s'.
95
 *
96
 * @since 1.0.0
97
 * @package GeoDirectory
98
 * @param string $time must be in format: 'Y-m-d H:i:s'.
99
 * @return bool|int|string the formatted time.
100
 */
101
function geodir_get_formated_time($time)
0 ignored issues
show
Best Practice introduced by
The function geodir_get_formated_time() has been defined more than once; this definition is ignored, only the first definition in geodirectory-functions/custom_fields_functions.php (L3217-3220) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
102
{
103
    return mysql2date(get_option('time_format'), $time, $translate = true);
104
}
105
106
107
/**
108
 * Return a formatted link with parameters.
109
 *
110
 * Returns a link with new parameters and currently used parameters regardless of ? or & in the $url parameter.
111
 *
112
 * @since 1.0.0
113
 * @package GeoDirectory
114
 * @param string $url The main url to be used.
115
 * @param array $params The arguments array.
116
 * @param bool $use_existing_arguments Do you want to use existing arguments? Default: false.
117
 * @return string Formatted link.
118
 */
119
function geodir_getlink($url, $params = array(), $use_existing_arguments = false)
120
{
121 12
    if ($use_existing_arguments) $params = $params + $_GET;
122 12
    if (!$params) return $url;
0 ignored issues
show
Bug Best Practice introduced by
The expression $params of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
123 12
    $link = $url;
124 12
    if (strpos($link, '?') === false) $link .= '?'; //If there is no '?' add one at the end
125 12
    elseif (strpos($link, '//maps.google.com/maps/api/js?language=')) $link .= '&amp;'; //If there is no '&' at the END, add one.
126 12
    elseif (!preg_match('/(\?|\&(amp;)?)$/', $link)) $link .= '&'; //If there is no '&' at the END, add one.
127
128 12
    $params_arr = array();
129 12
    foreach ($params as $key => $value) {
130 12
        if (gettype($value) == 'array') { //Handle array data properly
131
            foreach ($value as $val) {
132
                $params_arr[] = $key . '[]=' . urlencode($val);
133
            }
134
        } else {
135 12
            $params_arr[] = $key . '=' . urlencode($value);
136
        }
137 12
    }
138 12
    $link .= implode('&', $params_arr);
139
140 12
    return $link;
141
}
142
143
144
/**
145
 * Returns add listing page link.
146
 *
147
 * @since 1.0.0
148
 * @package GeoDirectory
149
 * @global object $wpdb WordPress Database object.
150
 * @param string $post_type The post type.
151
 * @return string Listing page url if valid. Otherwise home url will be returned.
152
 */
153
function geodir_get_addlisting_link($post_type = '')
154
{
155 3
    global $wpdb;
156
157
    //$check_pkg  = $wpdb->get_var("SELECT pid FROM ".GEODIR_PRICE_TABLE." WHERE post_type='".$post_type."' and status != '0'");
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
158 3
    $check_pkg = 1;
159 3
    if (post_type_exists($post_type) && $check_pkg) {
160
161 3
        $add_listing_link = get_page_link(geodir_add_listing_page_id());
162
163 3
        return esc_url( add_query_arg(array('listing_type' => $post_type), $add_listing_link) );
164
    } else
165
        return get_bloginfo('url');
166
}
167
168
/**
169
 * Get the current page URL.
170
 *
171
 * @since 1.0.0
172
 * @package GeoDirectory
173
 * @since 1.4.2 Removed the port number from the URL if port 80 is not being used.
174
 * @return string The current URL.
175
 */
176
function geodir_curPageURL()
177
{
178 4
    $pageURL = 'http';
179 4
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
180
        $pageURL .= "s";
181
    }
182 4
    $pageURL .= "://";
183 4
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
184
    /**
185
     * Filter the current page URL returned by function geodir_curPageURL().
186
     *
187
     * @since 1.4.1
188
     * @param string $pageURL The URL of the current page.
189
     */
190 4
    return apply_filters('geodir_curPageURL', $pageURL);
191
}
192
193
194
/**
195
 * Clean variables.
196
 *
197
 * This function is used to create posttype, posts, taxonomy and terms slug.
198
 *
199
 * @since 1.0.0
200
 * @package GeoDirectory
201
 * @param string $string The variable to clean.
202
 * @return string Cleaned variable.
203
 */
204
function geodir_clean($string)
205
{
206
207
    $string = trim(strip_tags(stripslashes($string)));
208
    $string = str_replace(" ", "-", $string); // Replaces all spaces with hyphens.
209
    $string = preg_replace('/[^A-Za-z0-9\-\_]/', '', $string); // Removes special chars.
210
    $string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
211
212
    return $string;
213
}
214
215
/**
216
 * Get Week Days list.
217
 *
218
 * @since 1.0.0
219
 * @package GeoDirectory
220
 * @return array Week days.
221
 */
222
function geodir_get_weekday()
223
{
224
    return array(__('Sunday', 'geodirectory'), __('Monday', 'geodirectory'), __('Tuesday', 'geodirectory'), __('Wednesday', 'geodirectory'), __('Thursday', 'geodirectory'), __('Friday', 'geodirectory'), __('Saturday', 'geodirectory'));
225
}
226
227
/**
228
 * Get Weeks lists.
229
 *
230
 * @since 1.0.0
231
 * @package GeoDirectory
232
 * @return array Weeks.
233
 */
234
function geodir_get_weeks()
235
{
236
    return array(__('First', 'geodirectory'), __('Second', 'geodirectory'), __('Third', 'geodirectory'), __('Fourth', 'geodirectory'), __('Last', 'geodirectory'));
237
}
238
239
240
/**
241
 * Check that page is.
242
 *
243
 * @since 1.0.0
244
 * @since 1.5.6 Added to check GD invoices and GD checkout pages.
245
 * @since 1.5.7 Updated to validate buddypress dashboard listings page as a author page.
246
 * @package GeoDirectory
247
 * @global object $wp_query WordPress Query object.
248
 * @global object $post The current post object.
249
 * @param string $gdpage The page type.
250
 * @return bool If valid returns true. Otherwise false.
251
 */
252
function geodir_is_page($gdpage = '')
253
{
254
255 22
    global $wp_query, $post,$wp;
256
    //if(!is_admin()):
0 ignored issues
show
Unused Code Comprehensibility introduced by
88% 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...
257
258
    switch ($gdpage):
259 22
        case 'add-listing':
260
261 20
            if (is_page() && get_query_var('page_id') == geodir_add_listing_page_id()) {
262
                return true;
263 20
            } elseif (is_page() && isset($post->post_content) && has_shortcode($post->post_content, 'gd_add_listing')) {
264
                return true;
265
            }
266
267 20
            break;
268 21
        case 'preview':
269 17
            if ((is_page() && get_query_var('page_id') == geodir_preview_page_id()) && isset($_REQUEST['listing_type'])
270 17
                && in_array($_REQUEST['listing_type'], geodir_get_posttypes())
271
            )
272 17
                return true;
273 17
            break;
274 21
        case 'listing-success':
275 2
            if (is_page() && get_query_var('page_id') == geodir_success_page_id())
276 2
                return true;
277 2
            break;
278 21 View Code Duplication
        case 'detail':
279 5
            $post_type = get_query_var('post_type');
280 5
            if(is_array($post_type)){$post_type = reset($post_type);}
281 5
            if (is_single() && in_array($post_type, geodir_get_posttypes()))
282 5
                return true;
283 3
            break;
284 20 View Code Duplication
        case 'pt':
285 2
            $post_type = get_query_var('post_type');
286 2
            if(is_array($post_type)){$post_type = reset($post_type);}
287 2
            if (is_post_type_archive() && in_array($post_type , geodir_get_posttypes()) && !is_tax())
288 2
                return true;
289
290 2
            break;
291 20
        case 'listing':
292 7
            if (is_tax() && geodir_get_taxonomy_posttype()) {
293
                global $current_term, $taxonomy, $term;
294
295
                return true;
296
            }
297 7
            $post_type = get_query_var('post_type');
298 7
            if(is_array($post_type)){$post_type = reset($post_type);}
299 7
            if (is_post_type_archive() && in_array($post_type, geodir_get_posttypes()))
300 7
                return true;
301
302 7
            break;
303 19
        case 'home':
304
305 3
            if ((is_page() && get_query_var('page_id') == geodir_home_page_id()) || is_page_geodir_home())
306 3
                return true;
307
308 4
            break;
309 19
        case 'location':
310 2
            if (is_page() && get_query_var('page_id') == geodir_location_page_id())
311 2
                return true;
312 2
            break;
313 19
        case 'author':
314 19
            if (is_author() && isset($_REQUEST['geodir_dashbord']))
315 19
                return true;
316
			
317 19
			if (function_exists('bp_loggedin_user_id') && function_exists('bp_displayed_user_id') && $my_id = (int)bp_loggedin_user_id()) {
318
				if (((bool)bp_is_current_component('listings') || (bool)bp_is_current_component('favorites')) && $my_id > 0 && $my_id == (int)bp_displayed_user_id()) {
319
					return true;
320
				}
321
			}
322 19
            break;
323 19
        case 'search':
324 19
            if (is_search() && isset($_REQUEST['geodir_search']))
325 19
                return true;
326 19
            break;
327 4
        case 'info':
328
            if (is_page() && get_query_var('page_id') == geodir_info_page_id())
329
                return true;
330
            break;
331 4
        case 'login':
332 4
            if (is_page() && get_query_var('page_id') == geodir_login_page_id())
333 4
                return true;
334 4
            break;
335 2
        case 'checkout':
336 View Code Duplication
            if (is_page() && function_exists('geodir_payment_checkout_page_id') && get_query_var('page_id') == geodir_payment_checkout_page_id())
337
                return true;
338
            break;
339 2
        case 'invoices':
340 View Code Duplication
            if (is_page() && function_exists('geodir_payment_invoices_page_id') && get_query_var('page_id') == geodir_payment_invoices_page_id())
341
                return true;
342
            break;
343 2
        default:
344 2
            return false;
345
            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...
346
347 2
    endswitch;
348
349
    //endif;
350
351 22
    return false;
352
}
353
354
/**
355
 * Sets a key and value in $wp object if the current page is a geodir page.
356
 *
357
 * @since 1.0.0
358
 * @since 1.5.4 Added check for new style GD homepage.
359
 * @since 1.5.6 Added check for GD invoices and GD checkout page.
360
 * @package GeoDirectory
361
 * @param object $wp WordPress object.
362
 */
363
function geodir_set_is_geodir_page($wp)
364
{
365
    if (!is_admin()) {
366
        //$wp->query_vars['gd_is_geodir_page'] = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
367
        //print_r()
368
        if (empty($wp->query_vars) || !array_diff(array_keys($wp->query_vars), array('preview', 'page', 'paged', 'cpage'))) {
369
            if (get_option('geodir_set_as_home'))
370
                $wp->query_vars['gd_is_geodir_page'] = true;
371
            if(geodir_is_page('home')){
372
                $wp->query_vars['gd_is_geodir_page'] = true;
373
            }
374
375
376
        }
377
378
        if (!isset($wp->query_vars['gd_is_geodir_page']) && isset($wp->query_vars['page_id'])) {
379
            if (
380
                $wp->query_vars['page_id'] == geodir_add_listing_page_id()
381
                || $wp->query_vars['page_id'] == geodir_preview_page_id()
382
                || $wp->query_vars['page_id'] == geodir_success_page_id()
383
                || $wp->query_vars['page_id'] == geodir_location_page_id()
384
                || $wp->query_vars['page_id'] == geodir_home_page_id()
385
                || $wp->query_vars['page_id'] == geodir_info_page_id()
386
                || $wp->query_vars['page_id'] == geodir_login_page_id()
387
                || (function_exists('geodir_payment_checkout_page_id') && $wp->query_vars['page_id'] == geodir_payment_checkout_page_id())
388
                || (function_exists('geodir_payment_invoices_page_id') && $wp->query_vars['page_id'] == geodir_payment_invoices_page_id())
389
            )
390
                $wp->query_vars['gd_is_geodir_page'] = true;
391
        }
392
393
        if (!isset($wp->query_vars['gd_is_geodir_page']) && isset($wp->query_vars['pagename'])) {
394
            $page = get_page_by_path($wp->query_vars['pagename']);
395
396
            if (!empty($page) && (
397
                    $page->ID == geodir_add_listing_page_id()
398
                    || $page->ID == geodir_preview_page_id()
399
                    || $page->ID == geodir_success_page_id()
400
                    || $page->ID == geodir_location_page_id()
401
                    || (isset($wp->query_vars['page_id']) && $wp->query_vars['page_id'] == geodir_home_page_id())
402
                    || (isset($wp->query_vars['page_id']) && $wp->query_vars['page_id'] == geodir_info_page_id())
403
                    || (isset($wp->query_vars['page_id']) && $wp->query_vars['page_id'] == geodir_login_page_id())
404
                    || (isset($wp->query_vars['page_id']) && function_exists('geodir_payment_checkout_page_id') && $wp->query_vars['page_id'] == geodir_payment_checkout_page_id())
405
                    || (isset($wp->query_vars['page_id']) && function_exists('geodir_payment_invoices_page_id') && $wp->query_vars['page_id'] == geodir_payment_invoices_page_id())
406
                )
407
            )
408
                $wp->query_vars['gd_is_geodir_page'] = true;
409
        }
410
411
412
        if (!isset($wp->query_vars['gd_is_geodir_page']) && isset($wp->query_vars['post_type']) && $wp->query_vars['post_type'] != '') {
413
            $requested_post_type = $wp->query_vars['post_type'];
414
            // check if this post type is geodirectory post types 
415
            $post_type_array = geodir_get_posttypes();
416
            if (in_array($requested_post_type, $post_type_array)) {
417
                $wp->query_vars['gd_is_geodir_page'] = true;
418
            }
419
        }
420
421
        if (!isset($wp->query_vars['gd_is_geodir_page'])) {
422
            $geodir_taxonomis = geodir_get_taxonomies('', true);
423
            if(!empty($geodir_taxonomis)){
424
                foreach ($geodir_taxonomis as $taxonomy) {
0 ignored issues
show
Bug introduced by
The expression $geodir_taxonomis 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...
425
                    if (array_key_exists($taxonomy, $wp->query_vars)) {
426
                        $wp->query_vars['gd_is_geodir_page'] = true;
427
                        break;
428
                    }
429
                }
430
            }
431
432
        }
433
434
        if (!isset($wp->query_vars['gd_is_geodir_page']) && isset($wp->query_vars['author_name']) && isset($_REQUEST['geodir_dashbord']))
435
            $wp->query_vars['gd_is_geodir_page'] = true;
436
437
438
        if (!isset($wp->query_vars['gd_is_geodir_page']) && isset($_REQUEST['geodir_search']))
439
            $wp->query_vars['gd_is_geodir_page'] = true;
440
441
442
//check if homepage
443
        if(!isset($wp->query_vars['gd_is_geodir_page'])
444
            && !isset($wp->query_vars['page_id'])
445
            && !isset($wp->query_vars['pagename'])
446
            && is_page_geodir_home()){
447
            $wp->query_vars['gd_is_geodir_page'] = true;
448
        }
449
        //echo $wp->query_vars['gd_is_geodir_page'] ;
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
450
        /*echo "<pre>" ;
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
451
		print_r($wp) ;
452
		echo "</pre>" ;
453
	//	exit();
454
			*/
455
    } // end of is admin
456
}
457
458
/**
459
 * Checks whether the current page is a GD page or not.
460
 *
461
 * @since 1.0.0
462
 * @package GeoDirectory
463
 * @global object $wp WordPress object.
464
 * @return bool If the page is GD page returns true. Otherwise false.
465
 */
466
function geodir_is_geodir_page()
467
{
468 24
    global $wp;
469 24
    if (isset($wp->query_vars['gd_is_geodir_page']) && $wp->query_vars['gd_is_geodir_page'])
470 24
        return true;
471
    else
472 24
        return false;
473
}
474
475
if (!function_exists('geodir_get_imagesize')) {
476
    /**
477
     * Get image size using the size key .
478
     *
479
     * @since 1.0.0
480
     * @package GeoDirectory
481
     * @param string $size The image size key.
482
     * @return array|mixed|void|WP_Error If valid returns image size. Else returns error.
483
     */
484
    function geodir_get_imagesize($size = '')
485
    {
486
487 8
        $imagesizes = array('list-thumb' => array('w' => 283, 'h' => 188),
488 8
            'thumbnail' => array('w' => 125, 'h' => 125),
489 8
            'widget-thumb' => array('w' => 50, 'h' => 50),
490 8
            'slider-thumb' => array('w' => 100, 'h' => 100)
491 8
        );
492
493
        /**
494
         * Filter the image sizes array.
495
         *
496
         * @since 1.0.0
497
         * @param array $imagesizes Image size array.
498
         */
499 8
        $imagesizes = apply_filters('geodir_imagesizes', $imagesizes);
500
501 8
        if (!empty($size) && array_key_exists($size, $imagesizes)) {
502
            /**
503
             * Filters image size of the passed key.
504
             *
505
             * @since 1.0.0
506
             * @param array $imagesizes[$size] Image size array of the passed key.
507
             */
508 8
            return apply_filters('geodir_get_imagesize_' . $size, $imagesizes[$size]);
509
510
        } elseif (!empty($size)) {
511
512
            return new WP_Error('geodir_no_imagesize', __("Given image size is not valid", 'geodirectory'));
513
514
        }
515
516
        return $imagesizes;
517
    }
518
}
519
520
/**
521
 * Get an image size
522
 *
523
 * Variable is filtered by geodir_get_image_size_{image_size}
524
 */
525
/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
526
function geodir_get_image_size( $image_size ) {
527
	$return = '';
528
	switch ($image_size) :
529
		case "list_thumbnail_size" : $return = get_option('geodirectory_list_thumbnail_size'); break;
530
	endswitch;
531
	return apply_filters( 'geodir_get_image_size_'.$image_size, $return );
532
}
533
*/
534
535
536
if (!function_exists('createRandomString')) {
537
    /**
538
     * Creates random string.
539
     *
540
     * @since 1.0.0
541
     * @package GeoDirectory
542
     * @return string Random string.
543
     */
544
    function createRandomString()
545
    {
546
        $chars = "abcdefghijkmlnopqrstuvwxyz1023456789";
547
        srand((double)microtime() * 1000000);
548
        $i = 0;
549
        $rstring = '';
550
        while ($i <= 25) {
551
            $num = rand() % 33;
552
            $tmp = substr($chars, $num, 1);
553
            $rstring = $rstring . $tmp;
554
            $i++;
555
        }
556
        return $rstring;
557
    }
558
}
559
560
if (!function_exists('geodir_getDistanceRadius')) {
561
    /**
562
     * Calculates the distance radius.
563
     *
564
     * @since 1.0.0
565
     * @package GeoDirectory
566
     * @param string $uom Measurement unit type.
567
     * @return float The mean radius.
568
     */
569
    function geodir_getDistanceRadius($uom = 'km')
570
    {
571
//	Use Haversine formula to calculate the great circle distance between two points identified by longitude and latitude
572 5
        switch (geodir_strtolower($uom)):
573 5
            case 'km'    :
574
                $earthMeanRadius = 6371.009; // km
575
                break;
576 5
            case 'm'    :
577 5
            case 'meters'    :
578
                $earthMeanRadius = 6371.009 * 1000; // km
579
                break;
580 5
            case 'miles'    :
581 5
                $earthMeanRadius = 3958.761; // miles
582 5
                break;
583
            case 'yards'    :
584
            case 'yds'    :
585
                $earthMeanRadius = 3958.761 * 1760; // yards
586
                break;
587
            case 'feet'    :
588
            case 'ft'    :
589
                $earthMeanRadius = 3958.761 * 1760 * 3; // feet
590
                break;
591
            case 'nm'    :
592
                $earthMeanRadius = 3440.069; //  miles
593
                break;
594
            default:
595
                $earthMeanRadius = 3958.761; // miles
596
                break;
597 5
        endswitch;
598 5
        return $earthMeanRadius;
599
    }
600
}
601
602
603
if (!function_exists('geodir_calculateDistanceFromLatLong')) {
604
    /**
605
     * Calculate the great circle distance between two points identified by longitude and latitude.
606
     *
607
     * @since 1.0.0
608
     * @package GeoDirectory
609
     * @param array $point1 Latitude and Longitude of point 1.
610
     * @param array $point2 Latitude and Longitude of point 2.
611
     * @param string $uom Unit of measurement.
612
     * @return float The distance.
613
     */
614
    function geodir_calculateDistanceFromLatLong($point1, $point2, $uom = 'km')
615
    {
616
//	Use Haversine formula to calculate the great circle distance between two points identified by longitude and latitude
617
618 5
        $earthMeanRadius = geodir_getDistanceRadius($uom);
619
620 5
        $deltaLatitude = deg2rad((float) $point2['latitude'] - (float) $point1['latitude']);
621 5
        $deltaLongitude = deg2rad((float) $point2['longitude'] - (float) $point1['longitude']);
622 5
        $a = sin($deltaLatitude / 2) * sin($deltaLatitude / 2) +
623 5
            cos(deg2rad((float) $point1['latitude'])) * cos(deg2rad((float) $point2['latitude'])) *
624 5
            sin($deltaLongitude / 2) * sin($deltaLongitude / 2);
625 5
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
626 5
        $distance = $earthMeanRadius * $c;
627 5
        return $distance;
628
629
    }
630
}
631
632
633
if (!function_exists('geodir_sendEmail')) {
634
    /**
635
     * The main function that send transactional emails using the args provided.
636
     *
637
     * @since 1.0.0
638
     * @since 1.5.7 Added db translations for notifications subject and content.
639
     * @package GeoDirectory
640
     * @param string $fromEmail Sender email address.
641
     * @param string $fromEmailName Sender name.
642
     * @param string $toEmail Receiver email address.
643
     * @param string $toEmailName Receiver name.
644
     * @param string $to_subject Email subject.
645
     * @param string $to_message Email content.
646
     * @param string $extra Not being used.
647
     * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration, post_submit, listing_published.
648
     * @param string $post_id The post ID.
649
     * @param string $user_id The user ID.
650
     */
651
    function geodir_sendEmail($fromEmail, $fromEmailName, $toEmail, $toEmailName, $to_subject, $to_message, $extra = '', $message_type, $post_id = '', $user_id = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $extra 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...
652 9
        $login_details = '';
653
654
        // strip slashes from subject & message text
655 9
        $to_subject = stripslashes_deep($to_subject);
656 9
        $to_message = stripslashes_deep($to_message);
657
658 9
        if ($message_type == 'send_friend') {
659 2
            $subject = get_option('geodir_email_friend_subject');
660 2
            $message = get_option('geodir_email_friend_content');
661 9
        } elseif ($message_type == 'send_enquiry') {
662 2
            $subject = get_option('geodir_email_enquiry_subject');
663 2
            $message = get_option('geodir_email_enquiry_content');
664 7
        } elseif ($message_type == 'forgot_password') {
665 1
            $subject = get_option('geodir_forgot_password_subject');
666 1
            $message = get_option('geodir_forgot_password_content');
667 1
            $login_details = $to_message;
668 5
        } elseif ($message_type == 'registration') {
669 2
            $subject = get_option('geodir_registration_success_email_subject');
670 2
            $message = get_option('geodir_registration_success_email_content');
671 2
            $login_details = $to_message;
672 4
        } elseif ($message_type == 'post_submit') {
673 1
            $subject = get_option('geodir_post_submited_success_email_subject');
674 1
            $message = get_option('geodir_post_submited_success_email_content');
675 2
        } elseif ($message_type == 'listing_published') {
676 1
            $subject = get_option('geodir_post_published_email_subject');
677 1
            $message = get_option('geodir_post_published_email_content');
678 1
        } elseif ($message_type == 'listing_edited') {
679
            $subject = get_option('geodir_post_edited_email_subject_admin');
680
            $message = get_option('geodir_post_edited_email_content_admin');
681
        }
682
		
683 9
		if (!empty($subject)) {
684 9
			$subject = __(stripslashes_deep($subject),'geodirectory');
685 9
		}
686
		
687 9
		if (!empty($message)) {
688 9
			$message = __(stripslashes_deep($message),'geodirectory');
689 9
		}
690
691 9
        $to_message = nl2br($to_message);
692 9
        $sitefromEmail = get_option('site_email');
693 9
        $sitefromEmailName = get_site_emailName();
694 9
        $productlink = get_permalink($post_id);
695
696 9
        $user_login = '';
697 9
        if ($user_id > 0 && $user_info = get_userdata($user_id)) {
698 1
            $user_login = $user_info->user_login;
699 1
        }
700
701 9
        $posted_date = '';
702 9
        $listingLink = '';
703
704 9
        $post_info = get_post($post_id);
705
706 9
        if ($post_info) {
707 2
            $posted_date = $post_info->post_date;
708 2
            $listingLink = '<a href="' . $productlink . '"><b>' . $post_info->post_title . '</b></a>';
709 2
        }
710 9
        $siteurl = home_url();
711 9
        $siteurl_link = '<a href="' . $siteurl . '">' . $siteurl . '</a>';
712 9
        $loginurl = geodir_login_url();
713 9
        $loginurl_link = '<a href="' . $loginurl . '">login</a>';
714
        
715 9
        $post_author_id = !empty($post_info) ? $post_info->post_author : 0;
716 9
        $post_author_name = geodir_get_client_name($post_author_id);
717 9
        $current_date = date_i18n('Y-m-d H:i:s', current_time('timestamp'));
718
719 9
        if ($fromEmail == '') {
720 6
            $fromEmail = get_option('site_email');
721 6
        }
722
723 9
        if ($fromEmailName == '') {
724 6
            $fromEmailName = get_option('site_email_name');
725 6
        }
726
727 9
        $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#comments#]', '[#login_url#]', '[#login_details#]', '[#client_name#]', '[#posted_date#]','[#from_email#]','[#user_login#]','[#username#]','[#post_author_id#]','[#post_author_name#]','[#current_date#]');
728 9
        $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $to_message, $loginurl_link, $login_details, $toEmailName, $posted_date,$fromEmail, $user_login, $user_login, $post_author_id, $post_author_name, $current_date);
729 9
        $message = str_replace($search_array, $replace_array, $message);
0 ignored issues
show
Bug introduced by
The variable $message 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...
730
731 9
        $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#client_name#]', '[#posted_date#]','[#from_email#]','[#user_login#]','[#username#]','[#post_author_id#]','[#post_author_name#]','[#current_date#]');
732 9
        $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $toEmailName, $posted_date,$fromEmail, $user_login, $user_login, $post_author_id, $post_author_name, $current_date);
733 9
        $subject = str_replace($search_array, $replace_array, $subject);
0 ignored issues
show
Bug introduced by
The variable $subject 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...
734
735 9
        $headers = 'MIME-Version: 1.0' . "\r\n";
736 9
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
737 9
        $headers .= "Reply-To: " . $fromEmail . "\r\n";
738 9
        $headers .= 'From: ' . $sitefromEmailName . ' <' . $sitefromEmail . '>' . "\r\n";
739
740 9
        $to = $toEmail;
741 9
        $sent = wp_mail($to, $subject, $message, $headers);
742
743 9
        if( ! $sent ) {
744
            if ( is_array( $to ) ) {
745
                $to = implode( ',', $to );
746
            }
747
            $log_message = sprintf(
748
                __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
749
                $message_type,
750
                date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
751
                $to,
752
                $subject
753
            );
754
            geodir_error_log( $log_message );
755
        }
756
757
        ///////// ADMIN BCC EMIALS
758 9
        $adminEmail = get_bloginfo('admin_email');
759 9
        $to = $adminEmail;
760
761 9
        $admin_bcc = false;
762 9
        if ($message_type == 'post_submit') {
763 1
            $subject = __(stripslashes_deep(get_option('geodir_post_submited_success_email_subject_admin')), 'geodirectory');
764 1
            $message = __(stripslashes_deep(get_option('geodir_post_submited_success_email_content_admin')), 'geodirectory');
765
766 1
            $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#comments#]', '[#login_url#]', '[#login_details#]', '[#client_name#]', '[#posted_date#]','[#user_login#]','[#username#]');
767 1
            $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $to_message, $loginurl_link, $login_details, $toEmailName, $posted_date, $user_login, $user_login);
768 1
            $message = str_replace($search_array, $replace_array, $message);
769
770 1
            $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#client_name#]', '[#posted_date#]','[#user_login#]','[#username#]');
771 1
            $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $toEmailName, $posted_date, $user_login, $user_login);
772 1
            $subject = str_replace($search_array, $replace_array, $subject);
773
774 1
            $subject .= ' - ADMIN BCC COPY';
775 1
            $admin_bcc = true;
776
777 1
        }
778 8
        elseif ($message_type == 'registration' && get_option('geodir_bcc_new_user')) {
779 2
            $subject .= ' - ADMIN BCC COPY';
780 2
            $admin_bcc = true;
781 2
        }
782 6
        elseif ($message_type == 'send_friend' && get_option('geodir_bcc_friend')) {
783 2
            $subject .= ' - ADMIN BCC COPY';
784 2
            $admin_bcc = true;
785 2
        }
786 4
        elseif ($message_type == 'send_enquiry' && get_option('geodir_bcc_enquiry')) {
787 2
            $subject .= ' - ADMIN BCC COPY';
788 2
            $admin_bcc = true;
789 2
        }
790 2
        elseif ($message_type == 'listing_published' && get_option('geodir_bcc_listing_published')) {
791 1
            $subject .= ' - ADMIN BCC COPY';
792 1
            $admin_bcc = true;
793 1
        }
794
795 9 View Code Duplication
        if($admin_bcc===true){
796 8
            $sent = wp_mail($to, $subject, $message, $headers);
797
798 8
            if( ! $sent ) {
799
                if ( is_array( $to ) ) {
800
                    $to = implode( ',', $to );
801
                }
802
                $log_message = sprintf(
803
                    __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
804
                    $message_type,
805
                    date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
806
                    $to,
807
                    $subject
808
                );
809
                geodir_error_log( $log_message );
810
            }
811 8
        }
812
813 9
    }
814
}
815
816
817
/**
818
 * Generates breadcrumb for taxonomy (category, tags etc.) pages.
819
 *
820
 * @since 1.0.0
821
 * @package GeoDirectory
822
 */
823
function geodir_taxonomy_breadcrumb()
824
{
825
826
    $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
827
    $parent = $term->parent;
828
829
    while ($parent):
830
        $parents[] = $parent;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$parents was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parents = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
831
        $new_parent = get_term_by('id', $parent, get_query_var('taxonomy'));
832
        $parent = $new_parent->parent;
833
    endwhile;
834
835
    if (!empty($parents)):
836
        $parents = array_reverse($parents);
837
838
        foreach ($parents as $parent):
839
            $item = get_term_by('id', $parent, get_query_var('taxonomy'));
840
            $url = get_term_link($item, get_query_var('taxonomy'));
841
            echo '<li> > <a href="' . $url . '">' . $item->name . '</a></li>';
842
        endforeach;
843
844
    endif;
845
846
    echo '<li> > ' . $term->name . '</li>';
847
}
848
849
850
/**
851
 * Main function that generates breadcrumb for all pages.
852
 *
853
 * @since 1.0.0
854
 * @since 1.5.7 Changes for the neighbourhood system improvement.
855
 * @package GeoDirectory
856
 * @global object $wp_query WordPress Query object.
857
 * @global object $post The current post object.
858
 * @global object $gd_session GeoDirectory Session object.
859
 */
860
function geodir_breadcrumb()
861
{
862 2
    global $wp_query, $geodir_add_location_url;
863
864
    /**
865
     * Filter breadcrumb separator.
866
     *
867
     * @since 1.0.0
868
     */
869 2
    $separator = apply_filters('geodir_breadcrumb_separator', ' > ');
870
871 2
    if (!geodir_is_page('home')) {
872 2
        $breadcrumb = '';
873 2
        $url_categoris = '';
0 ignored issues
show
Unused Code introduced by
$url_categoris 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...
874 2
        $breadcrumb .= '<div class="geodir-breadcrumb clearfix"><ul id="breadcrumbs">';
875
        /**
876
         * Filter breadcrumb's first link.
877
         *
878
         * @since 1.0.0
879
         */
880 2
        $breadcrumb .= '<li>' . apply_filters('geodir_breadcrumb_first_link', '<a href="' . home_url() . '">' . __('Home', 'geodirectory') . '</a>') . '</li>';
881
882 2
        $gd_post_type = geodir_get_current_posttype();
883 2
        $post_type_info = get_post_type_object($gd_post_type);
884
885 2
        remove_filter('post_type_archive_link', 'geodir_get_posttype_link');
886
887 2
        $listing_link = get_post_type_archive_link($gd_post_type);
888
889 2
        add_filter('post_type_archive_link', 'geodir_get_posttype_link', 10, 2);
890 2
        $listing_link = rtrim($listing_link, '/');
891 2
        $listing_link .= '/';
892
893 2
        $post_type_for_location_link = $listing_link;
894 2
        $location_terms = geodir_get_current_location_terms('query_vars', $gd_post_type);
895
896 2
        global $wp, $gd_session;
897 2
        $location_link = $post_type_for_location_link;
898
899 2
        if (geodir_is_page('detail') || geodir_is_page('listing')) {
900 2
            global $post;
901 2
            $location_manager = defined('POST_LOCATION_TABLE') ? true : false;
902 2
			$neighbourhood_active = $location_manager && get_option('location_neighbourhoods') ? true : false;
903
				
904 2 View Code Duplication
			if(geodir_is_page('detail') && isset($post->country_slug)){
905
                $location_terms = array(
906
                    'gd_country' => $post->country_slug,
907
                    'gd_region' => $post->region_slug,
908
                    'gd_city' => $post->city_slug
909
                );
910
				
911
				if ($neighbourhood_active && !empty($location_terms['gd_city']) && $gd_ses_neighbourhood = $gd_session->get('gd_neighbourhood')) {
912
					$location_terms['gd_neighbourhood'] = $gd_ses_neighbourhood;
913
				}
914
            }
915
916 2
            $geodir_show_location_url = get_option('geodir_show_location_url');
917
918 2
            $hide_url_part = array();
919 2
            if ($location_manager) {
920
                $hide_country_part = get_option('geodir_location_hide_country_part');
921
                $hide_region_part = get_option('geodir_location_hide_region_part');
922
923
                if ($hide_region_part && $hide_country_part) {
924
                    $hide_url_part = array('gd_country', 'gd_region');
925
                } else if ($hide_region_part && !$hide_country_part) {
926
                    $hide_url_part = array('gd_region');
927
                } else if (!$hide_region_part && $hide_country_part) {
928
                    $hide_url_part = array('gd_country');
929
                }
930
            }
931
932 2
            $hide_text_part = array();
0 ignored issues
show
Unused Code introduced by
$hide_text_part 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...
933 2
            if ($geodir_show_location_url == 'country_city') {
934
                $hide_text_part = array('gd_region');
0 ignored issues
show
Unused Code introduced by
$hide_text_part 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...
935
936
                if (isset($location_terms['gd_region']) && !$location_manager) {
937
                    unset($location_terms['gd_region']);
938
                }
939 2
            } else if ($geodir_show_location_url == 'region_city') {
940
                $hide_text_part = array('gd_country');
0 ignored issues
show
Unused Code introduced by
$hide_text_part 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...
941
942
                if (isset($location_terms['gd_country']) && !$location_manager) {
943
                    unset($location_terms['gd_country']);
944
                }
945 2
            } else if ($geodir_show_location_url == 'city') {
946
                $hide_text_part = array('gd_country', 'gd_region');
0 ignored issues
show
Unused Code introduced by
$hide_text_part 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...
947
948
                if (isset($location_terms['gd_country']) && !$location_manager) {
949
                    unset($location_terms['gd_country']);
950
                }
951
                if (isset($location_terms['gd_region']) && !$location_manager) {
952
                    unset($location_terms['gd_region']);
953
                }
954
            }
955
956 2
            $is_location_last = '';
0 ignored issues
show
Unused Code introduced by
$is_location_last 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...
957 2
            $is_taxonomy_last = '';
0 ignored issues
show
Unused Code introduced by
$is_taxonomy_last 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...
958 2
            $breadcrumb .= '<li>';
959 2
            if (get_query_var($gd_post_type . 'category'))
960 2
                $gd_taxonomy = $gd_post_type . 'category';
961 2
            elseif (get_query_var($gd_post_type . '_tags'))
962
                $gd_taxonomy = $gd_post_type . '_tags';
963
964 2
            $breadcrumb .= $separator . '<a href="' . $listing_link . '">' . __(ucfirst($post_type_info->label), 'geodirectory') . '</a>';
965 2
            if (!empty($gd_taxonomy) || geodir_is_page('detail'))
966 2
                $is_location_last = false;
967
            else
968 1
                $is_location_last = true;
969
970 2
            if (!empty($gd_taxonomy) && geodir_is_page('listing'))
971 2
                $is_taxonomy_last = true;
972
            else
973 2
                $is_taxonomy_last = false;
974
975 2
            if (!empty($location_terms)) {
976
                $geodir_get_locations = function_exists('get_actual_location_name') ? true : false;
977
978
                foreach ($location_terms as $key => $location_term) {
979
                    if ($location_term != '') {
980
                        if (!empty($hide_url_part) && in_array($key, $hide_url_part)) { // Hide location part from url & breadcrumb.
981
                            continue;
982
                        }
983
984
                        $gd_location_link_text = preg_replace('/-(\d+)$/', '', $location_term);
985
                        $gd_location_link_text = preg_replace('/[_-]/', ' ', $gd_location_link_text);
986
                        $gd_location_link_text = ucfirst($gd_location_link_text);
987
988
                        $location_term_actual_country = '';
989
                        $location_term_actual_region = '';
990
                        $location_term_actual_city = '';
991
                        if ($geodir_get_locations) {
992
                            if ($key == 'gd_country') {
993
                                $location_term_actual_country = get_actual_location_name('country', $location_term, true);
994
                            } else if ($key == 'gd_region') {
995
                                $location_term_actual_region = get_actual_location_name('region', $location_term, true);
996
                            } else if ($key == 'gd_city') {
997
                                $location_term_actual_city = get_actual_location_name('city', $location_term, true);
998
                            }
999
                        } else {
1000
                            $location_info = geodir_get_location();
1001
1002
                            if (!empty($location_info) && isset($location_info->location_id)) {
1003
                                if ($key == 'gd_country') {
1004
                                    $location_term_actual_country = __($location_info->country, 'geodirectory');
1005
                                } else if ($key == 'gd_region') {
1006
                                    $location_term_actual_region = __($location_info->region, 'geodirectory');
1007
                                } else if ($key == 'gd_city') {
1008
                                    $location_term_actual_city = __($location_info->city, 'geodirectory');
1009
                                }
1010
                            }
1011
                        }
1012
1013
                        if ($is_location_last && $key == 'gd_country' && !(isset($location_terms['gd_region']) && $location_terms['gd_region'] != '') && !(isset($location_terms['gd_city']) && $location_terms['gd_city'] != '')) {
1014
                            $breadcrumb .= $location_term_actual_country != '' ? $separator . $location_term_actual_country : $separator . $gd_location_link_text;
1015
                        } else if ($is_location_last && $key == 'gd_region' && !(isset($location_terms['gd_city']) && $location_terms['gd_city'] != '')) {
1016
                            $breadcrumb .= $location_term_actual_region != '' ? $separator . $location_term_actual_region : $separator . $gd_location_link_text;
1017
                        } else if ($is_location_last && $key == 'gd_city' && empty($location_terms['gd_neighbourhood'])) {
1018
                            $breadcrumb .= $location_term_actual_city != '' ? $separator . $location_term_actual_city : $separator . $gd_location_link_text;
1019
                        } else if ($is_location_last && $key == 'gd_neighbourhood') {
1020
                            $breadcrumb .= $separator . $gd_location_link_text;
1021
                        } else {
1022
                            if (get_option('permalink_structure') != '') {
1023
                                $location_link .= $location_term . '/';
1024
                            } else {
1025
                                $location_link .= "&$key=" . $location_term;
1026
                            }
1027
1028
                            if ($key == 'gd_country' && $location_term_actual_country != '') {
1029
                                $gd_location_link_text = $location_term_actual_country;
1030
                            } else if ($key == 'gd_region' && $location_term_actual_region != '') {
1031
                                $gd_location_link_text = $location_term_actual_region;
1032
                            } else if ($key == 'gd_city' && $location_term_actual_city != '') {
1033
                                $gd_location_link_text = $location_term_actual_city;
1034
                            }
1035
1036
                            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
1037
                            if (geodir_is_page('detail') && !empty($hide_text_part) && in_array($key, $hide_text_part)) {
1038
                                continue;
1039
                            }
1040
                            */
1041
1042
                            $breadcrumb .= $separator . '<a href="' . $location_link . '">' . $gd_location_link_text . '</a>';
1043
                        }
1044
                    }
1045
                }
1046
            }
1047
1048 2
            if (!empty($gd_taxonomy)) {
1049
                $term_index = 1;
1050
1051
                //if(get_option('geodir_add_categories_url'))
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
1052
                {
1053
                    if (get_query_var($gd_post_type . '_tags')) {
1054
                        $cat_link = $listing_link . 'tags/';
1055
                    } else
1056
                        $cat_link = $listing_link;
1057
1058
                    foreach ($location_terms as $key => $location_term) {
1059
                        if ($location_manager && in_array($key, $hide_url_part)) {
1060
                            continue;
1061
                        }
1062
1063
                        if ($location_term != '') {
1064
                            if (get_option('permalink_structure') != '') {
1065
                                $cat_link .= $location_term . '/';
1066
                            }
1067
                        }
1068
                    }
1069
1070
                    $term_array = explode("/", trim($wp_query->query[$gd_taxonomy], "/"));
1071
                    foreach ($term_array as $term) {
1072
                        $term_link_text = preg_replace('/-(\d+)$/', '', $term);
1073
                        $term_link_text = preg_replace('/[_-]/', ' ', $term_link_text);
1074
1075
                        // get term actual name
1076
                        $term_info = get_term_by('slug', $term, $gd_taxonomy, 'ARRAY_A');
1077
                        if (!empty($term_info) && isset($term_info['name']) && $term_info['name'] != '') {
1078
                            $term_link_text = urldecode($term_info['name']);
1079
                        } else {
1080
                            $term_link_text = geodir_ucwords(urldecode($term_link_text));
1081
                        }
1082
1083
                        if ($term_index == count($term_array) && $is_taxonomy_last)
1084
                            $breadcrumb .= $separator . $term_link_text;
1085
                        else {
1086
                            $cat_link .= $term . '/';
1087
                            $breadcrumb .= $separator . '<a href="' . $cat_link . '">' . $term_link_text . '</a>';
1088
                        }
1089
                        $term_index++;
1090
                    }
1091
                }
1092
1093
1094
            }
1095
1096 2
            if (geodir_is_page('detail'))
1097 2
                $breadcrumb .= $separator . get_the_title();
1098
1099 2
            $breadcrumb .= '</li>';
1100
1101
1102 2
        } elseif (geodir_is_page('author')) {
1103 1
            $user_id = get_current_user_id();
1104 1
            $author_link = get_author_posts_url($user_id);
1105 1
            $default_author_link = geodir_getlink($author_link, array('geodir_dashbord' => 'true', 'stype' => 'gd_place'), false);
1106
1107
            /**
1108
             * Filter author page link.
1109
             *
1110
             * @since 1.0.0
1111
             * @param string $default_author_link Default author link.
1112
             * @param int $user_id Author ID.
1113
             */
1114 1
            $default_author_link = apply_filters('geodir_dashboard_author_link', $default_author_link, $user_id);
1115
1116 1
            $breadcrumb .= '<li>';
1117 1
            $breadcrumb .= $separator . '<a href="' . $default_author_link . '">' . __('My Dashboard', 'geodirectory') . '</a>';
1118
1119 1
            if (isset($_REQUEST['list'])) {
1120
                $author_link = geodir_getlink($author_link, array('geodir_dashbord' => 'true', 'stype' => $_REQUEST['stype']), false);
1121
1122
                /**
1123
                 * Filter author page link.
1124
                 *
1125
                 * @since 1.0.0
1126
                 * @param string $author_link Author page link.
1127
                 * @param int $user_id Author ID.
1128
                 * @param string $_REQUEST['stype'] Post type.
1129
                 */
1130
                $author_link = apply_filters('geodir_dashboard_author_link', $author_link, $user_id, $_REQUEST['stype']);
1131
1132
                $breadcrumb .= $separator . '<a href="' . $author_link . '">' . __(ucfirst($post_type_info->label), 'geodirectory') . '</a>';
1133
                $breadcrumb .= $separator . ucfirst(__('My', 'geodirectory') . ' ' . $_REQUEST['list']);
1134
            } else
1135 1
                $breadcrumb .= $separator . __(ucfirst($post_type_info->label), 'geodirectory');
1136
1137 1
            $breadcrumb .= '</li>';
1138 1
        } elseif (is_category() || is_single()) {
1139
            $category = get_the_category();
1140
            if (is_category()) {
1141
                $breadcrumb .= '<li>' . $separator . $category[0]->cat_name . '</li>';
1142
            }
1143
            if (is_single()) {
1144
                $breadcrumb .= '<li>' . $separator . '<a href="' . get_category_link($category[0]->term_id) . '">' . $category[0]->cat_name . '</a></li>';
1145
                $breadcrumb .= '<li>' . $separator . get_the_title() . '</li>';
1146
            }
1147
            /* End of my version ##################################################### */
1148
        } else if (is_page()) {
1149
            $page_title = get_the_title();
1150
1151
            if (geodir_is_page('location')) {
1152
                $page_title = defined('GD_LOCATION') ? GD_LOCATION : __('Location', 'geodirectory');
1153
            }
1154
1155
            $breadcrumb .= '<li>' . $separator;
1156
            $breadcrumb .= stripslashes_deep($page_title);
1157
            $breadcrumb .= '</li>';
1158
        } else if (is_tag()) {
1159
            $breadcrumb .=  "<li> " . $separator . single_tag_title('',false) . '</li>';
1160
        } else if (is_day()) {
1161
            $breadcrumb .= "<li> " . $separator . __(" Archive for", 'geodirectory') . " ";
1162
            the_time('F jS, Y');
1163
            $breadcrumb .= '</li>';
1164
        } else if (is_month()) {
1165
            $breadcrumb .= "<li> " . $separator . __(" Archive for", 'geodirectory') . " ";
1166
            the_time('F, Y');
1167
            $breadcrumb .= '</li>';
1168
        } else if (is_year()) {
1169
            $breadcrumb .= "<li> " . $separator . __(" Archive for", 'geodirectory') . " ";
1170
            the_time('Y');
1171
            $breadcrumb .= '</li>';
1172
        } else if (is_author()) {
1173
            $breadcrumb .= "<li> " . $separator . __(" Author Archive", 'geodirectory');
1174
            $breadcrumb .= '</li>';
1175
        } else if (isset($_GET['paged']) && !empty($_GET['paged'])) {
1176
            $breadcrumb .= "<li>" . $separator . __("Blog Archives", 'geodirectory');
1177
            $breadcrumb .= '</li>';
1178
        } else if (is_search()) {
1179
            $breadcrumb .= "<li> " . $separator . __(" Search Results", 'geodirectory');
1180
            $breadcrumb .= '</li>';
1181
        }
1182 2
        $breadcrumb .= '</ul></div>';
1183
1184
        /**
1185
         * Filter breadcrumb html output.
1186
         *
1187
         * @since 1.0.0
1188
         * @param string $breadcrumb Breadcrumb HTML.
1189
         * @param string $separator Breadcrumb separator.
1190
         */
1191 2
        echo $breadcrumb = apply_filters('geodir_breadcrumb', $breadcrumb, $separator);
1192 2
    }
1193 2
}
1194
1195
1196
add_action("admin_init", "geodir_allow_wpadmin"); // check user is admin
1197
if (!function_exists('geodir_allow_wpadmin')) {
1198
    /**
1199
     * Allow only admins to access wp-admin.
1200
     *
1201
     * Normal users will be redirected to home page.
1202
     *
1203
     * @since 1.0.0
1204
     * @package GeoDirectory
1205
     * @global object $wpdb WordPress Database object.
1206
     */
1207
    function geodir_allow_wpadmin()
1208
    {
1209 1
        global $wpdb;
1210 1
        if (get_option('geodir_allow_wpadmin') == '0' && is_user_logged_in() && (!isset($_REQUEST['action']))) // checking action in request to allow ajax request go through
1211 1
        {
1212
            if (current_user_can('manage_options')) {
1213
            } else {
1214
1215
                wp_redirect(home_url());
1216
                exit;
1217
            }
1218
1219
        }
1220 1
    }
1221
}
1222
1223
1224
/**
1225
 * Move Images from a remote url to upload directory.
1226
 *
1227
 * @since 1.0.0
1228
 * @package GeoDirectory
1229
 * @param string $url The remote image url.
1230
 * @return array|WP_Error The uploaded data as array. When failure returns error.
1231
 */
1232
function fetch_remote_file($url)
1233
{
1234
    // extract the file name and extension from the url
1235 1
    require_once(ABSPATH . 'wp-includes/pluggable.php');
1236 1
    $file_name = basename($url);
1237 1
    if (strpos($file_name, '?') !== false) {
1238
        list($file_name) = explode('?', $file_name);
1239
    }
1240
1241
1242
    // get placeholder file in the upload dir with a unique, sanitized filename
1243
1244 1
    $post_upload_date = isset($post['upload_date']) ? $post['upload_date'] : '';
0 ignored issues
show
Bug introduced by
The variable $post seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1245
1246 1
    $upload = wp_upload_bits($file_name, 0, '', $post_upload_date);
1247 1
    if ($upload['error'])
1248 1
        return new WP_Error('upload_dir_error', $upload['error']);
1249
1250
    // fetch the remote url and write it to the placeholder file
1251 1
    $headers = wp_remote_get($url, array('stream' => true,'filename' => $upload['file']));
1252
1253 1
    $log_message = '';
1254 1
    $filesize = filesize($upload['file']);
1255
    // request failed
1256 1
    if (!$headers) {
1257
        $log_message = __('Remote server did not respond', 'geodirectory');
1258
    }
1259
    // make sure the fetch was successful
1260 1
    elseif ($headers['response']['code'] != '200') {
1261
        $log_message = sprintf(__('Remote server returned error response %1$d %2$s', 'geodirectory'), esc_html($headers['response']), get_status_header_desc($headers['response']));
1262
    }
1263 1
    elseif (isset($headers['headers']['content-length']) && $filesize != $headers['headers']['content-length']) {
1264
        $log_message =  __('Remote file is incorrect size', 'geodirectory');
1265
    }
1266 1
    elseif (0 == $filesize) {
1267
        $log_message = __('Zero size file downloaded', 'geodirectory');
1268
    }
1269
1270 1
    if($log_message){
1271
        $del = unlink($upload['file']);
1272
        if(!$del){geodir_error_log(__('GeoDirectory: fetch_remote_file() failed to delete temp file.', 'geodirectory'));}
1273
        return new WP_Error('import_file_error',$log_message );
1274
    }
1275
1276
1277 1
    return $upload;
1278
}
1279
1280
/**
1281
 * Get maximum file upload size.
1282
 *
1283
 * @since 1.0.0
1284
 * @package GeoDirectory
1285
 * @return string|void Max upload size.
1286
 */
1287 View Code Duplication
function geodir_max_upload_size()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Best Practice introduced by
The function geodir_max_upload_size() has been defined more than once; this definition is ignored, only the first definition in geodirectory-functions/custom_fields_functions.php (L3493-3504) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
1288
{
1289
    $max_filesize = (float)get_option('geodir_upload_max_filesize', 2);
1290
1291
    if ($max_filesize > 0 && $max_filesize < 1) {
1292
        $max_filesize = (int)($max_filesize * 1024) . 'kb';
1293
    } else {
1294
        $max_filesize = $max_filesize > 0 ? $max_filesize . 'mb' : '2mb';
1295
    }
1296
1297
    /**
1298
     * Filter default image upload size limit.
1299
     *
1300
     * @since 1.0.0
1301
     * @param string $max_filesize Max file upload size. Ex. 10mb, 512kb.
1302
     */
1303
    return apply_filters('geodir_default_image_upload_size_limit', $max_filesize);
1304
}
1305
1306
/**
1307
 * Check if dummy folder exists or not.
1308
 *
1309
 * Check if dummy folder exists or not , if not then fetch from live url.
1310
 *
1311
 * @since 1.0.0
1312
 * @package GeoDirectory
1313
 * @return bool If dummy folder exists returns true, else false.
1314
 */
1315
function geodir_dummy_folder_exists()
1316
{
1317 1
    $path = geodir_plugin_path() . '/geodirectory-admin/dummy/';
1318 1
    if (!is_dir($path))
1319 1
        return false;
1320
    else
1321
        return true;
1322
1323
}
1324
1325
/**
1326
 * Get the author info.
1327
 *
1328
 * @since 1.0.0
1329
 * @package GeoDirectory
1330
 * @global object $wpdb WordPress Database object.
1331
 * @param int $aid The author ID.
1332
 * @return object Author info.
1333
 */
1334
function  geodir_get_author_info($aid)
1335
{
1336
    global $wpdb;
1337
    /*$infosql = "select * from $wpdb->users where ID=$aid";*/
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...
1338
    $infosql = $wpdb->prepare("select * from $wpdb->users where ID=%d", array($aid));
1339
    $info = $wpdb->get_results($infosql);
1340
    if ($info) {
1341
        return $info[0];
1342
    }
1343
}
1344
1345
if (!function_exists('adminEmail')) {
1346
    /**
1347
     * Send emails to client on post submission, renew etc.
1348
     *
1349
     * @since 1.0.0
1350
     * @package GeoDirectory
1351
     * @global object $wpdb WordPress Database object.
1352
     * @param int|string $page_id Page ID.
1353
     * @param int|string $user_id User ID.
1354
     * @param string $message_type Can be 'expiration','post_submited','renew','upgrade','claim_approved','claim_rejected','claim_requested','auto_claim','payment_success','payment_fail'.
1355
     * @param string $custom_1 Custom data to be sent.
1356
     */
1357
    function adminEmail($page_id, $user_id, $message_type, $custom_1 = '')
1358
    {
1359
        global $wpdb;
1360
        if ($message_type == 'expiration') {
1361
            $subject = stripslashes(__(get_option('renew_email_subject'),'geodirectory'));
1362
            $client_message = stripslashes(__(get_option('renew_email_content'),'geodirectory'));
1363
        } elseif ($message_type == 'post_submited') {
1364
            $subject = __(get_option('post_submited_success_email_subject_admin'),'geodirectory');
1365
            $client_message = __(get_option('post_submited_success_email_content_admin'),'geodirectory');
1366
        } elseif ($message_type == 'renew') {
1367
            $subject = __(get_option('post_renew_success_email_subject_admin'),'geodirectory');
1368
            $client_message = __(get_option('post_renew_success_email_content_admin'),'geodirectory');
1369
        } elseif ($message_type == 'upgrade') {
1370
            $subject = __(get_option('post_upgrade_success_email_subject_admin'),'geodirectory');
1371
            $client_message = __(get_option('post_upgrade_success_email_content_admin'),'geodirectory');
1372
        } elseif ($message_type == 'claim_approved') {
1373
            $subject = __(get_option('claim_approved_email_subject'),'geodirectory');
1374
            $client_message = __(get_option('claim_approved_email_content'),'geodirectory');
1375
        } elseif ($message_type == 'claim_rejected') {
1376
            $subject = __(get_option('claim_rejected_email_subject'),'geodirectory');
1377
            $client_message = __(get_option('claim_rejected_email_content'),'geodirectory');
1378
        } elseif ($message_type == 'claim_requested') {
1379
            $subject = __(get_option('claim_email_subject_admin'),'geodirectory');
1380
            $client_message = __(get_option('claim_email_content_admin'),'geodirectory');
1381
        } elseif ($message_type == 'auto_claim') {
1382
            $subject = __(get_option('auto_claim_email_subject'),'geodirectory');
1383
            $client_message = __(get_option('auto_claim_email_content'),'geodirectory');
1384
        } elseif ($message_type == 'payment_success') {
1385
            $subject = __(get_option('post_payment_success_admin_email_subject'),'geodirectory');
1386
            $client_message = __(get_option('post_payment_success_admin_email_content'),'geodirectory');
1387
        } elseif ($message_type == 'payment_fail') {
1388
            $subject = __(get_option('post_payment_fail_admin_email_subject'),'geodirectory');
1389
            $client_message = __(get_option('post_payment_fail_admin_email_content'),'geodirectory');
1390
        }
1391
        $transaction_details = $custom_1;
1392
        $fromEmail = get_option('site_email');
1393
        $fromEmailName = get_site_emailName();
1394
//$alivedays = get_post_meta($page_id,'alive_days',true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
1395
        $pkg_limit = get_property_price_info_listing($page_id);
1396
        $alivedays = $pkg_limit['days'];
1397
        $productlink = get_permalink($page_id);
1398
        $post_info = get_post($page_id);
1399
        $post_date = date('dS F,Y', strtotime($post_info->post_date));
1400
        $listingLink = '<a href="' . $productlink . '"><b>' . $post_info->post_title . '</b></a>';
1401
        $loginurl = geodir_login_url();
1402
        $loginurl_link = '<a href="' . $loginurl . '">login</a>';
1403
        $siteurl = home_url();
1404
        $siteurl_link = '<a href="' . $siteurl . '">' . $fromEmailName . '</a>';
1405
        $user_info = get_userdata($user_id);
1406
        $user_email = $user_info->user_email;
1407
        $display_name = geodir_get_client_name($user_id);
1408
        $user_login = $user_info->user_login;
1409
        $number_of_grace_days = get_option('ptthemes_listing_preexpiry_notice_days');
1410
        if ($number_of_grace_days == '') {
1411
            $number_of_grace_days = 1;
1412
        }
1413
        if ($post_info->post_type == 'event') {
1414
            $post_type = 'event';
1415
        } else {
1416
            $post_type = 'listing';
1417
        }
1418
        $renew_link = '<a href="' . $siteurl . '?ptype=post_' . $post_type . '&renew=1&pid=' . $page_id . '">' . RENEW_LINK . '</a>';
1419
        $search_array = array('[#client_name#]', '[#listing_link#]', '[#posted_date#]', '[#number_of_days#]', '[#number_of_grace_days#]', '[#login_url#]', '[#username#]', '[#user_email#]', '[#site_name_url#]', '[#renew_link#]', '[#post_id#]', '[#site_name#]', '[#transaction_details#]');
1420
        $replace_array = array($display_name, $listingLink, $post_date, $alivedays, $number_of_grace_days, $loginurl_link, $user_login, $user_email, $siteurl_link, $renew_link, $page_id, $fromEmailName, $transaction_details);
1421
        $client_message = str_replace($search_array, $replace_array, $client_message);
0 ignored issues
show
Bug introduced by
The variable $client_message 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...
1422
        $subject = str_replace($search_array, $replace_array, $subject);
0 ignored issues
show
Bug introduced by
The variable $subject 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...
1423
        $headers = 'MIME-Version: 1.0' . "\r\n";
1424
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
1425
        $headers .= 'From: ' . $fromEmailName . ' <' . $fromEmail . '>' . "\r\n";
1426
1427
        $to = $fromEmail;
1428
        $message = $client_message;
1429
        $sent = wp_mail($to, $subject, $message, $headers);
1430
        if( ! $sent ) {
1431
            if ( is_array( $to ) ) {
1432
                $to = implode( ',', $to );
1433
            }
1434
            $log_message = sprintf(
1435
                __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
1436
                $message_type,
1437
                date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
1438
                $to,
1439
                $subject
1440
            );
1441
            geodir_error_log( $log_message );
1442
        }
1443
    }
1444
}
1445
1446
if (!function_exists('sendEmail')) {
1447
    /**
1448
     * @todo could be a duplicate of geodir_sendEmail.
1449
     *
1450
     * @since 1.0.0
1451
     * @package GeoDirectory
1452
     * @param string $fromEmail Sender email address.
1453
     * @param string $fromEmailName Sender name.
1454
     * @param string $toEmail Receiver email address.
1455
     * @param string $toEmailName Receiver name.
1456
     * @param string $to_subject Email subject.
1457
     * @param string $to_message Email content.
1458
     * @param string $extra Not being used.
1459
     * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration.
1460
     * @param string $post_id The post ID.
1461
     * @param string $user_id The user ID.
1462
     */
1463
    function sendEmail($fromEmail, $fromEmailName, $toEmail, $toEmailName, $to_subject, $to_message, $extra = '', $message_type, $post_id = '', $user_id = '')
0 ignored issues
show
Unused Code introduced by
The parameter $extra is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $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...
1464
    {
1465
        $login_details = '';
1466
        if ($message_type == 'send_friend') {
1467
            $subject = stripslashes(__(get_option('email_friend_subject'),'geodirectory'));
1468
            $message = stripslashes(__(get_option('email_friend_content'),'geodirectory'));
1469
        } elseif ($message_type == 'send_enquiry') {
1470
            $subject = __(get_option('email_enquiry_subject'),'geodirectory');
1471
            $message = __(get_option('email_enquiry_content'),'geodirectory');
1472
        } elseif ($message_type == 'forgot_password') {
1473
            $subject = __(get_option('forgot_password_subject'),'geodirectory');
1474
            $message = __(get_option('forgot_password_content'),'geodirectory');
1475
            $login_details = $to_message;
1476
        } elseif ($message_type == 'registration') {
1477
            $subject = __(get_option('registration_success_email_subject'),'geodirectory');
1478
            $message = __(get_option('registration_success_email_content'),'geodirectory');
1479
            $login_details = $to_message;
1480
        }
1481
        $to_message = nl2br($to_message);
1482
        $sitefromEmail = get_option('site_email');
1483
        $sitefromEmailName = get_site_emailName();
1484
        $productlink = get_permalink($post_id);
1485
        $post_info = get_post($post_id);
1486
        $listingLink = '<a href="' . $productlink . '"><b>' . $post_info->post_title . '</b></a>';
1487
        $siteurl = home_url();
1488
        $siteurl_link = '<a href="' . $siteurl . '">' . $siteurl . '</a>';
1489
        $loginurl = geodir_login_url();
1490
        $loginurl_link = '<a href="' . $loginurl . '">login</a>';
1491
        if ($fromEmail == '') {
1492
            $fromEmail = get_option('site_email');
1493
        }
1494
        if ($fromEmailName == '') {
1495
            $fromEmailName = get_option('site_email_name');
1496
        }
1497
        $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#comments#]', '[#login_url#]', '[#login_details#]', '[#client_name#]');
1498
        $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $to_message, $loginurl_link, $login_details, $toEmailName);
1499
        $message = str_replace($search_array, $replace_array, $message);
0 ignored issues
show
Bug introduced by
The variable $message 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...
1500
1501
        $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#client_name#]');
1502
        $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $toEmailName);
1503
        $subject = str_replace($search_array, $replace_array, $subject);
0 ignored issues
show
Bug introduced by
The variable $subject 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...
1504
        $headers = 'MIME-Version: 1.0' . "\r\n";
1505
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
1506
        $headers .= "Reply-To: " . $fromEmail . "\r\n";
1507
        $headers .= 'From: ' . $sitefromEmailName . ' <' . $sitefromEmail . '>' . "\r\n";
1508
1509
        $to = $toEmail;
1510
1511
        $sent = wp_mail($to, $subject, $message, $headers);
1512
        if( ! $sent ) {
1513
            if ( is_array( $to ) ) {
1514
                $to = implode( ',', $to );
1515
            }
1516
            $log_message = sprintf(
1517
                __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
1518
                $message_type,
1519
                date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
1520
                $to,
1521
                $subject
1522
            );
1523
            geodir_error_log( $log_message );
1524
        }
1525
1526
        ///////// ADMIN BCC EMIALS
1527
        $admin_bcc = false;
1528
        if ($message_type == 'registration') {
1529
            $message_raw = explode(__("Password:", 'geodirectory'), $message);
1530
            $message_raw2 = explode("</p>", $message_raw[1], 2);
1531
            $message = $message_raw[0] . __('Password:', 'geodirectory') . ' **********</p>' . $message_raw2[1];
1532
        }
1533
        $adminEmail = get_bloginfo('admin_email');
1534
        $to = $adminEmail;
1535
1536
        if ($message_type == 'registration' && get_option('bcc_new_user')) {
1537
            $subject .= ' - ADMIN BCC COPY';
1538
            $admin_bcc = true;
1539
        }
1540
        elseif ($message_type == 'send_friend' && get_option('bcc_friend')) {
1541
            $subject .= ' - ADMIN BCC COPY';
1542
            $admin_bcc = true;
1543
        }
1544
        elseif ($message_type == 'send_enquiry' && get_option('bcc_enquiry')) {
1545
            $subject .= ' - ADMIN BCC COPY';
1546
            $admin_bcc = true;
1547
        }
1548
1549 View Code Duplication
        if($admin_bcc === true){
1550
            $sent = wp_mail($to, $subject, $message, $headers);
1551
            if( ! $sent ) {
1552
                if ( is_array( $to ) ) {
1553
                    $to = implode( ',', $to );
1554
                }
1555
                $log_message = sprintf(
1556
                    __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
1557
                    $message_type,
1558
                    date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
1559
                    $to,
1560
                    $subject
1561
                );
1562
                geodir_error_log( $log_message );
1563
            }
1564
        }
1565
1566
    }
1567
}
1568
1569
/*
1570
Language translation helper functions
1571
*/
1572
1573
/**
1574
 * Function to get the translated category id's.
1575
 *
1576
 * @since 1.0.0
1577
 * @package GeoDirectory
1578
 * @param array $ids_array Category IDs.
1579
 * @param string $type Category taxonomy.
1580
 * @return array Category IDs.
1581
 */
1582
function gd_lang_object_ids($ids_array, $type)
1583
{
1584
    if (function_exists('icl_object_id')) {
1585
        $res = array();
1586
        foreach ($ids_array as $id) {
1587
            $xlat = icl_object_id($id, $type, false);
1588
            if (!is_null($xlat)) $res[] = $xlat;
1589
        }
1590
        return $res;
1591
    } else {
1592
        return $ids_array;
1593
    }
1594
}
1595
1596
1597
/**
1598
 * function to add class to body when multi post type is active.
1599
 *
1600
 * @since 1.0.0
1601
 * @since 1.5.6 Add geodir-page class to body for all gd pages.
1602
 * @package GeoDirectory
1603
 * @global object $wpdb WordPress Database object.
1604
 * @param array $classes Body CSS classes.
1605
 * @return array Modified Body CSS classes.
1606
 */
1607
function geodir_custom_posts_body_class($classes) {
1608 2
    global $wpdb, $wp;
1609 2
    $post_types = geodir_get_posttypes('object');
1610 2
    if (!empty($post_types) && count((array)$post_types) > 1) {
1611
        $classes[] = 'geodir_custom_posts';
1612
    }
1613
1614
    // fix body class for signup page
1615 2
    if (geodir_is_page('login')) {
1616
        $new_classes = array();
1617
        $new_classes[] = 'signup page-geodir-signup';
1618
        if (!empty($classes)) {
1619
            foreach ($classes as $class) {
1620
                if ($class && $class != 'home' && $class != 'blog') {
1621
                    $new_classes[] = $class;
1622
                }
1623
            }
1624
        }
1625
        $classes = $new_classes;
1626
    }
1627
1628 2
    if (geodir_is_geodir_page()) {
1629
        $classes[] = 'geodir-page';
1630
    }
1631
1632 2
    return $classes;
1633
}
1634
1635
add_filter('body_class', 'geodir_custom_posts_body_class'); // let's add a class to the body so we can style the new addition to the search
1636
1637
1638
/**
1639
 * Returns available map zoom levels.
1640
 *
1641
 * @since 1.0.0
1642
 * @package GeoDirectory
1643
 * @return array Available map zoom levels.
1644
 */
1645
function geodir_map_zoom_level()
1646
{
1647
    /**
1648
     * Filter GD map zoom level.
1649
     *
1650
     * @since 1.0.0
1651
     */
1652 2
    return apply_filters('geodir_map_zoom_level', array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19));
1653
1654
}
1655
1656
1657
/**
1658
 * This function takes backup of an option so they can be restored later.
1659
 *
1660
 * @since 1.0.0
1661
 * @package GeoDirectory
1662
 * @param string $geodir_option_name Option key.
1663
 */
1664
function geodir_option_version_backup($geodir_option_name)
1665
{
1666
    $version_date = time();
1667
    $geodir_option = get_option($geodir_option_name);
1668
1669
    if (!empty($geodir_option)) {
1670
        add_option($geodir_option_name . '_' . $version_date, $geodir_option);
1671
    }
1672
}
1673
1674
/**
1675
 * display add listing page for wpml.
1676
 *
1677
 * @since 1.0.0
1678
 * @package GeoDirectory
1679
 * @param int $page_id The page ID.
1680
 * @return int Page ID.
1681
 */
1682
function get_page_id_geodir_add_listing_page($page_id)
1683
{
1684 13
    if (geodir_wpml_multilingual_status()) {
1685
        $post_type = 'post_page';
1686
        $page_id = geodir_get_wpml_element_id($page_id, $post_type);
1687
    }
1688 13
    return $page_id;
1689
}
1690
1691
/**
1692
 * Returns wpml multilingual status.
1693
 *
1694
 * @since 1.0.0
1695
 * @package GeoDirectory
1696
 * @return bool Returns true when sitepress multilingual CMS active. else returns false.
1697
 */
1698
function geodir_wpml_multilingual_status()
1699
{
1700 13
    if (function_exists('icl_object_id')) {
1701
        return true;
1702
    }
1703 13
    return false;
1704
}
1705
1706
/**
1707
 * Returns WPML element ID.
1708
 *
1709
 * @since 1.0.0
1710
 * @package GeoDirectory
1711
 * @param int $page_id The page ID.
1712
 * @param string $post_type The post type.
1713
 * @return int Element ID when exists. Else the page id.
1714
 */
1715
function geodir_get_wpml_element_id($page_id, $post_type)
1716
{
1717
    global $sitepress;
1718
    if (geodir_wpml_multilingual_status() && !empty($sitepress) && isset($sitepress->queries)) {
1719
        $trid = $sitepress->get_element_trid($page_id, $post_type);
1720
1721
        if ($trid > 0) {
1722
            $translations = $sitepress->get_element_translations($trid, $post_type);
1723
1724
            $lang = $sitepress->get_current_language();
1725
            $lang = $lang ? $lang : $sitepress->get_default_language();
1726
1727
            if (!empty($translations) && !empty($lang) && isset($translations[$lang]) && isset($translations[$lang]->element_id) && !empty($translations[$lang]->element_id)) {
1728
                $page_id = $translations[$lang]->element_id;
1729
            }
1730
        }
1731
    }
1732
    return $page_id;
1733
}
1734
1735
/**
1736
 * WPML check elemet ID.
1737
 *
1738
 * @since 1.0.0
1739
 * @package GeoDirectory
1740
 * @deprecated 1.4.6 No longer needed as we handel translating GD pages as normal now.
1741
 */
1742
function geodir_wpml_check_element_id()
1743
{
1744
    global $sitepress;
1745
    if (geodir_wpml_multilingual_status() && !empty($sitepress) && isset($sitepress->queries)) {
1746
        $el_type = 'post_page';
1747
        $el_id = get_option('geodir_add_listing_page');
1748
        $default_lang = $sitepress->get_default_language();
1749
        $el_details = $sitepress->get_element_language_details($el_id, $el_type);
1750
1751
        if (!($el_id > 0 && $default_lang && !empty($el_details) && isset($el_details->language_code) && $el_details->language_code == $default_lang)) {
1752
            if (!$el_details->source_language_code) {
1753
                $sitepress->set_element_language_details($el_id, $el_type, '', $default_lang);
1754
                $sitepress->icl_translations_cache->clear();
1755
            }
1756
        }
1757
    }
1758
}
1759
1760
/**
1761
 * Returns orderby SQL using the given query args.
1762
 *
1763
 * @since 1.0.0
1764
 * @package GeoDirectory
1765
 * @global object $wpdb WordPress Database object.
1766
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1767
 * @param array $query_args The query array.
1768
 * @return string Orderby SQL.
1769
 */
1770
function geodir_widget_listings_get_order($query_args)
0 ignored issues
show
Unused Code introduced by
The parameter $query_args 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...
1771
{
1772 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
1773
1774 8
    $query_args = $gd_query_args_widgets;
1775 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
1776
        return $wpdb->posts . ".post_date DESC, ";
1777
    }
1778
1779 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
1780 8
    $table = $plugin_prefix . $post_type . '_detail';
1781
1782 8
    $sort_by = !empty($query_args['order_by']) ? $query_args['order_by'] : '';
1783
1784
    switch ($sort_by) {
1785 8
        case 'latest':
1786 8
        case 'newest':
1787 4
            $orderby = $wpdb->posts . ".post_date DESC, ";
1788 4
            break;
1789 4
        case 'featured':
1790
            $orderby = $table . ".is_featured ASC, ";
1791
            break;
1792 4
        case 'az':
1793
            $orderby = $wpdb->posts . ".post_title ASC, ";
1794
            break;
1795 4
        case 'high_review':
1796 3
            $orderby = $table . ".rating_count DESC, " . $table . ".overall_rating DESC, ";
1797 3
            break;
1798 1
        case 'high_rating':
1799
            $orderby = "( " . $table . ".overall_rating  ) DESC, ";
1800
            break;
1801 1
        case 'random':
1802
            $orderby = "RAND(), ";
1803
            break;
1804 1
        default:
1805 1
            $orderby = $wpdb->posts . ".post_title ASC, ";
1806 1
            break;
1807 1
    }
1808
1809 8
    return $orderby;
1810
}
1811
1812
/**
1813
 * Retrieve listings/count using requested filter parameters.
1814
 *
1815
 * @since 1.0.0
1816
 * @package GeoDirectory
1817
 * @since 1.4.2 New paramater $count_only added
1818
 * @global object $wpdb WordPress Database object.
1819
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1820
 * @global string $table_prefix WordPress Database Table prefix.
1821
 * @param array $query_args The query array.
1822
 * @param  int|bool $count_only If true returns listings count only, otherwise returns array
1823
 * @return mixed Result object.
1824
 */
1825
function geodir_get_widget_listings($query_args = array(), $count_only = false)
1826
{
1827 8
    global $wpdb, $plugin_prefix, $table_prefix;
1828 8
    $GLOBALS['gd_query_args_widgets'] = $query_args;
1829 8
    $gd_query_args_widgets = $query_args;
1830
1831 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
1832 8
    $table = $plugin_prefix . $post_type . '_detail';
1833
1834 8
    $fields = $wpdb->posts . ".*, " . $table . ".*";
1835
    /**
1836
     * Filter widget listing fields string part that is being used for query.
1837
     *
1838
     * @since 1.0.0
1839
     * @param string $fields Fields string.
1840
     * @param string $table Table name.
1841
     * @param string $post_type Post type.
1842
     */
1843 8
    $fields = apply_filters('geodir_filter_widget_listings_fields', $fields, $table, $post_type);
1844
1845 8
    $join = "INNER JOIN " . $table . " ON (" . $table . ".post_id = " . $wpdb->posts . ".ID)";
1846
1847
    ########### WPML ###########
1848
1849 8
    if (function_exists('icl_object_id')) {
1850
        global $sitepress;
1851
        $lang_code = ICL_LANGUAGE_CODE;
1852
        if ($lang_code) {
1853
            $join .= " JOIN " . $table_prefix . "icl_translations icl_t ON icl_t.element_id = " . $table_prefix . "posts.ID";
1854
        }
1855
    }
1856
1857
    ########### WPML ###########
1858
1859
    /**
1860
     * Filter widget listing join clause string part that is being used for query.
1861
     *
1862
     * @since 1.0.0
1863
     * @param string $join Join clause string.
1864
     * @param string $post_type Post type.
1865
     */
1866 8
    $join = apply_filters('geodir_filter_widget_listings_join', $join, $post_type);
1867
1868 8
    $post_status = is_super_admin() ? " OR " . $wpdb->posts . ".post_status = 'private'" : '';
1869
1870 8
    $where = " AND ( " . $wpdb->posts . ".post_status = 'publish' " . $post_status . " ) AND " . $wpdb->posts . ".post_type = '" . $post_type . "'";
1871
1872
    ########### WPML ###########
1873 8
    if (function_exists('icl_object_id')) {
1874
        if ($lang_code) {
1875
            $where .= " AND icl_t.language_code = '$lang_code' AND icl_t.element_type = 'post_$post_type' ";
0 ignored issues
show
Bug introduced by
The variable $lang_code 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...
1876
        }
1877
    }
1878
    ########### WPML ###########
1879
    /**
1880
     * Filter widget listing where clause string part that is being used for query.
1881
     *
1882
     * @since 1.0.0
1883
     * @param string $where Where clause string.
1884
     * @param string $post_type Post type.
1885
     */
1886 8
    $where = apply_filters('geodir_filter_widget_listings_where', $where, $post_type);
1887 8
    $where = $where != '' ? " WHERE 1=1 " . $where : '';
1888
1889 8
    $groupby = " GROUP BY $wpdb->posts.ID ";
1890
    /**
1891
     * Filter widget listing groupby clause string part that is being used for query.
1892
     *
1893
     * @since 1.0.0
1894
     * @param string $groupby Group by clause string.
1895
     * @param string $post_type Post type.
1896
     */
1897 8
    $groupby = apply_filters('geodir_filter_widget_listings_groupby', $groupby, $post_type);
1898
1899 8
    if ($count_only) {
1900 1
        $sql = "SELECT COUNT(" . $wpdb->posts . ".ID) AS total FROM " . $wpdb->posts . "
1901 1
			" . $join . "
1902 1
			" . $where;
1903 1
        $rows = (int)$wpdb->get_var($sql);
1904 1
    } else {
1905 8
        $orderby = geodir_widget_listings_get_order($query_args);
1906
        /**
1907
         * Filter widget listing orderby clause string part that is being used for query.
1908
         *
1909
         * @since 1.0.0
1910
         * @param string $orderby Order by clause string.
1911
         * @param string $table Table name.
1912
         * @param string $post_type Post type.
1913
         */
1914 8
        $orderby = apply_filters('geodir_filter_widget_listings_orderby', $orderby, $table, $post_type);
1915 8
        $orderby .= $wpdb->posts . ".post_title ASC";
1916 8
        $orderby = $orderby != '' ? " ORDER BY " . $orderby : '';
1917
1918 8
        $limit = !empty($query_args['posts_per_page']) ? $query_args['posts_per_page'] : 5;
1919
        /**
1920
         * Filter widget listing limit that is being used for query.
1921
         *
1922
         * @since 1.0.0
1923
         * @param int $limit Query results limit.
1924
         * @param string $post_type Post type.
1925
         */
1926 8
        $limit = apply_filters('geodir_filter_widget_listings_limit', $limit, $post_type);
1927
1928 8
        $page = !empty($query_args['pageno']) ? absint($query_args['pageno']) : 1;
1929 8
        if ( !$page )
1930 8
            $page = 1;
1931
1932 8
        $limit = (int)$limit > 0 ? " LIMIT " . absint( ( $page - 1 ) * (int)$limit ) . ", " . (int)$limit : "";
1933
1934 8
        $sql = "SELECT SQL_CALC_FOUND_ROWS " . $fields . " FROM " . $wpdb->posts . "
1935 8
			" . $join . "
1936 8
			" . $where . "
1937 8
			" . $groupby . "
1938 8
			" . $orderby . "
1939 8
			" . $limit;
1940 8
        $rows = $wpdb->get_results($sql);
1941
    }
1942
1943 8
    unset($GLOBALS['gd_query_args_widgets']);
1944 8
    unset($gd_query_args_widgets);
1945
1946 8
    return $rows;
1947
}
1948
1949
/**
1950
 * Listing query fields SQL part for widgets.
1951
 *
1952
 * @since 1.0.0
1953
 * @package GeoDirectory
1954
 * @global object $wpdb WordPress Database object.
1955
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1956
 * @param string $fields Fields SQL.
1957
 * @return string Modified fields SQL.
1958
 */
1959
function geodir_function_widget_listings_fields($fields)
1960
{
1961 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
1962
1963 8
    $query_args = $gd_query_args_widgets;
1964 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
1965
        return $fields;
1966
    }
1967
    
1968 8
    return $fields;
1969
}
1970
1971
/**
1972
 * Listing query join clause SQL part for widgets.
1973
 *
1974
 * @since 1.0.0
1975
 * @package GeoDirectory
1976
 * @global object $wpdb WordPress Database object.
1977
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1978
 * @param string $join Join clause SQL.
1979
 * @return string Modified join clause SQL.
1980
 */
1981
function geodir_function_widget_listings_join($join)
1982
{
1983 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
1984
1985 8
    $query_args = $gd_query_args_widgets;
1986 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
1987
        return $join;
1988
    }
1989
1990 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
1991 8
    $table = $plugin_prefix . $post_type . '_detail';
1992
1993 8 View Code Duplication
    if (!empty($query_args['with_pics_only'])) {
1994
        $join .= " LEFT JOIN " . GEODIR_ATTACHMENT_TABLE . " ON ( " . GEODIR_ATTACHMENT_TABLE . ".post_id=" . $table . ".post_id AND " . GEODIR_ATTACHMENT_TABLE . ".mime_type LIKE '%image%' )";
1995
    }
1996
1997 8 View Code Duplication
    if (!empty($query_args['tax_query'])) {
1998 4
        $tax_queries = get_tax_sql($query_args['tax_query'], $wpdb->posts, 'ID');
1999 4
        if (!empty($tax_queries['join']) && !empty($tax_queries['where'])) {
2000 2
            $join .= $tax_queries['join'];
2001 2
        }
2002 4
    }
2003
2004 8
    return $join;
2005
}
2006
2007
/**
2008
 * Listing query where clause SQL part for widgets.
2009
 *
2010
 * @since 1.0.0
2011
 * @package GeoDirectory
2012
 * @global object $wpdb WordPress Database object.
2013
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2014
 * @param string $where Where clause SQL.
2015
 * @return string Modified where clause SQL.
2016
 */
2017
function geodir_function_widget_listings_where($where)
2018
{
2019 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2020
2021 8
    $query_args = $gd_query_args_widgets;
2022 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2023
        return $where;
2024
    }
2025 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
2026 8
    $table = $plugin_prefix . $post_type . '_detail';
2027
2028 8
    if (!empty($query_args)) {
2029 8
        if (!empty($query_args['gd_location']) && function_exists('geodir_default_location_where')) {
2030
            $where = geodir_default_location_where($where, $table);
2031
        }
2032
2033 8
        if (!empty($query_args['post_author'])) {
2034
            $where .= " AND " . $wpdb->posts . ".post_author = " . (int)$query_args['post_author'];
2035
        }
2036
        
2037 8
        if (!empty($query_args['show_featured_only'])) {
2038 2
            $where .= " AND " . $table . ".is_featured = '1'";
2039 2
        }
2040
2041 8
        if (!empty($query_args['show_special_only'])) {
2042
            $where .= " AND ( " . $table . ".geodir_special_offers != '' AND " . $table . ".geodir_special_offers IS NOT NULL )";
2043
        }
2044
2045 8
        if (!empty($query_args['with_pics_only'])) {
2046
            $where .= " AND " . GEODIR_ATTACHMENT_TABLE . ".ID IS NOT NULL ";
2047
        }
2048
2049 8
        if (!empty($query_args['featured_image_only'])) {
2050 2
            $where .= " AND " . $table . ".featured_image IS NOT NULL AND " . $table . ".featured_image!='' ";
2051 2
        }
2052
2053 8
        if (!empty($query_args['with_videos_only'])) {
2054
            $where .= " AND ( " . $table . ".geodir_video != '' AND " . $table . ".geodir_video IS NOT NULL )";
2055
        }
2056
2057 8 View Code Duplication
        if (!empty($query_args['tax_query'])) {
2058 4
            $tax_queries = get_tax_sql($query_args['tax_query'], $wpdb->posts, 'ID');
2059
2060 4
            if (!empty($tax_queries['join']) && !empty($tax_queries['where'])) {
2061 2
                $where .= $tax_queries['where'];
2062 2
            }
2063 4
        }
2064 8
    }
2065
2066 8
    return $where;
2067
}
2068
2069
/**
2070
 * Listing query orderby clause SQL part for widgets.
2071
 *
2072
 * @since 1.0.0
2073
 * @package GeoDirectory
2074
 * @global object $wpdb WordPress Database object.
2075
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2076
 * @param string $orderby Orderby clause SQL.
2077
 * @return string Modified orderby clause SQL.
2078
 */
2079
function geodir_function_widget_listings_orderby($orderby)
2080
{
2081 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2082
2083 8
    $query_args = $gd_query_args_widgets;
2084 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2085
        return $orderby;
2086
    }
2087
2088 8
    return $orderby;
2089
}
2090
2091
/**
2092
 * Listing query limit for widgets.
2093
 *
2094
 * @since 1.0.0
2095
 * @package GeoDirectory
2096
 * @global object $wpdb WordPress Database object.
2097
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2098
 * @param int $limit Query limit.
2099
 * @return int Query limit.
2100
 */
2101
function geodir_function_widget_listings_limit($limit)
2102
{
2103 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2104
2105 8
    $query_args = $gd_query_args_widgets;
2106 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2107
        return $limit;
2108
    }
2109
2110 8
    if (!empty($query_args) && !empty($query_args['posts_per_page'])) {
2111 8
        $limit = (int)$query_args['posts_per_page'];
2112 8
    }
2113
2114 8
    return $limit;
2115
}
2116
2117
/**
2118
 * WP media large width.
2119
 *
2120
 * @since 1.0.0
2121
 * @package GeoDirectory
2122
 * @param int $default Default width.
2123
 * @param string|array $params Image parameters.
2124
 * @return int Large size width.
2125
 */
2126 View Code Duplication
function geodir_media_image_large_width($default = 800, $params = '')
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2127
{
2128 1
    $large_size_w = get_option('large_size_w');
2129 1
    $large_size_w = $large_size_w > 0 ? $large_size_w : $default;
2130 1
    $large_size_w = absint($large_size_w);
2131
2132 1
    if (!get_option('geodir_use_wp_media_large_size')) {
2133 1
        $large_size_w = 800;
2134 1
    }
2135
2136
    /**
2137
     * Filter large image width.
2138
     *
2139
     * @since 1.0.0
2140
     * @param int $large_size_w Large image width.
2141
     * @param int $default Default width.
2142
     * @param string|array $params Image parameters.
2143
     */
2144 1
    $large_size_w = apply_filters('geodir_filter_media_image_large_width', $large_size_w, $default, $params);
2145 1
    return $large_size_w;
2146
}
2147
2148
/**
2149
 * WP media large height.
2150
 *
2151
 * @since 1.0.0
2152
 * @package GeoDirectory
2153
 * @param int $default Default height.
2154
 * @param string $params Image parameters.
2155
 * @return int Large size height.
2156
 */
2157 View Code Duplication
function geodir_media_image_large_height($default = 800, $params = '')
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2158
{
2159 1
    $large_size_h = get_option('large_size_h');
2160 1
    $large_size_h = $large_size_h > 0 ? $large_size_h : $default;
2161 1
    $large_size_h = absint($large_size_h);
2162
2163 1
    if (!get_option('geodir_use_wp_media_large_size')) {
2164 1
        $large_size_h = 800;
2165 1
    }
2166
2167
    /**
2168
     * Filter large image height.
2169
     *
2170
     * @since 1.0.0
2171
     * @param int $large_size_h Large image height.
2172
     * @param int $default Default height.
2173
     * @param string|array $params Image parameters.
2174
     */
2175 1
    $large_size_h = apply_filters('geodir_filter_media_image_large_height', $large_size_h, $default, $params);
2176
2177 1
    return $large_size_h;
2178
}
2179
2180
/**
2181
 * Sanitize location name.
2182
 *
2183
 * @since 1.0.0
2184
 * @package GeoDirectory
2185
 * @param string $type Location type. Can be gd_country, gd_region, gd_city.
2186
 * @param string $name Location name.
2187
 * @param bool $translate Do you want to translate the name? Default: true.
2188
 * @return string Sanitized name.
2189
 */
2190
function geodir_sanitize_location_name($type, $name, $translate = true)
2191
{
2192
    if ($name == '') {
2193
        return NULL;
2194
    }
2195
2196
    $type = $type == 'gd_country' ? 'country' : $type;
2197
    $type = $type == 'gd_region' ? 'region' : $type;
2198
    $type = $type == 'gd_city' ? 'city' : $type;
2199
2200
    $return = $name;
2201
    if (function_exists('get_actual_location_name')) {
2202
        $return = get_actual_location_name($type, $name, $translate);
2203
    } else {
2204
        $return = preg_replace('/-(\d+)$/', '', $return);
2205
        $return = preg_replace('/[_-]/', ' ', $return);
2206
        $return = geodir_ucwords($return);
2207
        $return = $translate ? __($return, 'geodirectory') : $return;
2208
    }
2209
2210
    return $return;
2211
}
2212
2213
2214
/**
2215
 * Pluralize comment number.
2216
 *
2217
 * @since 1.0.0
2218
 * @package GeoDirectory
2219
 * @param int $number Comments number.
2220
 */
2221
function geodir_comments_number($number)
2222
{
2223
2224 8
    if ($number > 1) {
2225
        $output = str_replace('%', number_format_i18n($number), __('% Reviews', 'geodirectory'));
2226 8
    } elseif ($number == 0 || $number == '') {
2227 8
        $output = __('No Reviews', 'geodirectory');
2228 8
    } else { // must be one
2229 4
        $output = __('1 Review', 'geodirectory');
2230
    }
2231 8
    echo $output;
2232 8
}
2233
2234
/**
2235
 * Checks whether the current page is geodirectory home page or not.
2236
 *
2237
 * @since 1.0.0
2238
 * @package GeoDirectory
2239
 * @global object $wpdb WordPress Database object.
2240
 * @return bool If current page is GD home page returns true, else false.
2241
 */
2242
function is_page_geodir_home()
2243
{
2244 3
    global $wpdb;
2245 3
    $cur_url = str_replace(array("https://", "http://", "www."), array('', '', ''), geodir_curPageURL());
2246 3
    if (function_exists('geodir_location_geo_home_link')) {
2247
        remove_filter('home_url', 'geodir_location_geo_home_link', 100000);
2248
    }
2249 3
    $home_url = home_url('', 'http');
2250 3
    if (function_exists('geodir_location_geo_home_link')) {
2251
        add_filter('home_url', 'geodir_location_geo_home_link', 100000, 2);
2252
    }
2253 3
    $home_url = str_replace("www.", "", $home_url);
2254 3
    if ( (strpos($home_url, $cur_url) !== false || strpos($home_url . '/', $cur_url) !== false) && ('page' == get_option('show_on_front') && get_option('page_on_front') && get_option('page_on_front')==get_option('geodir_home_page')) ) {
2255
        return true;
2256 3
    }elseif(get_query_var('page_id') == get_option('page_on_front') && 'page' == get_option('show_on_front') && get_option('page_on_front') && get_option('page_on_front')==get_option('geodir_home_page')){
2257
        return true;
2258
    } else {
2259 3
        return false;
2260
    }
2261
2262
}
2263
2264
2265
/**
2266
 * Returns homepage canonical url for SEO plugins.
2267
 *
2268
 * @since 1.0.0
2269
 * @package GeoDirectory
2270
 * @global object $post The current post object.
2271
 * @param string $url The old url.
2272
 * @return string The canonical URL.
2273
 */
2274
function geodir_wpseo_homepage_canonical($url)
2275
{
2276
    global $post;
2277
2278
    if (is_page_geodir_home()) {
2279
        return home_url();
2280
    }
2281
2282
    return $url;
2283
}
2284
2285
add_filter('wpseo_canonical', 'geodir_wpseo_homepage_canonical', 10);
2286
add_filter('aioseop_canonical_url', 'geodir_wpseo_homepage_canonical', 10);
2287
2288
/**
2289
 * Add extra fields to google maps script call.
2290
 *
2291
 * @since 1.0.0
2292
 * @package GeoDirectory
2293
 * @global object $post The current post object.
2294
 * @param string $extra Old extra string.
2295
 * @return string Modified extra string.
2296
 */
2297
function geodir_googlemap_script_extra_details_page($extra)
2298
{
2299 2
    global $post;
2300 2
    $add_google_places_api = false;
2301 2
    if (isset($post->post_content) && has_shortcode($post->post_content, 'gd_add_listing')) {
2302
        $add_google_places_api = true;
2303
    }
2304 2
    if (!str_replace('libraries=places', '', $extra) && (geodir_is_page('detail') || $add_google_places_api)) {
2305 1
        $extra .= "&amp;libraries=places";
2306 1
    }
2307
2308 2
    return $extra;
2309
}
2310
2311
add_filter('geodir_googlemap_script_extra', 'geodir_googlemap_script_extra_details_page', 101, 1);
2312
2313
2314
/**
2315
 * Generates popular post category HTML.
2316
 *
2317
 * @since 1.0.0
2318
 * @since 1.5.1 Added option to set default post type.
2319
 * @package GeoDirectory
2320
 * @global object $wpdb WordPress Database object.
2321
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2322
 * @global string $geodir_post_category_str The geodirectory post category.
2323
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2324
 * @param array|string $instance The settings for the particular instance of the widget.
2325
 */
2326
function geodir_popular_post_category_output($args = '', $instance = '')
2327
{
2328
    // prints the widget
2329 3
    global $wpdb, $plugin_prefix, $geodir_post_category_str;
2330 3
    extract($args, EXTR_SKIP);
2331
2332 3
    echo $before_widget;
2333
2334
    /** This filter is documented in geodirectory_widgets.php */
2335 3
    $title = empty($instance['title']) ? __('Popular Categories', 'geodirectory') : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2336
2337 3
    $gd_post_type = geodir_get_current_posttype();
2338
2339 3
    $category_limit = isset($instance['category_limit']) && $instance['category_limit'] > 0 ? (int)$instance['category_limit'] : 15;
2340 3
    $default_post_type = !empty($gd_post_type) ? $gd_post_type : (isset($instance['default_post_type']) && gdsc_is_post_type_valid($instance['default_post_type']) ? $instance['default_post_type'] : '');
2341
2342 3
    $taxonomy = array();
2343 3
    if (!empty($gd_post_type)) {
2344
        $taxonomy[] = $gd_post_type . "category";
2345
    } else {
2346 3
        $taxonomy = geodir_get_taxonomies($gd_post_type);
2347
    }
2348
2349 3
    $terms = get_terms($taxonomy);
2350 3
    $a_terms = array();
2351 3
    $b_terms = array();
2352
2353 3
    foreach ($terms as $term) {
2354 3
        if ($term->count > 0) {
2355 3
            $a_terms[$term->taxonomy][] = $term;
2356 3
        }
2357 3
    }
2358
2359 3
    if (!empty($a_terms)) {
2360 3
        foreach ($a_terms as $b_key => $b_val) {
2361 3
            $b_terms[$b_key] = geodir_sort_terms($b_val, 'count');
2362 3
        }
2363
2364 3
        $default_taxonomy = $default_post_type != '' && isset($b_terms[$default_post_type . 'category']) ? $default_post_type . 'category' : '';
2365
2366 3
        $tax_change_output = '';
2367 3
        if (count($b_terms) > 1) {
2368
            $tax_change_output .= "<select data-limit='$category_limit' class='geodir-cat-list-tax'  onchange='geodir_get_post_term(this);'>";
2369
            foreach ($b_terms as $key => $val) {
2370
                $ptype = get_post_type_object(str_replace("category", "", $key));
2371
                $cpt_name = __($ptype->labels->singular_name, 'geodirectory');
2372
                $tax_change_output .= "<option value='$key' ". selected($key, $default_taxonomy, false) .">" . sprintf(__('%s Categories', 'geodirectory'),$cpt_name) . "</option>";
2373
            }
2374
            $tax_change_output .= "</select>";
2375
        }
2376
2377 3
        if (!empty($b_terms)) {
2378 3
            $terms = $default_taxonomy != '' && isset($b_terms[$default_taxonomy]) ? $b_terms[$default_taxonomy] : reset($b_terms);// get the first array
2379 3
            global $cat_count;//make global so we can change via function
2380 3
            $cat_count = 0;
2381
            ?>
2382
            <div class="geodir-category-list-in clearfix">
2383
                <div class="geodir-cat-list clearfix">
2384
                    <?php
2385 3
                    echo $before_title . __($title) . $after_title;
2386
2387 3
                    echo $tax_change_output;
2388
2389 3
                    echo '<ul class="geodir-popular-cat-list">';
2390
2391 3
                    geodir_helper_cat_list_output($terms, $category_limit);
2392
2393 3
                    echo '</ul>';
2394
                    ?>
2395
                </div>
2396
                <?php
2397 3
                $hide = '';
2398 3
                if ($cat_count < $category_limit) {
2399 3
                    $hide = 'style="display:none;"';
2400 3
                }
2401 3
                echo "<div class='geodir-cat-list-more' $hide >";
2402 3
                echo '<a href="javascript:void(0)" class="geodir-morecat geodir-showcat">' . __('More Categories', 'geodirectory') . '</a>';
2403 3
                echo '<a href="javascript:void(0)" class="geodir-morecat geodir-hidecat geodir-hide">' . __('Less Categories', 'geodirectory') . '</a>';
2404 3
                echo "</div>";
2405
                /* add scripts */
2406 3
                add_action('wp_footer', 'geodir_popular_category_add_scripts', 100);
2407
                ?>
2408
            </div>
2409
        <?php
2410 3
        }
2411 3
    }
2412 3
    echo $after_widget;
2413 3
}
2414
2415
/**
2416
 * Generates category list HTML.
2417
 *
2418
 * @since 1.0.0
2419
 * @package GeoDirectory
2420
 * @global string $geodir_post_category_str The geodirectory post category.
2421
 * @param array $terms An array of term objects.
2422
 * @param int $category_limit Number of categories to display by default.
2423
 */
2424
function geodir_helper_cat_list_output($terms, $category_limit)
2425
{
2426 3
    global $geodir_post_category_str, $cat_count;
2427 3
    $term_icons = geodir_get_term_icon();
2428
2429 3
    $geodir_post_category_str = array();
2430
2431
2432 3
    foreach ($terms as $cat) {
2433 3
        $post_type = str_replace("category", "", $cat->taxonomy);
2434 3
        $term_icon_url = !empty($term_icons) && isset($term_icons[$cat->term_id]) ? $term_icons[$cat->term_id] : '';
2435
2436 3
        $cat_count++;
2437
2438 3
        $geodir_post_category_str[] = array('posttype' => $post_type, 'termid' => $cat->term_id);
2439
2440 3
        $class_row = $cat_count > $category_limit ? 'geodir-pcat-hide geodir-hide' : 'geodir-pcat-show';
2441 3
        $total_post = $cat->count;
2442
2443 3
        $term_link = get_term_link( $cat, $cat->taxonomy );
2444
        /**
2445
         * Filer the category term link.
2446
         *
2447
         * @since 1.4.5
2448
         * @param string $term_link The term permalink.
2449
         * @param int    $cat->term_id The term id.
2450
         * @param string $post_type Wordpress post type.
2451
         */
2452 3
        $term_link = apply_filters( 'geodir_category_term_link', $term_link, $cat->term_id, $post_type );
2453
2454 3
        echo '<li class="' . $class_row . '"><a href="' . $term_link . '">';
2455 3
        echo '<img alt="' . esc_attr($cat->name) . ' icon" style="height:20px;vertical-align:middle;" src="' . $term_icon_url . '"/> <span class="cat-link">'; echo $cat->name . '</span> <span class="geodir_term_class geodir_link_span geodir_category_class_' . $post_type . '_' . $cat->term_id . '">(' . $total_post . ')</span> ';
2456 3
        echo '</a></li>';
2457 3
    }
2458 3
}
2459
2460
/**
2461
 * Generates listing slider HTML.
2462
 *
2463
 * @since 1.0.0
2464
 * @package GeoDirectory
2465
 * @global object $post The current post object.
2466
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2467
 * @param array|string $instance The settings for the particular instance of the widget.
2468
 */
2469
function geodir_listing_slider_widget_output($args = '', $instance = '')
2470
{
2471
    // prints the widget
2472 2
    extract($args, EXTR_SKIP);
2473
2474 2
    echo $before_widget;
2475
2476
    /** This filter is documented in geodirectory_widgets.php */
2477 2
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2478
    /**
2479
     * Filter the widget post type.
2480
     *
2481
     * @since 1.0.0
2482
     * @param string $instance['post_type'] Post type of listing.
2483
     */
2484 2
    $post_type = empty($instance['post_type']) ? 'gd_place' : apply_filters('widget_post_type', $instance['post_type']);
2485
    /**
2486
     * Filter the widget's term.
2487
     *
2488
     * @since 1.0.0
2489
     * @param string $instance['category'] Filter by term. Can be any valid term.
2490
     */
2491 2
    $category = empty($instance['category']) ? '0' : apply_filters('widget_category', $instance['category']);
2492
    /**
2493
     * Filter the widget listings limit.
2494
     *
2495
     * @since 1.0.0
2496
     * @param string $instance['post_number'] Number of listings to display.
2497
     */
2498 2
    $post_number = empty($instance['post_number']) ? '5' : apply_filters('widget_post_number', $instance['post_number']);
2499
    /**
2500
     * Filter the widget listings limit shown at one time.
2501
     *
2502
     * @since 1.5.0
2503
     * @param string $instance['max_show'] Number of listings to display on screen.
2504
     */
2505 2
    $max_show = empty($instance['max_show']) ? '1' : apply_filters('widget_max_show', $instance['max_show']);
2506
    /**
2507
     * Filter the widget slide width.
2508
     *
2509
     * @since 1.5.0
2510
     * @param string $instance['slide_width'] Width of the slides shown.
2511
     */
2512 2
    $slide_width = empty($instance['slide_width']) ? '' : apply_filters('widget_slide_width', $instance['slide_width']);
2513
    /**
2514
     * Filter widget's "show title" value.
2515
     *
2516
     * @since 1.0.0
2517
     * @param string|bool $instance['show_title'] Do you want to display title? Can be 1 or 0.
2518
     */
2519 2
    $show_title = empty($instance['show_title']) ? '' : apply_filters('widget_show_title', $instance['show_title']);
2520
    /**
2521
     * Filter widget's "slideshow" value.
2522
     *
2523
     * @since 1.0.0
2524
     * @param int $instance['slideshow'] Setup a slideshow for the slider to animate automatically.
2525
     */
2526 2
    $slideshow = empty($instance['slideshow']) ? 0 : apply_filters('widget_slideshow', $instance['slideshow']);
2527
    /**
2528
     * Filter widget's "animationLoop" value.
2529
     *
2530
     * @since 1.0.0
2531
     * @param int $instance['animationLoop'] Gives the slider a seamless infinite loop.
2532
     */
2533 2
    $animationLoop = empty($instance['animationLoop']) ? 0 : apply_filters('widget_animationLoop', $instance['animationLoop']);
2534
    /**
2535
     * Filter widget's "directionNav" value.
2536
     *
2537
     * @since 1.0.0
2538
     * @param int $instance['directionNav'] Enable previous/next arrow navigation?. Can be 1 or 0.
2539
     */
2540 2
    $directionNav = empty($instance['directionNav']) ? 0 : apply_filters('widget_directionNav', $instance['directionNav']);
2541
    /**
2542
     * Filter widget's "slideshowSpeed" value.
2543
     *
2544
     * @since 1.0.0
2545
     * @param int $instance['slideshowSpeed'] Set the speed of the slideshow cycling, in milliseconds.
2546
     */
2547 2
    $slideshowSpeed = empty($instance['slideshowSpeed']) ? 5000 : apply_filters('widget_slideshowSpeed', $instance['slideshowSpeed']);
2548
    /**
2549
     * Filter widget's "animationSpeed" value.
2550
     *
2551
     * @since 1.0.0
2552
     * @param int $instance['animationSpeed'] Set the speed of animations, in milliseconds.
2553
     */
2554 2
    $animationSpeed = empty($instance['animationSpeed']) ? 600 : apply_filters('widget_animationSpeed', $instance['animationSpeed']);
2555
    /**
2556
     * Filter widget's "animation" value.
2557
     *
2558
     * @since 1.0.0
2559
     * @param string $instance['animation'] Controls the animation type, "fade" or "slide".
2560
     */
2561 2
    $animation = empty($instance['animation']) ? 'slide' : apply_filters('widget_animation', $instance['animation']);
2562
    /**
2563
     * Filter widget's "list_sort" type.
2564
     *
2565
     * @since 1.0.0
2566
     * @param string $instance['list_sort'] Listing sort by type.
2567
     */
2568 2
    $list_sort = empty($instance['list_sort']) ? 'latest' : apply_filters('widget_list_sort', $instance['list_sort']);
2569 2
    $show_featured_only = !empty($instance['show_featured_only']) ? 1 : NULL;
2570
2571 2
    wp_enqueue_script('geodirectory-jquery-flexslider-js');
2572
    ?>
2573
    <script type="text/javascript">
2574
        jQuery(window).load(function () {
2575
            jQuery('#geodir_widget_carousel').flexslider({
2576
                animation: "slide",
2577
                selector: ".geodir-slides > li",
2578
                namespace: "geodir-",
2579
                controlNav: false,
2580
                directionNav: false,
2581
                animationLoop: false,
2582
                slideshow: false,
2583
                itemWidth: 75,
2584
                itemMargin: 5,
2585
                asNavFor: '#geodir_widget_slider',
2586
                rtl: <?php echo ( is_rtl() ? 'true' : 'false' ); /* fix rtl issue */ ?>
2587
            });
2588
2589
            jQuery('#geodir_widget_slider').flexslider({
2590
                animation: "<?php echo $animation;?>",
2591
                selector: ".geodir-slides > li",
2592
                namespace: "geodir-",
2593
                controlNav: true,
2594
                animationLoop: <?php echo $animationLoop;?>,
2595
                slideshow: <?php echo $slideshow;?>,
2596
                slideshowSpeed: <?php echo $slideshowSpeed;?>,
2597
                animationSpeed: <?php echo $animationSpeed;?>,
2598
                directionNav: <?php echo $directionNav;?>,
2599
                maxItems: <?php echo $max_show;?>,
2600
                move: 1,
2601
                <?php if($slide_width){ echo "itemWidth: ".$slide_width.",";}?>
2602
                sync: "#geodir_widget_carousel",
2603
                start: function (slider) {
2604
                    jQuery('.geodir-listing-flex-loader').hide();
2605
                    jQuery('#geodir_widget_slider').css({'visibility': 'visible'});
2606
                    jQuery('#geodir_widget_carousel').css({'visibility': 'visible'});
2607
                },
2608
                rtl: <?php echo ( is_rtl() ? 'true' : 'false' ); /* fix rtl issue */ ?>
2609
            });
2610
        });
2611
    </script>
2612
    <?php
2613
    $query_args = array(
2614 2
        'posts_per_page' => $post_number,
2615 2
        'is_geodir_loop' => true,
2616 2
        'post_type' => $post_type,
2617
        'order_by' => $list_sort
2618 2
    );
2619 2
    if ($show_featured_only) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $show_featured_only of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
2620 1
        $query_args['show_featured_only'] = 1;
2621 1
    }
2622
2623 2
    if ($category != 0 || $category != '') {
2624 2
        $category_taxonomy = geodir_get_taxonomies($post_type);
2625
        $tax_query = array(
2626 2
            'taxonomy' => $category_taxonomy[0],
2627 2
            'field' => 'id',
2628
            'terms' => $category
2629 2
        );
2630
2631 2
        $query_args['tax_query'] = array($tax_query);
2632 2
    }
2633
2634
    // we want listings with featured image only
2635 2
    $query_args['featured_image_only'] = 1;
2636
2637 2
    if ($post_type == 'gd_event') {
2638
        $query_args['gedir_event_listing_filter'] = 'upcoming';
2639
    }// show only upcomming events
2640
2641 2
    $widget_listings = geodir_get_widget_listings($query_args);
2642 2
    if (!empty($widget_listings) || (isset($with_no_results) && $with_no_results)) {
2643 1
        if ($title) {
2644
            echo $before_title . $title . $after_title;
2645
        }
2646
2647 1
        global $post;
2648
2649 1
        $current_post = $post;// keep current post info
2650
2651 1
        $widget_main_slides = '';
2652 1
        $nav_slides = '';
2653 1
        $widget_slides = 0;
2654
2655 1
        foreach ($widget_listings as $widget_listing) {
2656 1
            global $gd_widget_listing_type;
2657 1
            $post = $widget_listing;
2658 1
            $widget_image = geodir_get_featured_image($post->ID, 'thumbnail', get_option('geodir_listing_no_img'));
2659
2660 1
            if (!empty($widget_image)) {
2661 1
                if ($widget_image->height >= 200) {
2662 1
                    $widget_spacer_height = 0;
2663 1
                } else {
2664 1
                    $widget_spacer_height = ((200 - $widget_image->height) / 2);
2665
                }
2666
2667 1
                $widget_main_slides .= '<li class="geodir-listing-slider-widget"><img class="geodir-listing-slider-spacer" src="' . geodir_plugin_url() . "/geodirectory-assets/images/spacer.gif" . '" alt="' . $widget_image->title . '" title="' . $widget_image->title . '" style="max-height:' . $widget_spacer_height . 'px !important;margin:0 auto;" width="100" />';
2668
2669 1
                $title = '';
2670 1
                if ($show_title) {
2671
                    $title = '<div class="geodir-slider-title"><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></div>';
2672
                }
2673
2674 1
                $widget_main_slides .= $title . '<img src="' . $widget_image->src . '" alt="' . $widget_image->title . '" title="' . $widget_image->title . '" style="max-height:200px;margin:0 auto;" /></li>';
2675 1
                $nav_slides .= '<li><img src="' . $widget_image->src . '" alt="' . $widget_image->title . '" title="' . $widget_image->title . '" style="max-height:48px;margin:0 auto;" /></li>';
2676 1
                $widget_slides++;
2677 1
            }
2678 1
        }
2679
        ?>
2680
        <div class="flex-container" style="min-height:200px;">
2681
            <div class="geodir-listing-flex-loader"><i class="fa fa-refresh fa-spin"></i></div>
2682
            <div id="geodir_widget_slider" class="geodir_flexslider">
2683
                <ul class="geodir-slides clearfix"><?php echo $widget_main_slides; ?></ul>
2684
            </div>
2685
            <?php if ($widget_slides > 1) { ?>
2686
                <div id="geodir_widget_carousel" class="geodir_flexslider">
2687
                    <ul class="geodir-slides clearfix"><?php echo $nav_slides; ?></ul>
2688
                </div>
2689
            <?php } ?>
2690
        </div>
2691
        <?php
2692 1
        $GLOBALS['post'] = $current_post;
2693 1
        setup_postdata($current_post);
2694 1
    }
2695 2
    echo $after_widget;
2696 2
}
2697
2698
2699
/**
2700
 * Generates login box HTML.
2701
 *
2702
 * @since 1.0.0
2703
 * @package GeoDirectory
2704
 * @global object $current_user Current user object.
2705
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2706
 * @param array|string $instance The settings for the particular instance of the widget.
2707
 */
2708
function geodir_loginwidget_output($args = '', $instance = '')
2709
{
2710
    //print_r($args);
2711
    //print_r($instance);
2712
    // prints the widget
2713 2
    extract($args, EXTR_SKIP);
2714
2715
    /** This filter is documented in geodirectory_widgets.php */
2716 2
    $title = empty($instance['title']) ? __('My Dashboard', 'geodirectory') : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2717
2718 2
    echo $before_widget;
2719 2
    echo $before_title . $title . $after_title;
2720
2721 2
    if (is_user_logged_in()) {
2722 2
        global $current_user;
2723
2724 2
        $author_link = get_author_posts_url($current_user->data->ID);
2725 2
        $author_link = geodir_getlink($author_link, array('geodir_dashbord' => 'true'), false);
2726
2727 2
        echo '<ul class="geodir-loginbox-list">';
2728 2
        ob_start();
2729
        ?>
2730
        <li><a class="signin"
2731
               href="<?php echo wp_logout_url(home_url()); ?>"><?php _e('Logout', 'geodirectory'); ?></a></li>
2732
        <?php
2733 2
        $post_types = geodir_get_posttypes('object');
2734 2
        $show_add_listing_post_types_main_nav = get_option('geodir_add_listing_link_user_dashboard');
2735 2
        $geodir_allow_posttype_frontend = get_option('geodir_allow_posttype_frontend');
0 ignored issues
show
Unused Code introduced by
$geodir_allow_posttype_frontend 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...
2736
2737 2
        if (!empty($show_add_listing_post_types_main_nav)) {
2738 2
            $addlisting_links = '';
2739 2
            foreach ($post_types as $key => $postobj) {
0 ignored issues
show
Bug introduced by
The expression $post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
2740
2741 2
                if (in_array($key, $show_add_listing_post_types_main_nav)) {
2742
2743 2
                    if ($add_link = geodir_get_addlisting_link($key)) {
2744
2745 2
                        $name = $postobj->labels->name;
2746
2747 2
                        $selected = '';
2748 2
                        if (geodir_get_current_posttype() == $key && geodir_is_page('add-listing'))
2749 2
                            $selected = 'selected="selected"';
2750
2751
                        /**
2752
                         * Filter add listing link.
2753
                         *
2754
                         * @since 1.0.0
2755
                         * @param string $add_link Add listing link.
2756
                         * @param string $key Add listing array key.
2757
                         * @param int $current_user->ID Current user ID.
2758
                         */
2759 2
                        $add_link = apply_filters('geodir_dashboard_link_add_listing', $add_link, $key, $current_user->ID);
2760
2761 2
                        $addlisting_links .= '<option ' . $selected . ' value="' . $add_link . '">' . __(ucfirst($name), 'geodirectory') . '</option>';
2762
2763 2
                    }
2764 2
                }
2765
2766 2
            }
2767
2768 View Code Duplication
            if ($addlisting_links != '') { ?>
2769
2770
                <li><select id="geodir_add_listing" class="chosen_select" onchange="window.location.href=this.value"
2771
                            option-autoredirect="1" name="geodir_add_listing" option-ajaxchosen="false"
2772
                            data-placeholder="<?php echo esc_attr(__('Add Listing', 'geodirectory')); ?>">
2773
                        <option value="" disabled="disabled" selected="selected" style='display:none;'><?php echo esc_attr(__('Add Listing', 'geodirectory')); ?></option>
2774
                        <?php echo $addlisting_links; ?>
2775
                    </select></li> <?php
2776
2777 2
            }
2778
2779 2
        }
2780
        // My Favourites in Dashboard
2781 2
        $show_favorite_link_user_dashboard = get_option('geodir_favorite_link_user_dashboard');
2782 2
        $user_favourite = geodir_user_favourite_listing_count();
2783
2784 2
        if (!empty($show_favorite_link_user_dashboard) && !empty($user_favourite)) {
2785
            $favourite_links = '';
2786
2787
            foreach ($post_types as $key => $postobj) {
0 ignored issues
show
Bug introduced by
The expression $post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
2788
                if (in_array($key, $show_favorite_link_user_dashboard) && array_key_exists($key, $user_favourite)) {
2789
                    $name = $postobj->labels->name;
2790
                    $post_type_link = geodir_getlink($author_link, array('stype' => $key, 'list' => 'favourite'), false);
2791
2792
                    $selected = '';
2793
2794 View Code Duplication
                    if (isset($_REQUEST['list']) && $_REQUEST['list'] == 'favourite' && isset($_REQUEST['stype']) && $_REQUEST['stype'] == $key && isset($_REQUEST['geodir_dashbord'])) {
2795
                        $selected = 'selected="selected"';
2796
                    }
2797
                    /**
2798
                     * Filter favorite listing link.
2799
                     *
2800
                     * @since 1.0.0
2801
                     * @param string $post_type_link Favorite listing link.
2802
                     * @param string $key Favorite listing array key.
2803
                     * @param int $current_user->ID Current user ID.
2804
                     */
2805
                    $post_type_link = apply_filters('geodir_dashboard_link_favorite_listing', $post_type_link, $key, $current_user->ID);
2806
2807
                    $favourite_links .= '<option ' . $selected . ' value="' . $post_type_link . '">' . __(ucfirst($name), 'geodirectory') . '</option>';
2808
                }
2809
            }
2810
2811 View Code Duplication
            if ($favourite_links != '') {
2812
                ?>
2813
                <li>
2814
                    <select id="geodir_my_favourites" class="chosen_select" onchange="window.location.href=this.value"
2815
                            option-autoredirect="1" name="geodir_my_favourites" option-ajaxchosen="false"
2816
                            data-placeholder="<?php echo esc_attr(__('My Favorites', 'geodirectory')); ?>">
2817
                        <option value="" disabled="disabled" selected="selected" style='display:none;'><?php echo esc_attr(__('My Favorites', 'geodirectory')); ?></option>
2818
                        <?php echo $favourite_links; ?>
2819
                    </select>
2820
                </li>
2821
            <?php
2822
            }
2823
        }
2824
2825
2826 2
        $show_listing_link_user_dashboard = get_option('geodir_listing_link_user_dashboard');
2827 2
        $user_listing = geodir_user_post_listing_count();
2828
2829 2
        if (!empty($show_listing_link_user_dashboard) && !empty($user_listing)) {
2830 2
            $listing_links = '';
2831
2832 2
            foreach ($post_types as $key => $postobj) {
0 ignored issues
show
Bug introduced by
The expression $post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
2833 2
                if (in_array($key, $show_listing_link_user_dashboard) && array_key_exists($key, $user_listing)) {
2834 2
                    $name = $postobj->labels->name;
2835 2
                    $listing_link = geodir_getlink($author_link, array('stype' => $key), false);
2836
2837 2
                    $selected = '';
2838 2 View Code Duplication
                    if (!isset($_REQUEST['list']) && isset($_REQUEST['geodir_dashbord']) && isset($_REQUEST['stype']) && $_REQUEST['stype'] == $key) {
2839 1
                        $selected = 'selected="selected"';
2840 1
                    }
2841
2842
                    /**
2843
                     * Filter my listing link.
2844
                     *
2845
                     * @since 1.0.0
2846
                     * @param string $listing_link My listing link.
2847
                     * @param string $key My listing array key.
2848
                     * @param int $current_user->ID Current user ID.
2849
                     */
2850 2
                    $listing_link = apply_filters('geodir_dashboard_link_my_listing', $listing_link, $key, $current_user->ID);
2851
2852 2
                    $listing_links .= '<option ' . $selected . ' value="' . $listing_link . '">' . __(ucfirst($name), 'geodirectory') . '</option>';
2853 2
                }
2854 2
            }
2855
2856 2 View Code Duplication
            if ($listing_links != '') {
2857
                ?>
2858
                <li>
2859
                    <select id="geodir_my_listings" class="chosen_select" onchange="window.location.href=this.value"
2860
                            option-autoredirect="1" name="geodir_my_listings" option-ajaxchosen="false"
2861
                            data-placeholder="<?php echo esc_attr(__('My Listings', 'geodirectory')); ?>">
2862
                        <option value="" disabled="disabled" selected="selected" style='display:none;'><?php echo esc_attr(__('My Listings', 'geodirectory')); ?></option>
2863
                        <?php echo $listing_links; ?>
2864
                    </select>
2865
                </li>
2866
            <?php
2867 2
            }
2868 2
        }
2869
2870 2
        $dashboard_link = ob_get_clean();
2871
        /**
2872
         * Filter dashboard links HTML.
2873
         *
2874
         * @since 1.0.0
2875
         * @param string $dashboard_link Dashboard links HTML.
2876
         */
2877 2
        echo apply_filters('geodir_dashboard_links', $dashboard_link);
2878 2
        echo '</ul>';
2879 2
    } else {
2880
        ?>
2881
        <?php
2882
        /**
2883
         * Filter signup form action link.
2884
         *
2885
         * @since 1.0.0
2886
         */
2887
        ?>
2888
        <form name="loginform" class="loginform1"
2889
              action="<?php echo geodir_login_url(); ?>"
2890
              method="post">
2891
            <div class="geodir_form_row"><input placeholder="<?php _e('Email', 'geodirectory'); ?>" name="log"
2892
                                                type="text" class="textfield user_login1"/> <span
2893
                    class="user_loginInfo"></span></div>
2894
            <div class="geodir_form_row"><input placeholder="<?php _e('Password', 'geodirectory'); ?>"
2895
                                                name="pwd" type="password"
2896
                                                class="textfield user_pass1 input-text"/><span
2897
                    class="user_passInfo"></span></div>
2898
2899
            <input type="hidden" name="redirect_to" value="<?php echo htmlspecialchars(geodir_curPageURL()); ?>"/>
2900
            <input type="hidden" name="testcookie" value="1"/>
2901
2902
            <div class="geodir_form_row clearfix"><input type="submit" name="submit"
2903
                                                         value="<?php echo SIGN_IN_BUTTON; ?>" class="b_signin"/>
2904
2905
                <p class="geodir-new-forgot-link">
2906
                    <?php
2907
                    /**
2908
                     * Filter signup page register form link.
2909
                     *
2910
                     * @since 1.0.0
2911
                     */
2912
                    ?>
2913
                    <a href="<?php echo geodir_login_url(array('signup' => true)); ?>"
2914
                       class="goedir-newuser-link"><?php echo NEW_USER_TEXT; ?></a>
2915
2916
                    <?php
2917
                    /**
2918
                     * Filter signup page forgot password form link.
2919
                     *
2920
                     * @since 1.0.0
2921
                     */
2922
                    ?>
2923
                    <a href="<?php echo geodir_login_url(array('forgot' => true)); ?>"
2924
                       class="goedir-forgot-link"><?php echo FORGOT_PW_TEXT; ?></a></p></div>
2925
        </form>
2926
    <?php }
2927
2928 2
    echo $after_widget;
2929 2
}
2930
2931
2932
/**
2933
 * Generates popular postview HTML.
2934
 *
2935
 * @since 1.0.0
2936
 * @since 1.5.1 View all link fixed for location filter disabled.
2937
 * @package GeoDirectory
2938
 * @global object $post The current post object.
2939
 * @global string $gridview_columns_widget The girdview style of the listings for widget.
2940
 * @global bool $geodir_is_widget_listing Is this a widget listing?. Default: false.
2941
 * @global object $gd_session GeoDirectory Session object.
2942
 *
2943
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2944
 * @param array|string $instance The settings for the particular instance of the widget.
2945
 */
2946
function geodir_popular_postview_output($args = '', $instance = '') {
2947 2
    global $gd_session;
2948
	
2949
    // prints the widget
2950 2
    extract($args, EXTR_SKIP);
2951
2952 2
    echo $before_widget;
2953
2954
    /** This filter is documented in geodirectory_widgets.php */
2955 2
    $title = empty($instance['title']) ? geodir_ucwords($instance['category_title']) : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2956
    /**
2957
     * Filter the widget post type.
2958
     *
2959
     * @since 1.0.0
2960
     * @param string $instance['post_type'] Post type of listing.
2961
     */
2962 2
    $post_type = empty($instance['post_type']) ? 'gd_place' : apply_filters('widget_post_type', $instance['post_type']);
2963
    /**
2964
     * Filter the widget's term.
2965
     *
2966
     * @since 1.0.0
2967
     * @param string $instance['category'] Filter by term. Can be any valid term.
2968
     */
2969 2
    $category = empty($instance['category']) ? '0' : apply_filters('widget_category', $instance['category']);
2970
    /**
2971
     * Filter the widget listings limit.
2972
     *
2973
     * @since 1.0.0
2974
     * @param string $instance['post_number'] Number of listings to display.
2975
     */
2976 2
    $post_number = empty($instance['post_number']) ? '5' : apply_filters('widget_post_number', $instance['post_number']);
2977
    /**
2978
     * Filter widget's "layout" type.
2979
     *
2980
     * @since 1.0.0
2981
     * @param string $instance['layout'] Widget layout type.
2982
     */
2983 2
    $layout = empty($instance['layout']) ? 'gridview_onehalf' : apply_filters('widget_layout', $instance['layout']);
2984
    /**
2985
     * Filter widget's "add_location_filter" value.
2986
     *
2987
     * @since 1.0.0
2988
     * @param string|bool $instance['add_location_filter'] Do you want to add location filter? Can be 1 or 0.
2989
     */
2990 2
    $add_location_filter = empty($instance['add_location_filter']) ? '0' : apply_filters('widget_add_location_filter', $instance['add_location_filter']);
2991
    /**
2992
     * Filter widget's listing width.
2993
     *
2994
     * @since 1.0.0
2995
     * @param string $instance['listing_width'] Listing width.
2996
     */
2997 2
    $listing_width = empty($instance['listing_width']) ? '' : apply_filters('widget_listing_width', $instance['listing_width']);
2998
    /**
2999
     * Filter widget's "list_sort" type.
3000
     *
3001
     * @since 1.0.0
3002
     * @param string $instance['list_sort'] Listing sort by type.
3003
     */
3004 2
    $list_sort = empty($instance['list_sort']) ? 'latest' : apply_filters('widget_list_sort', $instance['list_sort']);
3005 2
    $use_viewing_post_type = !empty($instance['use_viewing_post_type']) ? true : false;
3006
3007
    // set post type to current viewing post type
3008 2 View Code Duplication
    if ($use_viewing_post_type) {
3009 1
        $current_post_type = geodir_get_current_posttype();
3010 1
        if ($current_post_type != '' && $current_post_type != $post_type) {
3011
            $post_type = $current_post_type;
3012
            $category = array(); // old post type category will not work for current changed post type
3013
        }
3014 1
    }
3015
    // replace widget title dynamically
3016 2
    $posttype_plural_label = __(get_post_type_plural_label($post_type), 'geodirectory');
3017 2
    $posttype_singular_label = __(get_post_type_singular_label($post_type), 'geodirectory');
3018
3019 2
    $title = str_replace("%posttype_plural_label%", $posttype_plural_label, $title);
3020 2
    $title = str_replace("%posttype_singular_label%", $posttype_singular_label, $title);
3021
3022 2 View Code Duplication
    if (isset($instance['character_count'])) {
3023
        /**
3024
         * Filter the widget's excerpt character count.
3025
         *
3026
         * @since 1.0.0
3027
         * @param int $instance['character_count'] Excerpt character count.
3028
         */
3029 1
        $character_count = apply_filters('widget_list_character_count', $instance['character_count']);
3030 1
    } else {
3031 1
        $character_count = '';
3032
    }
3033
3034 2
    if (empty($title) || $title == 'All') {
3035 2
        $title .= ' ' . __(get_post_type_plural_label($post_type), 'geodirectory');
3036 2
    }
3037
3038 2
    $location_url = array();
3039 2
    $city = get_query_var('gd_city');
3040 2
    if (!empty($city)) {
3041
        $country = get_query_var('gd_country');
3042
        $region = get_query_var('gd_region');
3043
3044
        $geodir_show_location_url = get_option('geodir_show_location_url');
3045
3046
        if ($geodir_show_location_url == 'all') {
3047
            if ($country != '') {
3048
                $location_url[] = $country;
3049
            }
3050
3051
            if ($region != '') {
3052
                $location_url[] = $region;
3053
            }
3054
        } else if ($geodir_show_location_url == 'country_city') {
3055
            if ($country != '') {
3056
                $location_url[] = $country;
3057
            }
3058
        } else if ($geodir_show_location_url == 'region_city') {
3059
            if ($region != '') {
3060
                $location_url[] = $region;
3061
            }
3062
        }
3063
3064
        $location_url[] = $city;
3065
    }
3066
3067 2
    $location_url = implode('/', $location_url);
3068 2
    $skip_location = false;
3069 2
    if (!$add_location_filter && $gd_session->get('gd_multi_location')) {
3070
        $skip_location = true;
3071
        $gd_session->un_set('gd_multi_location');
3072
    }
3073
3074 2
    if (get_option('permalink_structure')) {
3075
        $viewall_url = get_post_type_archive_link($post_type);
3076
    } else {
3077 2
        $viewall_url = get_post_type_archive_link($post_type);
3078
    }
3079
3080 2
    if (!empty($category) && $category[0] != '0') {
3081
        global $geodir_add_location_url;
3082
3083
        $geodir_add_location_url = '0';
3084
3085
        if ($add_location_filter != '0') {
3086
            $geodir_add_location_url = '1';
3087
        }
3088
3089
        $viewall_url = get_term_link((int)$category[0], $post_type . 'category');
3090
3091
        $geodir_add_location_url = NULL;
3092
    }
3093 2
    if ($skip_location) {
3094
        $gd_session->set('gd_multi_location', 1);
3095
    }
3096
3097 2
    if(is_wp_error( $viewall_url  )){$viewall_url = '';}
3098
3099
    $query_args = array(
3100 2
        'posts_per_page' => $post_number,
3101 2
        'is_geodir_loop' => true,
3102 2
        'gd_location' => $add_location_filter ? true : false,
3103 2
        'post_type' => $post_type,
3104
        'order_by' => $list_sort
3105 2
    );
3106
3107 2
    if ($character_count) {
3108 1
        $query_args['excerpt_length'] = $character_count;
3109 1
    }
3110
3111 2
    if (!empty($instance['show_featured_only'])) {
3112 1
        $query_args['show_featured_only'] = 1;
3113 1
    }
3114
3115 2
    if (!empty($instance['show_special_only'])) {
3116
        $query_args['show_special_only'] = 1;
3117
    }
3118
3119 2 View Code Duplication
    if (!empty($instance['with_pics_only'])) {
3120
        $query_args['with_pics_only'] = 0;
3121
        $query_args['featured_image_only'] = 1;
3122
    }
3123
3124 2
    if (!empty($instance['with_videos_only'])) {
3125
        $query_args['with_videos_only'] = 1;
3126
    }
3127 2
    $with_no_results = !empty($instance['without_no_results']) ? false : true;
3128
3129 2 View Code Duplication
    if (!empty($category) && $category[0] != '0') {
3130
        $category_taxonomy = geodir_get_taxonomies($post_type);
3131
3132
        ######### WPML #########
3133
        if (function_exists('icl_object_id')) {
3134
            $category = gd_lang_object_ids($category, $category_taxonomy[0]);
3135
        }
3136
        ######### WPML #########
3137
3138
        $tax_query = array(
3139
            'taxonomy' => $category_taxonomy[0],
3140
            'field' => 'id',
3141
            'terms' => $category
3142
        );
3143
3144
        $query_args['tax_query'] = array($tax_query);
3145
    }
3146
3147 2
    global $gridview_columns_widget, $geodir_is_widget_listing;
3148
3149 2
    $widget_listings = geodir_get_widget_listings($query_args);
3150
3151 2
    if (!empty($widget_listings) || $with_no_results) {
3152
        ?>
3153
        <div class="geodir_locations geodir_location_listing">
3154
3155
            <?php
3156
            /**
3157
             * Called before the div containing the title and view all link in popular post view widget.
3158
             *
3159
             * @since 1.0.0
3160
             */
3161
            do_action('geodir_before_view_all_link_in_widget'); ?>
3162
            <div class="geodir_list_heading clearfix">
3163
                <?php echo $before_title . $title . $after_title; ?>
3164
                <a href="<?php echo $viewall_url; ?>"
3165
                   class="geodir-viewall"><?php _e('View all', 'geodirectory'); ?></a>
3166
            </div>
3167
            <?php
3168
            /**
3169
             * Called after the div containing the title and view all link in popular post view widget.
3170
             *
3171
             * @since 1.0.0
3172
             */
3173
            do_action('geodir_after_view_all_link_in_widget'); ?>
3174
            <?php
3175 2 View Code Duplication
            if (strstr($layout, 'gridview')) {
3176 2
                $listing_view_exp = explode('_', $layout);
3177 2
                $gridview_columns_widget = $layout;
3178 2
                $layout = $listing_view_exp[0];
3179 2
            } else {
3180
                $gridview_columns_widget = '';
3181
            }
3182
3183
            /**
3184
             * Filter the widget listing listview template path.
3185
             *
3186
             * @since 1.0.0
3187
             */
3188 2
            $template = apply_filters("geodir_template_part-widget-listing-listview", geodir_locate_template('widget-listing-listview'));
3189 2
            if (!isset($character_count)) {
3190
                /**
3191
                 * Filter the widget's excerpt character count.
3192
                 *
3193
                 * @since 1.0.0
3194
                 * @param int $instance['character_count'] Excerpt character count.
3195
                 */
3196
                $character_count = $character_count == '' ? 50 : apply_filters('widget_character_count', $character_count);
3197
            }
3198
3199 2
            global $post, $map_jason, $map_canvas_arr;
3200
3201 2
            $current_post = $post;
3202 2
            $current_map_jason = $map_jason;
3203 2
            $current_map_canvas_arr = $map_canvas_arr;
3204 2
            $geodir_is_widget_listing = true;
3205
3206
            /**
3207
             * Includes related listing listview template.
3208
             *
3209
             * @since 1.0.0
3210
             */
3211 2
            include($template);
3212
3213 2
            $geodir_is_widget_listing = false;
3214
3215 2
            $GLOBALS['post'] = $current_post;
3216 2
            if (!empty($current_post))
3217 2
                setup_postdata($current_post);
3218 2
            $map_jason = $current_map_jason;
3219 2
            $map_canvas_arr = $current_map_canvas_arr;
3220
            ?>
3221
        </div>
3222
    <?php
3223 2
    }
3224 2
    echo $after_widget;
3225
3226 2
}
3227
3228
3229
/*-----------------------------------------------------------------------------------*/
3230
/*  Review count functions
3231
/*-----------------------------------------------------------------------------------*/
3232
/**
3233
 * Count reviews by term ID.
3234
 *
3235
 * @since 1.0.0
3236
 * @since 1.5.1 Added filter to change SQL.
3237
 * @package GeoDirectory
3238
 * @global object $wpdb WordPress Database object.
3239
 * @global string $plugin_prefix Geodirectory plugin table prefix.
3240
 * @param int $term_id The term ID.
3241
 * @param int $taxonomy The taxonomy Id.
3242
 * @param string $post_type The post type.
3243
 * @return int Reviews count.
3244
 */
3245
function geodir_count_reviews_by_term_id($term_id, $taxonomy, $post_type)
3246
{
3247 9
    global $wpdb, $plugin_prefix;
3248
3249 9
    $detail_table = $plugin_prefix . $post_type . '_detail';
3250
3251 9
    $sql = "SELECT COALESCE(SUM(rating_count),0) FROM " . $detail_table . " WHERE post_status = 'publish' AND rating_count > 0 AND FIND_IN_SET(" . $term_id . ", " . $taxonomy . ")";
3252
3253
    /**
3254
     * Filter count review sql query.
3255
     *
3256
     * @since 1.5.1
3257
     * @param string $sql Database sql query..
3258
     * @param int $term_id The term ID.
3259
     * @param int $taxonomy The taxonomy Id.
3260
     * @param string $post_type The post type.
3261
     */
3262 9
    $sql = apply_filters('geodir_count_reviews_by_term_sql', $sql, $term_id, $taxonomy, $post_type);
3263
3264 9
    $count = $wpdb->get_var($sql);
3265
3266 9
    return $count;
3267
}
3268
3269
/**
3270
 * Count reviews by terms.
3271
 *
3272
 * @since 1.0.0
3273
 * @package GeoDirectory
3274
 * @param bool $force_update Force update option value?. Default.false.
3275
 * @return array Term array data.
3276
 */
3277
function geodir_count_reviews_by_terms($force_update = false)
3278
{
3279
    /**
3280
     * Filter review count option data.
3281
     *
3282
     * @since 1.0.0
3283
     * @param bool $force_update Force update option value?. Default.false.
3284
     */
3285 10
    $option_data = apply_filters('geodir_count_reviews_by_terms_before', '', $force_update);
3286 10
    if (!empty($option_data)) {
3287
        return $option_data;
3288
    }
3289
3290 10
    $option_data = get_option('geodir_global_review_count');
3291
3292 10
    if (!$option_data OR $force_update) {
3293 9
        $post_types = geodir_get_posttypes();
3294 9
        $term_array = array();
3295 9
        foreach ($post_types as $post_type) {
0 ignored issues
show
Bug introduced by
The expression $post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
3296
3297 9
            $taxonomy = geodir_get_taxonomies($post_type);
3298 9
            $taxonomy = $taxonomy[0];
3299
3300
            $args = array(
3301
                'hide_empty' => false
3302 9
            );
3303
3304 9
            $terms = get_terms($taxonomy, $args);
3305
3306 9
            foreach ($terms as $term) {
3307 9
                $count = geodir_count_reviews_by_term_id($term->term_id, $taxonomy, $post_type);
3308 9
                $children = get_term_children($term->term_id, $taxonomy);
0 ignored issues
show
Unused Code introduced by
$children 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...
3309
                /*if ( is_array( $children ) ) {
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...
3310
					foreach ( $children as $child_id ) {
3311
						$child_count = geodir_count_reviews_by_term_id($child_id, $taxonomy, $post_type);
3312
						$count = $count + $child_count;
3313
					}
3314
				}*/
3315 9
                $term_array[$term->term_id] = $count;
3316 9
            }
3317 9
        }
3318
3319 9
        update_option('geodir_global_review_count', $term_array);
3320
        //clear cache
3321 9
        wp_cache_delete('geodir_global_review_count');
3322 9
        return $term_array;
3323
    } else {
3324 1
        return $option_data;
3325
    }
3326
}
3327
3328
/**
3329
 * Force update review count.
3330
 *
3331
 * @since 1.0.0
3332
 * @package GeoDirectory
3333
 * @return bool
3334
 */
3335
function geodir_term_review_count_force_update($new_status, $old_status='', $post='')
3336
{
3337 9
    if(isset($_REQUEST['action']) && $_REQUEST['action']=='geodir_import_export'){return;}//do not run if importing listings
3338
3339 9 View Code Duplication
    if(isset($post->post_type) && ($post->post_type=='nav_menu_item' || $post->post_type=='page' || $post->post_type=='post')){
3340 2
        return;
3341
    }
3342 9
    if($new_status!=$old_status) {
3343 9
        geodir_count_reviews_by_terms(true);
3344 9
    }
3345 9
    return true;
3346
}
3347
3348
3349
/*-----------------------------------------------------------------------------------*/
3350
/*  Term count functions
3351
/*-----------------------------------------------------------------------------------*/
3352
/**
3353
 * Count posts by term.
3354
 *
3355
 * @since 1.0.0
3356
 * @package GeoDirectory
3357
 * @param array $data Count data array.
3358
 * @param object $term The term object.
3359
 * @return int Post count.
3360
 */
3361
function geodir_count_posts_by_term($data, $term)
3362
{
3363
3364
    if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
3365
        if (isset($data[$term->term_id])) {
3366
            return $data[$term->term_id];
3367
        } else {
3368
            return 0;
3369
        }
3370
    } else {
3371
        return $term->count;
3372
    }
3373
}
3374
3375
/**
3376
 * Sort terms object by post count.
3377
 *
3378
 * @since 1.0.0
3379
 * @package GeoDirectory
3380
 * param array $terms An array of term objects.
3381
 * @return array Sorted terms array.
3382
 */
3383
function geodir_sort_terms_by_count($terms)
3384
{
3385 4
    usort($terms, "geodir_sort_by_count_obj");
3386 4
    return $terms;
3387
}
3388
3389
/**
3390
 * Sort terms object by review count.
3391
 *
3392
 * @since 1.0.0
3393
 * @package GeoDirectory
3394
 * @param array $terms An array of term objects.
3395
 * @return array Sorted terms array.
3396
 */
3397
function geodir_sort_terms_by_review_count($terms)
3398
{
3399 1
    usort($terms, "geodir_sort_by_review_count_obj");
3400 1
    return $terms;
3401
}
3402
3403
/**
3404
 * Sort terms either by post count or review count.
3405
 *
3406
 * @since 1.0.0
3407
 * @package GeoDirectory
3408
 * @param array $terms An array of term objects.
3409
 * @param string $sort The sort type. Can be count (Post Count) or review_count. Default. count.
3410
 * @return array Sorted terms array.
3411
 */
3412
function geodir_sort_terms($terms, $sort = 'count')
3413
{
3414 5
    if ($sort == 'count') {
3415 4
        return geodir_sort_terms_by_count($terms);
3416
    }
3417 1
    if ($sort == 'review_count') {
3418 1
        return geodir_sort_terms_by_review_count($terms);
3419
    }
3420
}
3421
3422
/*-----------------------------------------------------------------------------------*/
3423
/*  Utils
3424
/*-----------------------------------------------------------------------------------*/
3425
/**
3426
 * Compares post count from array for sorting.
3427
 *
3428
 * @since 1.0.0
3429
 * @package GeoDirectory
3430
 * @param array $a The left side array to compare.
3431
 * @param array $b The right side array to compare.
3432
 * @return bool
3433
 */
3434
function geodir_sort_by_count($a, $b)
3435
{
3436
    return $a['count'] < $b['count'];
3437
}
3438
3439
/**
3440
 * Compares post count from object for sorting.
3441
 *
3442
 * @since 1.0.0
3443
 * @package GeoDirectory
3444
 * @param object $a The left side object to compare.
3445
 * @param object $b The right side object to compare.
3446
 * @return bool
3447
 */
3448
function geodir_sort_by_count_obj($a, $b)
3449
{
3450 4
    return $a->count < $b->count;
3451
}
3452
3453
/**
3454
 * Compares review count from object for sorting.
3455
 *
3456
 * @since 1.0.0
3457
 * @package GeoDirectory
3458
 * @param object $a The left side object to compare.
3459
 * @param object $b The right side object to compare.
3460
 * @return bool
3461
 */
3462
function geodir_sort_by_review_count_obj($a, $b)
3463
{
3464 1
    return $a->review_count < $b->review_count;
3465
}
3466
3467
/**
3468
 * Load geodirectory plugin textdomain.
3469
 *
3470
 * @since 1.4.2
3471
 * @package GeoDirectory
3472
 */
3473
function geodir_load_textdomain() {
3474
    /**
3475
     * Filter the plugin locale.
3476
     *
3477
     * @since 1.4.2
3478
     * @package GeoDirectory
3479
     */
3480
    $locale = apply_filters('plugin_locale', get_locale(), 'geodirectory');
3481
3482
    load_textdomain('geodirectory', WP_LANG_DIR . '/' . 'geodirectory' . '/' . 'geodirectory' . '-' . $locale . '.mo');
3483
    load_plugin_textdomain('geodirectory', false, plugin_basename(dirname(dirname(__FILE__))) . '/geodirectory-languages');
3484
3485
    /**
3486
     * Define language constants.
3487
     *
3488
     * @since 1.0.0
3489
     */
3490
    require_once(geodir_plugin_path() . '/language.php');
3491
3492
    $language_file = geodir_plugin_path() . '/db-language.php';
3493
3494
    // Load language string file if not created yet
3495
    if (!file_exists($language_file)) {
3496
        geodirectory_load_db_language();
3497
    }
3498
3499
    if (file_exists($language_file)) {
3500
        /**
3501
         * Language strings from database.
3502
         *
3503
         * @since 1.4.2
3504
         */
3505
        try {
3506
            require_once($language_file);
3507
        } catch(Exception $e) {
3508
            error_log('Language Error: ' . $e->getMessage());
3509
        }
3510
    }
3511
}
3512
3513
/**
3514
 * Load language strings in to file to translate via po editor
3515
 *
3516
 * @since 1.4.2
3517
 * @package GeoDirectory
3518
 *
3519
 * @global null|object $wp_filesystem WP_Filesystem object.
3520
 *
3521
 * @return bool True if file created otherwise false
3522
 */
3523
function geodirectory_load_db_language() {
3524 1
    global $wp_filesystem;
3525 1
    if( empty( $wp_filesystem ) ) {
3526 1
        require_once( ABSPATH .'/wp-admin/includes/file.php' );
3527 1
        WP_Filesystem();
3528 1
        global $wp_filesystem;
3529 1
    }
3530
3531 1
    $language_file = geodir_plugin_path() . '/db-language.php';
3532
3533 1
    if(is_file($language_file) && !is_writable($language_file))
3534 1
        return false; // Not possible to create.
3535
3536 1
    if(!is_file($language_file) && !is_writable(dirname($language_file)))
3537 1
        return false; // Not possible to create.
3538
3539 1
    $contents_strings = array();
3540
3541
    /**
3542
     * Filter the language string from database to translate via po editor
3543
     *
3544
     * @since 1.4.2
3545
     *
3546
     * @param array $contents_strings Array of strings.
3547
     */
3548 1
    $contents_strings = apply_filters('geodir_load_db_language', $contents_strings);
3549
3550 1
    $contents_strings = array_unique($contents_strings);
3551
3552 1
    $contents_head = array();
3553 1
    $contents_head[] = "<?php";
3554 1
    $contents_head[] = "/**";
3555 1
    $contents_head[] = " * Translate language string stored in database. Ex: Custom Fields";
3556 1
    $contents_head[] = " *";
3557 1
    $contents_head[] = " * @package GeoDirectory";
3558 1
    $contents_head[] = " * @since 1.4.2";
3559 1
    $contents_head[] = " */";
3560 1
    $contents_head[] = "";
3561 1
    $contents_head[] = "// Language keys";
3562
3563 1
    $contents_foot = array();
3564 1
    $contents_foot[] = "";
3565 1
    $contents_foot[] = "";
3566
3567 1
    $contents = implode(PHP_EOL, $contents_head);
3568
3569 1
    if (!empty($contents_strings)) {
3570 1
        foreach ( $contents_strings as $string ) {
3571 1
            if (is_scalar($string) && $string != '') {
3572 1
                $string = str_replace("'", "\'", $string);
3573 1
                $contents .= PHP_EOL . "__('" . $string . "', 'geodirectory');";
3574 1
            }
3575 1
        }
3576 1
    }
3577
3578 1
    $contents .= implode(PHP_EOL, $contents_foot);
3579
3580 1
    if($wp_filesystem->put_contents( $language_file, $contents, FS_CHMOD_FILE))
3581 1
        return false; // Failure; could not write file.
3582
3583
    return true;
3584
}
3585
3586
/**
3587
 * Get the custom fields texts for translation
3588
 *
3589
 * @since 1.4.2
3590
 * @since 1.5.7 Option values are translatable via db translation.
3591
 * @package GeoDirectory
3592
 *
3593
 * @global object $wpdb WordPress database abstraction object.
3594
 *
3595
 * @param  array $translation_texts Array of text strings.
3596
 * @return array Translation texts.
3597
 */
3598
function geodir_load_custom_field_translation($translation_texts = array()) {
3599 1
    global $wpdb;
3600
3601
    // Custom fields table
3602 1
    $sql = "SELECT admin_title, admin_desc, site_title, clabels, required_msg, default_value, option_values FROM " . GEODIR_CUSTOM_FIELDS_TABLE;
3603 1
    $rows = $wpdb->get_results($sql);
3604
3605 1
    if (!empty($rows)) {
3606 1
        foreach($rows as $row) {
3607 1
            if (!empty($row->admin_title))
3608 1
                $translation_texts[] = stripslashes_deep($row->admin_title);
3609
			
3610 1
            if (!empty($row->admin_desc))
3611 1
                $translation_texts[] = stripslashes_deep($row->admin_desc);
3612
3613 1
            if (!empty($row->site_title))
3614 1
                $translation_texts[] = stripslashes_deep($row->site_title);
3615
3616 1
            if (!empty($row->clabels))
3617 1
                $translation_texts[] = stripslashes_deep($row->clabels);
3618
3619 1
            if (!empty($row->required_msg))
3620 1
                $translation_texts[] = stripslashes_deep($row->required_msg);
3621
			
3622 1
			if (!empty($row->default_value))
3623 1
                $translation_texts[] = stripslashes_deep($row->default_value);
3624
			
3625 1
			if (!empty($row->option_values)) {
3626 1
				$option_values = geodir_string_values_to_options(stripslashes_deep($row->option_values));
3627
				
3628 1
				if (!empty($option_values)) {
3629 1
					foreach ($option_values as $option_value) {
3630 1
						if (!empty($option_value['label'])) {
3631 1
							$translation_texts[] = $option_value['label'];
3632 1
						}
3633 1
					}
3634 1
				}
3635 1
			}
3636 1
        }
3637 1
    }
3638
	
3639
    // Custom sorting fields table
3640 1
    $sql = "SELECT site_title, asc_title, desc_title FROM " . GEODIR_CUSTOM_SORT_FIELDS_TABLE;
3641 1
    $rows = $wpdb->get_results($sql);
3642
3643 1 View Code Duplication
    if (!empty($rows)) {
3644
        foreach($rows as $row) {
3645
            if (!empty($row->site_title))
3646
                $translation_texts[] = stripslashes_deep($row->site_title);
3647
3648
            if (!empty($row->asc_title))
3649
                $translation_texts[] = stripslashes_deep($row->asc_title);
3650
3651
            if (!empty($row->desc_title))
3652
                $translation_texts[] = stripslashes_deep($row->desc_title);
3653
        }
3654
    }
3655
	
3656
	// Advance search filter fields table
3657 1
	if (defined('GEODIR_ADVANCE_SEARCH_TABLE')) {
3658
		$sql = "SELECT field_site_name, front_search_title, field_desc FROM " . GEODIR_ADVANCE_SEARCH_TABLE;
3659
		$rows = $wpdb->get_results($sql);
3660
3661 View Code Duplication
		if (!empty($rows)) {
3662
			foreach($rows as $row) {
3663
				if (!empty($row->field_site_name))
3664
					$translation_texts[] = stripslashes_deep($row->field_site_name);
3665
3666
				if (!empty($row->front_search_title))
3667
					$translation_texts[] = stripslashes_deep($row->front_search_title);
3668
3669
				if (!empty($row->field_desc))
3670
					$translation_texts[] = stripslashes_deep($row->field_desc);
3671
			}
3672
		}
3673
	}
3674
3675 1
    $translation_texts = !empty($translation_texts) ? array_unique($translation_texts) : $translation_texts;
3676
3677 1
    return $translation_texts;
3678
}
3679
3680
/**
3681
 * Retrieve list of mime types and file extensions allowed for file upload.
3682
 *
3683
 * @since 1.4.7
3684
 * @package GeoDirectory
3685
 *
3686
 * @return array Array of mime types.
3687
 */
3688
function geodir_allowed_mime_types() {
3689
    /**
3690
     * Filter the list of mime types and file extensions allowed for file upload.
3691
     *
3692
     * @since 1.4.7
3693
     * @package GeoDirectory
3694
     *
3695
     * @param array $geodir_allowed_mime_types and file extensions.
3696
     */
3697
    return apply_filters( 'geodir_allowed_mime_types', array(
3698
            'Image' => array( // Image formats.
3699
                'jpg' => 'image/jpeg',
3700
                'jpe' => 'image/jpeg',
3701
                'jpeg' => 'image/jpeg',
3702
                'gif' => 'image/gif',
3703
                'png' => 'image/png',
3704
                'bmp' => 'image/bmp',
3705
                'ico' => 'image/x-icon',
3706
            ),
3707
            'Video' => array( // Video formats.
3708
                'asf' => 'video/x-ms-asf',
3709
                'avi' => 'video/avi',
3710
                'flv' => 'video/x-flv',
3711
                'mkv' => 'video/x-matroska',
3712
                'mp4' => 'video/mp4',
3713
                'mpeg' => 'video/mpeg',
3714
                'mpg' => 'video/mpeg',
3715
                'wmv' => 'video/x-ms-wmv',
3716
                '3gp' => 'video/3gpp',
3717
            ),
3718
            'Audio' => array( // Audio formats.
3719
                'ogg' => 'audio/ogg',
3720
                'mp3' => 'audio/mpeg',
3721
                'wav' => 'audio/wav',
3722
                'wma' => 'audio/x-ms-wma',
3723
            ),
3724
            'Text' => array( // Text formats.
3725
                'css' => 'text/css',
3726
                'csv' => 'text/csv',
3727
                'htm' => 'text/html',
3728
                'html' => 'text/html',
3729
                'txt' => 'text/plain',
3730
                'rtx' => 'text/richtext',
3731
                'vtt' => 'text/vtt',
3732
            ),
3733
            'Application' => array( // Application formats.
3734
                'doc' => 'application/msword',
3735
                'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3736
                'exe' => 'application/x-msdownload',
3737
                'js' => 'application/javascript',
3738
                'odt' => 'application/vnd.oasis.opendocument.text',
3739
                'pdf' => 'application/pdf',
3740
                'pot' => 'application/vnd.ms-powerpoint',
3741
                'ppt' => 'application/vnd.ms-powerpoint',
3742
                'pptx' => 'application/vnd.ms-powerpoint',
3743
                'psd' => 'application/octet-stream',
3744
                'rar' => 'application/rar',
3745
                'rtf' => 'application/rtf',
3746
                'swf' => 'application/x-shockwave-flash',
3747
                'tar' => 'application/x-tar',
3748
                'xls' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3749
                'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3750
                'zip' => 'application/zip',
3751
            )
3752
        )
3753
    );
3754
}
3755
3756
/**
3757
 * Retrieve list of user display name for user id.
3758
 *
3759
 * @since 1.5.0
3760
 *
3761
 * @param  string $user_id The WP user id.
3762
 * @return string User display name.
3763
 */
3764
function geodir_get_client_name($user_id) {
3765 9
    $client_name = '';
3766
3767 9
    $user_data = get_userdata($user_id);
3768
3769 9
    if (!empty($user_data)) {
3770 2
        if (isset($user_data->display_name) && trim($user_data->display_name) != '') {
3771 2
            $client_name = trim($user_data->display_name);
3772 2
        } else if (isset($user_data->user_nicename) && trim($user_data->user_nicename) != '') {
3773
            $client_name = trim($user_data->user_nicename);
3774
        } else {
3775
            $client_name = trim($user_data->user_login);
3776
        }
3777 2
    }
3778
3779 9
    return $client_name;
3780
}
3781
3782
3783
3784
3785
3786
add_filter('wpseo_replacements','geodir_wpseo_replacements',10,1);
3787
/*
3788
 * Add location variables to wpseo replacements.
3789
 *
3790
 * @since 1.5.4
3791
 */
3792
function geodir_wpseo_replacements($vars){
3793
3794
    global $wp;
3795
    $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...
3796
    // location variables
3797
    $gd_post_type = geodir_get_current_posttype();
3798
    $location_array = geodir_get_current_location_terms('query_vars', $gd_post_type);
3799
    /**
3800
     * Filter the title variables location variables array
3801
     *
3802
     * @since 1.5.5
3803
     * @package GeoDirectory
3804
     * @param array $location_array The array of location variables.
3805
     * @param array $vars The page title variables.
3806
     */
3807
    $location_array = apply_filters('geodir_filter_title_variables_location_arr_seo',$location_array, $vars);
3808
    $location_titles = array();
3809 View Code Duplication
    if(get_query_var( 'gd_country_full' )){
3810
        if(get_query_var( 'gd_country_full' )){$location_array['gd_country'] = get_query_var( 'gd_country_full' );}
3811
        if(get_query_var( 'gd_region_full' )){$location_array['gd_region'] = get_query_var( 'gd_region_full' );}
3812
        if(get_query_var( 'gd_city_full' )){$location_array['gd_city'] = get_query_var( 'gd_city_full' );}
3813
    }
3814
    $location_single = '';
3815
    $gd_country = (isset($wp->query_vars['gd_country']) && $wp->query_vars['gd_country'] != '') ? $wp->query_vars['gd_country'] : '';
3816
    $gd_region = (isset($wp->query_vars['gd_region']) && $wp->query_vars['gd_region'] != '') ? $wp->query_vars['gd_region'] : '';
3817
    $gd_city = (isset($wp->query_vars['gd_city']) && $wp->query_vars['gd_city'] != '') ? $wp->query_vars['gd_city'] : '';
3818
3819
    $gd_country_actual = $gd_region_actual = $gd_city_actual = '';
3820
3821 View Code Duplication
    if (function_exists('get_actual_location_name')) {
3822
        $gd_country_actual = $gd_country != '' ? get_actual_location_name('country', $gd_country, true) : $gd_country;
3823
        $gd_region_actual = $gd_region != '' ? get_actual_location_name('region', $gd_region) : $gd_region;
3824
        $gd_city_actual = $gd_city != '' ? get_actual_location_name('city', $gd_city) : $gd_city;
3825
    }
3826
3827 View Code Duplication
    if ($gd_city != '') {
3828
        if ($gd_city_actual != '') {
3829
            $gd_city = $gd_city_actual;
3830
        } else {
3831
            $gd_city = preg_replace('/-(\d+)$/', '', $gd_city);
3832
            $gd_city = preg_replace('/[_-]/', ' ', $gd_city);
3833
            $gd_city = __(geodir_ucwords($gd_city), 'geodirectory');
3834
        }
3835
        $location_single = $gd_city;
3836
3837
    } else if ($gd_region != '') {
3838
        if ($gd_region_actual != '') {
3839
            $gd_region = $gd_region_actual;
3840
        } else {
3841
            $gd_region = preg_replace('/-(\d+)$/', '', $gd_region);
3842
            $gd_region = preg_replace('/[_-]/', ' ', $gd_region);
3843
            $gd_region = __(geodir_ucwords($gd_region), 'geodirectory');
3844
        }
3845
3846
        $location_single = $gd_region;
3847
    } else if ($gd_country != '') {
3848
        if ($gd_country_actual != '') {
3849
            $gd_country = $gd_country_actual;
3850
        } else {
3851
            $gd_country = preg_replace('/-(\d+)$/', '', $gd_country);
3852
            $gd_country = preg_replace('/[_-]/', ' ', $gd_country);
3853
            $gd_country = __(geodir_ucwords($gd_country), 'geodirectory');
3854
        }
3855
3856
        $location_single = $gd_country;
3857
    }
3858
3859 View Code Duplication
    if (!empty($location_array)) {
3860
3861
        $actual_location_name = function_exists('get_actual_location_name') ? true : false;
3862
        $location_array = array_reverse($location_array);
3863
3864
        foreach ($location_array as $location_type => $location) {
3865
            $gd_location_link_text = preg_replace('/-(\d+)$/', '', $location);
3866
            $gd_location_link_text = preg_replace('/[_-]/', ' ', $gd_location_link_text);
3867
3868
            $location_name = geodir_ucwords($gd_location_link_text);
3869
            $location_name = __($location_name, 'geodirectory');
3870
3871
            if ($actual_location_name) {
3872
                $location_type = strpos($location_type, 'gd_') === 0 ? substr($location_type, 3) : $location_type;
3873
                $location_name = get_actual_location_name($location_type, $location, true);
3874
            }
3875
3876
            $location_titles[] = $location_name;
3877
        }
3878
        if (!empty($location_titles)) {
3879
            $location_titles = array_unique($location_titles);
3880
        }
3881
    }
3882
3883
3884
    if(!empty($location_titles)) {
3885
        $vars['%%location%%'] = implode(", ", $location_titles);
3886
    }
3887
3888
3889
    if(!empty($location_titles)) {
3890
        $vars['%%in_location%%'] = __('in ', 'geodirectory') . implode(", ", $location_titles);
3891
    }
3892
3893
3894
3895
    if($location_single) {
3896
        $vars['%%in_location_single%%'] = __('in', 'geodirectory') . ' ' .$location_single;
3897
    }
3898
3899
3900
    if($location_single) {
3901
        $vars['%%location_single%%'] = $location_single;
3902
    }
3903
3904
    /**
3905
     * Filter the title variables after standard ones have been filtered for wpseo.
3906
     *
3907
     * @since 1.5.7
3908
     * @package GeoDirectory
3909
     * @param string $vars The title with variables.
3910
     * @param array $location_array The array of location variables.
3911
     */
3912
    return apply_filters('geodir_wpseo_replacements_vars',$vars,$location_array);
3913
}
3914
3915
3916
add_filter('geodir_seo_meta_title','geodir_filter_title_variables',10,3);
3917
add_filter('geodir_seo_page_title','geodir_filter_title_variables',10,2);
3918
add_filter('geodir_seo_meta_description_pre','geodir_filter_title_variables',10,3);
3919
function geodir_filter_title_variables($title, $gd_page, $sep=''){
3920
3921
3922 2
    if(!$gd_page || !$title){return $title;}// if no a GD page then bail.
3923 1
    global $post;
3924
    //print_r($post);
3925
    /*
3926
    %%date%%	                Replaced with the date of the post/page
3927
    %%title%%	                Replaced with the title of the post/page
3928
    %%sitename%%	            The site's name
3929
    %%sitedesc%%	            The site's tagline / description
3930
    %%excerpt%%	                Replaced with the post/page excerpt (or auto-generated if it does not exist)
3931
    %%tag%%	                    Replaced with the current tag/tags
3932
    %%category%%	            Replaced with the post categories (comma separated)
3933
    %%category_description%%	Replaced with the category description
3934
    %%tag_description%%	        Replaced with the tag description
3935
    %%term_description%%	    Replaced with the term description
3936
    %%term_title%%	            Replaced with the term name
3937
    %%searchphrase%%	        Replaced with the current search phrase
3938
    %%sep%%	                    The separator defined in your theme's wp_title() tag.
3939
3940
    ADVANCED
3941
    %%pt_single%%	            Replaced with the post type single label
3942
    %%pt_plural%%	            Replaced with the post type plural label
3943
    %%modified%%	            Replaced with the post/page modified time
3944
    %%id%%	                    Replaced with the post/page ID
3945
    %%name%%	                Replaced with the post/page author's 'nicename'
3946
    %%userid%%	                Replaced with the post/page author's userid
3947
    %%page%%	                Replaced with the current page number (i.e. page 2 of 4)
3948
    %%pagetotal%%	            Replaced with the current page total
3949
    %%pagenumber%%	            Replaced with the current page number
3950
     */
3951
3952 1
    if ($sep == '') {
3953
        /**
3954
         * Filter the page title separator.
3955
         *
3956
         * @since 1.0.0
3957
         * @package GeoDirectory
3958
         * @param string $sep The separator, default: `|`.
3959
         */
3960 1
        $sep = apply_filters('geodir_page_title_separator', '|');
3961 1
    }
3962
3963
3964 1
    if(strpos($title,'%%title%%') !== false){
3965 1
        $title = str_replace("%%title%%",$post->post_title,$title);
3966 1
    }
3967
3968 1 View Code Duplication
    if(strpos($title,'%%sitename%%') !== false){
3969 1
        $title = str_replace("%%sitename%%",get_bloginfo('name'),$title);
3970 1
    }
3971
3972 1 View Code Duplication
    if(strpos($title,'%%sitedesc%%') !== false){
3973
        $title = str_replace("%%sitedesc%%",get_bloginfo('description'),$title);
3974
    }
3975
3976 1
    if(strpos($title,'%%excerpt%%') !== false){
3977
        $title = str_replace("%%excerpt%%",strip_tags(get_the_excerpt()),$title);
3978
    }
3979
3980 1
    if(strpos($title,'%%pt_single%%') !== false){
3981
        $single_name = '';
3982
        if($gd_page=='search' || $gd_page=='author'){
3983
            $geodir_post_types = get_option('geodir_post_types');
3984
            $spt = esc_attr($_REQUEST['stype']);
3985
            if(isset($geodir_post_types[$spt]['labels']['singular_name'])){
3986
                $single_name = __($geodir_post_types[$spt]['labels']['singular_name'],'geodirectory');
3987
            }
3988
        }elseif($gd_page=='add-listing'){
3989
            $geodir_post_types = get_option('geodir_post_types');
3990
            $spt = isset($_REQUEST['listing_type']) ? esc_attr($_REQUEST['listing_type']) : '';
3991
            if(!$spt && isset($_REQUEST['pid'])){
3992
                $spt = get_post_type( $_REQUEST['pid'] );
3993
            }
3994
            if(!$spt){$spt='gd_place';}
3995
            if(isset($geodir_post_types[$spt]['labels']['singular_name'])){
3996
                $single_name = __($geodir_post_types[$spt]['labels']['singular_name'],'geodirectory');
3997
            }
3998
        }
3999 View Code Duplication
        elseif($post->post_type){
4000
            $geodir_post_types = get_option('geodir_post_types');
4001
            if(isset($geodir_post_types[$post->post_type]['labels']['singular_name'])){
4002
                $single_name = __($geodir_post_types[$post->post_type]['labels']['singular_name'],'geodirectory');
4003
            }
4004
4005
4006
        }
4007
        $title = str_replace("%%pt_single%%",$single_name,$title);
4008
    }
4009
4010 1
    if(strpos($title,'%%pt_plural%%') !== false){
4011 1
        $plural_name = '';
4012 1
        if($gd_page=='search' || $gd_page=='author'){
4013 1
            $geodir_post_types = get_option('geodir_post_types');
4014 1
            $spt = esc_attr($_REQUEST['stype']);
4015 1
            if(isset($geodir_post_types[$spt]['labels']['name'])){
4016 1
                $plural_name = __($geodir_post_types[$spt]['labels']['name'],'geodirectory');
4017 1
            }
4018 1
        }elseif($gd_page=='add-listing'){
4019
            $geodir_post_types = get_option('geodir_post_types');
4020
            $spt = sanitize_text_field($_REQUEST['listing_type']);
4021
            if(!$spt){$spt='gd_place';}
4022
            if(isset($geodir_post_types[$spt]['labels']['name'])){
4023
                $plural_name = __($geodir_post_types[$spt]['labels']['name'],'geodirectory');
4024
            }
4025
        }
4026 1 View Code Duplication
        elseif(isset($post->post_type) && $post->post_type){
4027 1
            $geodir_post_types = get_option('geodir_post_types');
4028 1
            if(isset($geodir_post_types[$post->post_type]['labels']['name'])){
4029 1
                $plural_name = __($geodir_post_types[$post->post_type]['labels']['name'],'geodirectory');
4030 1
            }
4031
4032 1
        }
4033 1
        $title = str_replace("%%pt_plural%%",$plural_name,$title);
4034 1
    }
4035
4036
4037
4038 1 View Code Duplication
    if(strpos($title,'%%category%%') !== false){
4039
        $cat_name = '';
4040
4041
        if($gd_page=='detail') {
4042
            if ($post->default_category) {
4043
                $cat = get_term($post->default_category, $post->post_type . 'category');
4044
                $cat_name = (isset($cat->name)) ? $cat->name : '';
4045
            }
4046
        }elseif($gd_page=='listing'){
4047
            $queried_object = get_queried_object();
4048
            if(isset($queried_object->name)){
4049
                $cat_name = $queried_object->name;
4050
            }
4051
        }
4052
        $title = str_replace("%%category%%",$cat_name,$title);
4053
    }
4054
4055 1 View Code Duplication
    if(strpos($title,'%%tag%%') !== false){
4056
        $cat_name = '';
4057
4058
        if($gd_page=='detail') {
4059
            if ($post->default_category) {
4060
                $cat = get_term($post->default_category, $post->post_type . 'category');
4061
                $cat_name = (isset($cat->name)) ? $cat->name : '';
4062
            }
4063
        }elseif($gd_page=='listing'){
4064
            $queried_object = get_queried_object();
4065
            if(isset($queried_object->name)){
4066
                $cat_name = $queried_object->name;
4067
            }
4068
        }
4069
        $title = str_replace("%%tag%%",$cat_name,$title);
4070
    }
4071
4072
4073
4074 1
    if(strpos($title,'%%id%%') !== false){
4075
        $ID = (isset($post->ID)) ? $post->ID : '';
4076
        $title = str_replace("%%id%%",$ID,$title);
4077
    }
4078
4079 1
    if(strpos($title,'%%sep%%') !== false){
4080 1
        $title = str_replace("%%sep%%",$sep,$title);
4081 1
    }
4082
4083
4084 1
    global $wp;
4085
    // location variables
4086 1
    $gd_post_type = geodir_get_current_posttype();
4087 1
    $location_array = geodir_get_current_location_terms('query_vars', $gd_post_type);
4088
    /**
4089
     * Filter the title variables location variables array
4090
     *
4091
     * @since 1.5.5
4092
     * @package GeoDirectory
4093
     * @param array $location_array The array of location variables.
4094
     * @param string $title The title with variables..
4095
     * @param string $gd_page The page being filtered.
4096
     * @param string $sep The separator, default: `|`.
4097
     */
4098 1
    $location_array = apply_filters('geodir_filter_title_variables_location_arr',$location_array,$title, $gd_page, $sep);
4099 1
    $location_titles = array();
4100 1 View Code Duplication
    if($gd_page=='location' && get_query_var( 'gd_country_full' )){
4101
        if(get_query_var( 'gd_country_full' )){$location_array['gd_country'] = get_query_var( 'gd_country_full' );}
4102
        if(get_query_var( 'gd_region_full' )){$location_array['gd_region'] = get_query_var( 'gd_region_full' );}
4103
        if(get_query_var( 'gd_city_full' )){$location_array['gd_city'] = get_query_var( 'gd_city_full' );}
4104
    }
4105 1
    $location_single = '';
4106 1
    $gd_country = (isset($wp->query_vars['gd_country']) && $wp->query_vars['gd_country'] != '') ? $wp->query_vars['gd_country'] : '';
4107 1
    $gd_region = (isset($wp->query_vars['gd_region']) && $wp->query_vars['gd_region'] != '') ? $wp->query_vars['gd_region'] : '';
4108 1
    $gd_city = (isset($wp->query_vars['gd_city']) && $wp->query_vars['gd_city'] != '') ? $wp->query_vars['gd_city'] : '';
4109
4110 1
    $gd_country_actual = $gd_region_actual = $gd_city_actual = '';
4111
4112 1 View Code Duplication
    if (function_exists('get_actual_location_name')) {
4113
        $gd_country_actual = $gd_country != '' ? get_actual_location_name('country', $gd_country, true) : $gd_country;
4114
        $gd_region_actual = $gd_region != '' ? get_actual_location_name('region', $gd_region) : $gd_region;
4115
        $gd_city_actual = $gd_city != '' ? get_actual_location_name('city', $gd_city) : $gd_city;
4116
    }
4117
4118 1 View Code Duplication
    if ($gd_city != '') {
4119
        if ($gd_city_actual != '') {
4120
            $gd_city = $gd_city_actual;
4121
        } else {
4122
            $gd_city = preg_replace('/-(\d+)$/', '', $gd_city);
4123
            $gd_city = preg_replace('/[_-]/', ' ', $gd_city);
4124
            $gd_city = __(geodir_ucwords($gd_city), 'geodirectory');
4125
        }
4126
        $location_single = $gd_city;
4127
4128 1
    } else if ($gd_region != '') {
4129
        if ($gd_region_actual != '') {
4130
            $gd_region = $gd_region_actual;
4131
        } else {
4132
            $gd_region = preg_replace('/-(\d+)$/', '', $gd_region);
4133
            $gd_region = preg_replace('/[_-]/', ' ', $gd_region);
4134
            $gd_region = __(geodir_ucwords($gd_region), 'geodirectory');
4135
        }
4136
4137
        $location_single = $gd_region;
4138 1
    } else if ($gd_country != '') {
4139
        if ($gd_country_actual != '') {
4140
            $gd_country = $gd_country_actual;
4141
        } else {
4142
            $gd_country = preg_replace('/-(\d+)$/', '', $gd_country);
4143
            $gd_country = preg_replace('/[_-]/', ' ', $gd_country);
4144
            $gd_country = __(geodir_ucwords($gd_country), 'geodirectory');
4145
        }
4146
4147
        $location_single = $gd_country;
4148
    }
4149
4150 1 View Code Duplication
    if (!empty($location_array)) {
4151
4152
        $actual_location_name = function_exists('get_actual_location_name') ? true : false;
4153
        $location_array = array_reverse($location_array);
4154
4155
        foreach ($location_array as $location_type => $location) {
4156
            $gd_location_link_text = preg_replace('/-(\d+)$/', '', $location);
4157
            $gd_location_link_text = preg_replace('/[_-]/', ' ', $gd_location_link_text);
4158
4159
            $location_name = geodir_ucwords($gd_location_link_text);
4160
            $location_name = __($location_name, 'geodirectory');
4161
4162
            if ($actual_location_name) {
4163
                $location_type = strpos($location_type, 'gd_') === 0 ? substr($location_type, 3) : $location_type;
4164
                $location_name = get_actual_location_name($location_type, $location, true);
4165
            }
4166
4167
            $location_titles[] = $location_name;
4168
        }
4169
        if (!empty($location_titles)) {
4170
            $location_titles = array_unique($location_titles);
4171
        }
4172
    }
4173
4174
4175 1
    if(strpos($title,'%%location%%') !== false){
4176
        $location = '';
4177
        if($location_titles) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $location_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
4178
            $location = implode(", ", $location_titles);
4179
        }
4180
        $title = str_replace("%%location%%",$location,$title);
4181
    }
4182
4183 1 View Code Duplication
    if(strpos($title,'%%in_location%%') !== false){
4184 1
        $location = '';
4185 1
        if($location_titles) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $location_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
4186
            $location = __('in ', 'geodirectory') . implode(", ", $location_titles);
4187
        }
4188 1
        $title = str_replace("%%in_location%%",$location,$title);
4189 1
    }
4190
4191 1 View Code Duplication
    if(strpos($title,'%%in_location_single%%') !== false){
4192 1
        if($location_single) {
4193
            $location_single = __('in', 'geodirectory') . ' ' .$location_single;
4194
        }
4195 1
        $title = str_replace("%%in_location_single%%",$location_single,$title);
4196 1
    }
4197
4198 1
    if(strpos($title,'%%location_single%%') !== false){
4199
        $title = str_replace("%%location_single%%",$location_single,$title);
4200
    }
4201
4202
4203 1 View Code Duplication
    if(strpos($title,'%%search_term%%') !== false){
4204
        $search_term = '';
4205
        if(isset($_REQUEST['s'])){
4206
            $search_term = esc_attr($_REQUEST['s']);
4207
        }
4208
        $title = str_replace("%%search_term%%",$search_term,$title);
4209
    }
4210
4211 1 View Code Duplication
    if(strpos($title,'%%search_near%%') !== false){
4212
        $search_term = '';
4213
        if(isset($_REQUEST['snear'])){
4214
            $search_term = esc_attr($_REQUEST['snear']);
4215
        }
4216
        $title = str_replace("%%search_near%%",$search_term,$title);
4217
    }
4218
4219 1
    if(strpos($title,'%%name%%') !== false){
4220 1
        $author_name = get_the_author();
4221 1
        if (!$author_name || $author_name === '') {
4222 1
            $queried_object = get_queried_object();
4223
            
4224 1
            if (isset($queried_object->data->user_nicename)) {
4225 1
                $author_name = $queried_object->data->user_nicename;
4226 1
            }
4227 1
        }
4228 1
        $title = str_replace("%%name%%", $author_name, $title);
4229 1
    }
4230
    
4231 1
    if (strpos($title, '%%page%%') !== false) {
4232
        $page = geodir_title_meta_page($sep);
4233
        $title = str_replace("%%page%%", $page, $title);
4234
    }
4235 1
    if (strpos($title, '%%pagenumber%%') !== false) {
4236
        $pagenumber = geodir_title_meta_pagenumber();
4237
        $title = str_replace("%%pagenumber%%", $pagenumber, $title);
4238
    }
4239 1
    if (strpos($title, '%%pagetotal%%') !== false) {
4240
        $pagetotal = geodir_title_meta_pagetotal();
4241
        $title = str_replace("%%pagetotal%%", $pagetotal, $title);
4242
    }
4243
4244 1
    $title = wptexturize( $title );
4245 1
    $title = convert_chars( $title );
4246 1
    $title = esc_html( $title );
4247
4248
    /**
4249
     * Filter the title variables after standard ones have been filtered.
4250
     *
4251
     * @since 1.5.7
4252
     * @package GeoDirectory
4253
     * @param string $title The title with variables.
4254
     * @param array $location_array The array of location variables.
4255
     * @param string $gd_page The page being filtered.
4256
     * @param string $sep The separator, default: `|`.
4257
     */
4258
4259 1
    return apply_filters('geodir_filter_title_variables_vars',$title,$location_array, $gd_page, $sep);
4260
}
4261
4262
/**
4263
 * Get the cpt texts for translation.
4264
 *
4265
 * @since 1.5.5
4266
 * @package GeoDirectory
4267
 *
4268
 * @param  array $translation_texts Array of text strings.
4269
 * @return array Translation texts.
4270
 */
4271
function geodir_load_cpt_text_translation($translation_texts = array()) {
4272 1
    $gd_post_types = geodir_get_posttypes('array');
4273
4274 1
    if (!empty($gd_post_types)) {
4275 1
        foreach ($gd_post_types as $post_type => $cpt_info) {
0 ignored issues
show
Bug introduced by
The expression $gd_post_types of type array|object|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
4276 1
            $labels = isset($cpt_info['labels']) ? $cpt_info['labels'] : '';
4277 1
            $description = isset($cpt_info['description']) ? $cpt_info['description'] : '';
4278 1
            $seo = isset($cpt_info['seo']) ? $cpt_info['seo'] : '';
4279
4280 1
            if (!empty($labels)) {
4281 1 View Code Duplication
                if ($labels['name'] != '' && !in_array($labels['name'], $translation_texts))
4282 1
                    $translation_texts[] = $labels['name'];
4283 1 View Code Duplication
                if ($labels['singular_name'] != '' && !in_array($labels['singular_name'], $translation_texts))
4284 1
                    $translation_texts[] = $labels['singular_name'];
4285 1 View Code Duplication
                if ($labels['add_new'] != '' && !in_array($labels['add_new'], $translation_texts))
4286 1
                    $translation_texts[] = $labels['add_new'];
4287 1 View Code Duplication
                if ($labels['add_new_item'] != '' && !in_array($labels['add_new_item'], $translation_texts))
4288 1
                    $translation_texts[] = $labels['add_new_item'];
4289 1 View Code Duplication
                if ($labels['edit_item'] != '' && !in_array($labels['edit_item'], $translation_texts))
4290 1
                    $translation_texts[] = $labels['edit_item'];
4291 1 View Code Duplication
                if ($labels['new_item'] != '' && !in_array($labels['new_item'], $translation_texts))
4292 1
                    $translation_texts[] = $labels['new_item'];
4293 1 View Code Duplication
                if ($labels['view_item'] != '' && !in_array($labels['view_item'], $translation_texts))
4294 1
                    $translation_texts[] = $labels['view_item'];
4295 1 View Code Duplication
                if ($labels['search_items'] != '' && !in_array($labels['search_items'], $translation_texts))
4296 1
                    $translation_texts[] = $labels['search_items'];
4297 1 View Code Duplication
                if ($labels['not_found'] != '' && !in_array($labels['not_found'], $translation_texts))
4298 1
                    $translation_texts[] = $labels['not_found'];
4299 1 View Code Duplication
                if ($labels['not_found_in_trash'] != '' && !in_array($labels['not_found_in_trash'], $translation_texts))
4300 1
                    $translation_texts[] = $labels['not_found_in_trash'];
4301 1 View Code Duplication
                if (isset($labels['label_post_profile']) && $labels['label_post_profile'] != '' && !in_array($labels['label_post_profile'], $translation_texts))
4302 1
                    $translation_texts[] = $labels['label_post_profile'];
4303 1 View Code Duplication
                if (isset($labels['label_post_info']) && $labels['label_post_info'] != '' && !in_array($labels['label_post_info'], $translation_texts))
4304 1
                    $translation_texts[] = $labels['label_post_info'];
4305 1 View Code Duplication
                if (isset($labels['label_post_images']) && $labels['label_post_images'] != '' && !in_array($labels['label_post_images'], $translation_texts))
4306 1
                    $translation_texts[] = $labels['label_post_images'];
4307 1 View Code Duplication
                if (isset($labels['label_post_map']) && $labels['label_post_map'] != '' && !in_array($labels['label_post_map'], $translation_texts))
4308 1
                    $translation_texts[] = $labels['label_post_map'];
4309 1 View Code Duplication
                if (isset($labels['label_reviews']) && $labels['label_reviews'] != '' && !in_array($labels['label_reviews'], $translation_texts))
4310 1
                    $translation_texts[] = $labels['label_reviews'];
4311 1 View Code Duplication
                if (isset($labels['label_related_listing']) && $labels['label_related_listing'] != '' && !in_array($labels['label_related_listing'], $translation_texts))
4312 1
                    $translation_texts[] = $labels['label_related_listing'];
4313 1
            }
4314
4315 1
            if ($description != '' && !in_array($description, $translation_texts)) {
4316 1
                $translation_texts[] = normalize_whitespace($description);
4317 1
            }
4318
4319 1
            if (!empty($seo)) {
4320 View Code Duplication
                if (isset($seo['meta_keyword']) && $seo['meta_keyword'] != '' && !in_array($seo['meta_keyword'], $translation_texts))
4321
                    $translation_texts[] = normalize_whitespace($seo['meta_keyword']);
4322
4323 View Code Duplication
                if (isset($seo['meta_description']) && $seo['meta_description'] != '' && !in_array($seo['meta_description'], $translation_texts))
4324
                    $translation_texts[] = normalize_whitespace($seo['meta_description']);
4325
            }
4326 1
        }
4327 1
    }
4328 1
    $translation_texts = !empty($translation_texts) ? array_unique($translation_texts) : $translation_texts;
4329
4330 1
    return $translation_texts;
4331
}
4332
4333
/**
4334
 * Remove the location terms to hide term from location url.
4335
 *
4336
 * @since 1.5.5
4337
 * @package GeoDirectory
4338
 *
4339
 * @param  array $location_terms Array of location terms.
4340
 * @return array Location terms.
4341
 */
4342
function geodir_remove_location_terms($location_terms = array()) {
4343
    $location_manager = defined('POST_LOCATION_TABLE') ? true : false;
4344
4345
    if (!empty($location_terms) && $location_manager) {
4346
        $hide_country_part = get_option('geodir_location_hide_country_part');
4347
        $hide_region_part = get_option('geodir_location_hide_region_part');
4348
4349
        if ($hide_region_part && $hide_country_part) {
4350
            if (isset($location_terms['gd_country']))
4351
                unset($location_terms['gd_country']);
4352
            if (isset($location_terms['gd_region']))
4353
                unset($location_terms['gd_region']);
4354
        } else if ($hide_region_part && !$hide_country_part) {
4355
            if (isset($location_terms['gd_region']))
4356
                unset($location_terms['gd_region']);
4357
        } else if (!$hide_region_part && $hide_country_part) {
4358
            if (isset($location_terms['gd_country']))
4359
                unset($location_terms['gd_country']);
4360
        }
4361
    }
4362
4363
    return $location_terms;
4364
}
4365
4366
/**
4367
 * Send notification when a listing has been edited by it's author.
4368
 *
4369
 * @since 1.5.9
4370
 * @package GeoDirectory
4371
 *
4372
 * @param int $post_ID Post ID.
4373
 * @param WP_Post $post Post object.
4374
 * @param bool $update Whether this is an existing listing being updated or not.
4375
 */
4376
function geodir_on_wp_insert_post($post_ID, $post, $update) {
4377 8
    if (!$update) {
4378 7
        return;
4379
    }
4380
    
4381 1
    $action = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : '';
4382 1
    $is_admin = is_admin() && ( !defined('DOING_AJAX' ) || ( defined('DOING_AJAX') && !DOING_AJAX ) )  ? true : false;
4383 1
    $inline_save = $action == 'inline-save' ? true : false;
4384
4385 1
    if (empty($post->post_type) || $is_admin || $inline_save || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) {
4386
        return;
4387
    }
4388
    
4389 1
    if ($action != '' && in_array($action, array('geodir_import_export'))) {
4390
        return;
4391
    }
4392
4393 1
    $user_id = (int)get_current_user_id();
4394
        
4395 1
    if ($user_id > 0 && get_option('geodir_notify_post_edited') && !wp_is_post_revision($post_ID) && in_array($post->post_type, geodir_get_posttypes())) {
4396
        $author_id = !empty($post->post_author) ? $post->post_author : 0;
4397
        
4398
        if ($user_id == $author_id && !is_super_admin()) {
4399
            $from_email = get_option('site_email');
4400
            $from_name = get_site_emailName();
4401
            $to_email = get_option('admin_email');
4402
            $to_name = get_option('name');
4403
            $message_type = 'listing_edited';
4404
            
4405
            $notify_edited = true;
4406
            /**
4407
             * Send notification when listing edited by author?
4408
             *
4409
             * @since 1.6.0
4410
             * @param bool $notify_edited Notify on listing edited by author?
4411
             * @param object $post The current post object.
4412
             */
4413
            $notify_edited = apply_filters('geodir_notify_on_listing_edited', $notify_edited, $post);
0 ignored issues
show
Unused Code introduced by
$notify_edited 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...
4414
            
4415
            geodir_sendEmail($from_email, $from_name, $to_email, $to_name, '', '', '', $message_type, $post_ID);
4416
        }
4417
    }
4418 1
}
4419
4420
/**
4421
 * Retrieve the current page start & end numbering with context (i.e. 'page 2 of 4') for use as replacement string.
4422
 *
4423
 * @since 1.6.0
4424
 * @package GeoDirectory
4425
 *
4426
 * @param string $sep The separator tag.
4427
 *
4428
 * @return string|null The current page start & end numbering.
4429
 */
4430
function geodir_title_meta_page($sep) {
4431
    $replacement = null;
4432
4433
    $max = geodir_title_meta_pagenumbering('max');
4434
    $nr  = geodir_title_meta_pagenumbering('nr');
4435
4436
    if ($max > 1 && $nr > 1) {
4437
        $replacement = sprintf($sep . ' ' . __('Page %1$d of %2$d', 'geodirectory'), $nr, $max);
4438
    }
4439
4440
    return $replacement;
4441
}
4442
4443
/**
4444
 * Retrieve the current page number for use as replacement string.
4445
 *
4446
 * @since 1.6.0
4447
 * @package GeoDirectory
4448
 *
4449
 * @return string|null The current page number.
4450
 */
4451 View Code Duplication
function geodir_title_meta_pagenumber() {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
4452
    $replacement = null;
4453
4454
    $nr = geodir_title_meta_pagenumbering('nr');
4455
    if (isset($nr) && $nr > 0) {
4456
        $replacement = (string)$nr;
4457
    }
4458
4459
    return $replacement;
4460
}
4461
4462
/**
4463
 * Retrieve the current page total for use as replacement string.
4464
 *
4465
 * @since 1.6.0
4466
 * @package GeoDirectory
4467
 *
4468
 * @return string|null The current page total.
4469
 */
4470 View Code Duplication
function geodir_title_meta_pagetotal() {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
4471
    $replacement = null;
4472
4473
    $max = geodir_title_meta_pagenumbering('max');
4474
    if (isset($max) && $max > 0) {
4475
        $replacement = (string)$max;
4476
    }
4477
4478
    return $replacement;
4479
}
4480
4481
/**
4482
 * Determine the page numbering of the current post/page/cpt.
4483
 *
4484
 * @param string $request 'nr'|'max' - whether to return the page number or the max number of pages.
4485
 *
4486
 * @since 1.6.0
4487
 * @package GeoDirectory
4488
 *
4489
 * @global object $wp_query WordPress Query object.
4490
 * @global object $post The current post object.
4491
 *
4492
 * @return int|null The current page numbering.
4493
 */
4494
function geodir_title_meta_pagenumbering($request = 'nr') {
4495
    global $wp_query, $post;
4496
    $max_num_pages = null;
0 ignored issues
show
Unused Code introduced by
$max_num_pages 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...
4497
    $page_number   = null;
0 ignored issues
show
Unused Code introduced by
$page_number 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...
4498
4499
    $max_num_pages = 1;
4500
4501
    if (!is_singular()) {
4502
        $page_number = get_query_var('paged');
4503
        if ($page_number === 0 || $page_number === '') {
4504
            $page_number = 1;
4505
        }
4506
4507
        if (isset($wp_query->max_num_pages) && ($wp_query->max_num_pages != '' && $wp_query->max_num_pages != 0)) {
4508
            $max_num_pages = $wp_query->max_num_pages;
4509
        }
4510
    } else {
4511
        $page_number = get_query_var('page');
4512
        if ($page_number === 0 || $page_number === '') {
4513
            $page_number = 1;
4514
        }
4515
4516
        if (isset($post->post_content)) {
4517
            $max_num_pages = (substr_count($post->post_content, '<!--nextpage-->' ) + 1);
4518
        }
4519
    }
4520
4521
    $return = null;
4522
4523
    switch ($request) {
4524
        case 'nr':
4525
            $return = $page_number;
4526
            break;
4527
        case 'max':
4528
            $return = $max_num_pages;
4529
            break;
4530
    }
4531
4532
    return $return;
4533
}