Passed
Pull Request — master (#249)
by Viruthagiri
10:31
created

general_functions.php ➔ fetch_remote_file()   D

Complexity

Conditions 18
Paths 314

Size

Total Lines 73
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 26.748

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 46
c 1
b 0
f 0
nc 314
nop 1
dl 0
loc 73
ccs 35
cts 50
cp 0.7
crap 26.748
rs 4.074

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * 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 21
    if (is_ssl()) :
32
        return str_replace('http://', 'https://', WP_PLUGIN_URL) . "/" . plugin_basename(dirname(dirname(__FILE__)));
33
    else :
34 21
        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 34
    if ( defined( 'GD_TESTING_MODE' ) && GD_TESTING_MODE ) {
51 34
        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 (L3205-3208) 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 (L3220-3223) 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 15
    if ($use_existing_arguments) $params = $params + $_GET;
122 15
    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 15
    $link = $url;
124 15
    if (strpos($link, '?') === false) $link .= '?'; //If there is no '?' add one at the end
125 15
    elseif (strpos($link, '//maps.google.com/maps/api/js?language=')) $link .= '&amp;'; //If there is no '&' at the END, add one.
126 15
    elseif (!preg_match('/(\?|\&(amp;)?)$/', $link)) $link .= '&'; //If there is no '&' at the END, add one.
127
128 15
    $params_arr = array();
129 15
    foreach ($params as $key => $value) {
130 15
        if (gettype($value) == 'array') { //Handle array data properly
131
            foreach ($value as $val) {
132
                $params_arr[] = $key . '[]=' . urlencode($val);
133
            }
134
        } else {
135 15
            $params_arr[] = $key . '=' . urlencode($value);
136
        }
137 15
    }
138 15
    $link .= implode('&', $params_arr);
139
140 15
    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 9
    $pageURL = 'http';
179 9
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
180
        $pageURL .= "s";
181
    }
182 9
    $pageURL .= "://";
183 9
    $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 9
    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 28
    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 28
        case 'add-listing':
260
261 25
            if (is_page() && get_query_var('page_id') == geodir_add_listing_page_id()) {
262 1
                return true;
263 24
            } elseif (is_page() && isset($post->post_content) && has_shortcode($post->post_content, 'gd_add_listing')) {
264
                return true;
265
            }
266
267 24
            break;
268 27
        case 'preview':
269 22
            if ((is_page() && get_query_var('page_id') == geodir_preview_page_id()) && isset($_REQUEST['listing_type'])
270 22
                && in_array($_REQUEST['listing_type'], geodir_get_posttypes())
271 1
            )
272 22
                return true;
273 21
            break;
274 27
        case 'listing-success':
275 6
            if (is_page() && get_query_var('page_id') == geodir_success_page_id())
276 6
                return true;
277 5
            break;
278 27 View Code Duplication
        case 'detail':
279 10
            $post_type = get_query_var('post_type');
280 10
            if(is_array($post_type)){$post_type = reset($post_type);}
281 10
            if (is_single() && in_array($post_type, geodir_get_posttypes()))
282 10
                return true;
283 8
            break;
284 26 View Code Duplication
        case 'pt':
285 7
            $post_type = get_query_var('post_type');
286 7
            if(is_array($post_type)){$post_type = reset($post_type);}
287 7
            if (is_post_type_archive() && in_array($post_type , geodir_get_posttypes()) && !is_tax())
288 7
                return true;
289
290 7
            break;
291 26
        case 'listing':
292 12
            if (is_tax() && geodir_get_taxonomy_posttype()) {
293
                global $current_term, $taxonomy, $term;
294
295
                return true;
296
            }
297 12
            $post_type = get_query_var('post_type');
298 12
            if(is_array($post_type)){$post_type = reset($post_type);}
299 12
            if (is_post_type_archive() && in_array($post_type, geodir_get_posttypes()))
300 12
                return true;
301
302 12
            break;
303 25
        case 'home':
304
305 8
            if ((is_page() && get_query_var('page_id') == geodir_home_page_id()) || is_page_geodir_home())
306 8
                return true;
307
308 9
            break;
309 25
        case 'location':
310 7
            if (is_page() && get_query_var('page_id') == geodir_location_page_id())
311 7
                return true;
312 6
            break;
313 25
        case 'author':
314 24
            if (is_author() && isset($_REQUEST['geodir_dashbord']))
315 24
                return true;
316
			
317 24
			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 24
            break;
323 25
        case 'search':
324 24
            if (is_search() && isset($_REQUEST['geodir_search']))
325 24
                return true;
326 23
            break;
327 10
        case 'info':
328 1
            if (is_page() && get_query_var('page_id') == geodir_info_page_id())
329 1
                return true;
330 1
            break;
331 9
        case 'login':
332 9
            if (is_page() && get_query_var('page_id') == geodir_login_page_id())
333 9
                return true;
334 9
            break;
335 7
        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 7
        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 7
        default:
344 7
            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 7
    endswitch;
348
349
    //endif;
350
351 28
    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 30
    global $wp;
469 30
    if (isset($wp->query_vars['gd_is_geodir_page']) && $wp->query_vars['gd_is_geodir_page'])
470 30
        return true;
471
    else
472 30
        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 9
        $imagesizes = array('list-thumb' => array('w' => 283, 'h' => 188),
488 9
            'thumbnail' => array('w' => 125, 'h' => 125),
489 9
            'widget-thumb' => array('w' => 50, 'h' => 50),
490 9
            'slider-thumb' => array('w' => 100, 'h' => 100)
491 9
        );
492
493
        /**
494
         * Filter the image sizes array.
495
         *
496
         * @since 1.0.0
497
         * @param array $imagesizes Image size array.
498
         */
499 9
        $imagesizes = apply_filters('geodir_imagesizes', $imagesizes);
500
501 9
        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 9
            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 1
        switch (geodir_strtolower($uom)):
573 1
            case 'km'    :
574
                $earthMeanRadius = 6371.009; // km
575
                break;
576 1
            case 'm'    :
577 1
            case 'meters'    :
578
                $earthMeanRadius = 6371.009 * 1000; // km
579
                break;
580 1
            case 'miles'    :
581 1
                $earthMeanRadius = 3958.761; // miles
582 1
                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 1
        endswitch;
598 1
        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 1
        $earthMeanRadius = geodir_getDistanceRadius($uom);
619
620 1
        $deltaLatitude = deg2rad((float) $point2['latitude'] - (float) $point1['latitude']);
621 1
        $deltaLongitude = deg2rad((float) $point2['longitude'] - (float) $point1['longitude']);
622 1
        $a = sin($deltaLatitude / 2) * sin($deltaLatitude / 2) +
623 1
            cos(deg2rad((float) $point1['latitude'])) * cos(deg2rad((float) $point2['latitude'])) *
624 1
            sin($deltaLongitude / 2) * sin($deltaLongitude / 2);
625 1
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
626 1
        $distance = $earthMeanRadius * $c;
627 1
        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 = '') {
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
742
        /**
743
         * Filter the client email to address.
744
         *
745
         * @since 1.6.1
746
         * @package GeoDirectory
747
         * @param string $to The email address the email is being sent to.
748
         * @param string $fromEmail Sender email address.
749
         * @param string $fromEmailName Sender name.
750
         * @param string $toEmail Receiver email address.
751
         * @param string $toEmailName Receiver name.
752
         * @param string $to_subject Email subject.
753
         * @param string $to_message Email content.
754
         * @param string $extra Not being used.
755
         * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration, post_submit, listing_published.
756
         * @param string $post_id The post ID.
757
         * @param string $user_id The user ID.
758
         */
759 9
        $to = apply_filters('geodir_sendEmail_to',$to,$fromEmail, $fromEmailName, $toEmail, $toEmailName, $to_subject, $to_message, $extra, $message_type, $post_id, $user_id );
760
        /**
761
         * Filter the client email subject.
762
         *
763
         * @since 1.6.1
764
         * @package GeoDirectory_Payment_Manager
765
         * @param string $subject The email subject.
766
         * @param string $fromEmail Sender email address.
767
         * @param string $fromEmailName Sender name.
768
         * @param string $toEmail Receiver email address.
769
         * @param string $toEmailName Receiver name.
770
         * @param string $to_subject Email subject.
771
         * @param string $to_message Email content.
772
         * @param string $extra Not being used.
773
         * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration, post_submit, listing_published.
774
         * @param string $post_id The post ID.
775
         * @param string $user_id The user ID.
776
         */
777 9
        $subject = apply_filters('geodir_sendEmail_subject',$subject,$fromEmail, $fromEmailName, $toEmail, $toEmailName, $to_subject, $to_message, $extra, $message_type, $post_id, $user_id );
778
        /**
779
         * Filter the client email message.
780
         *
781
         * @since 1.6.1
782
         * @package GeoDirectory_Payment_Manager
783
         * @param string $message The email message text.
784
         * @param string $fromEmail Sender email address.
785
         * @param string $fromEmailName Sender name.
786
         * @param string $toEmail Receiver email address.
787
         * @param string $toEmailName Receiver name.
788
         * @param string $to_subject Email subject.
789
         * @param string $to_message Email content.
790
         * @param string $extra Not being used.
791
         * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration, post_submit, listing_published.
792
         * @param string $post_id The post ID.
793
         * @param string $user_id The user ID.
794
         */
795 9
        $message = apply_filters('geodir_sendEmail_message',$message,$fromEmail, $fromEmailName, $toEmail, $toEmailName, $to_subject, $to_message, $extra, $message_type, $post_id, $user_id );
796
        /**
797
         * Filter the client email headers.
798
         *
799
         * @since 1.6.1
800
         * @package GeoDirectory_Payment_Manager
801
         * @param string $headers The email headers.
802
         * @param string $fromEmail Sender email address.
803
         * @param string $fromEmailName Sender name.
804
         * @param string $toEmail Receiver email address.
805
         * @param string $toEmailName Receiver name.
806
         * @param string $to_subject Email subject.
807
         * @param string $to_message Email content.
808
         * @param string $extra Not being used.
809
         * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration, post_submit, listing_published.
810
         * @param string $post_id The post ID.
811
         * @param string $user_id The user ID.
812
         */
813 9
        $headers = apply_filters('geodir_sendEmail_headers',$headers,$fromEmail, $fromEmailName, $toEmail, $toEmailName, $to_subject, $to_message, $extra, $message_type, $post_id, $user_id );
814
815 9
        $sent = wp_mail($to, $subject, $message, $headers);
816
817 9
        if( ! $sent ) {
818
            if ( is_array( $to ) ) {
819
                $to = implode( ',', $to );
820
            }
821
            $log_message = sprintf(
822
                __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
823
                $message_type,
824
                date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
825
                $to,
826
                $subject
827
            );
828
            geodir_error_log( $log_message );
829
        }
830
831
        ///////// ADMIN BCC EMIALS
832 9
        $adminEmail = get_bloginfo('admin_email');
833 9
        $to = $adminEmail;
834
835 9
        $admin_bcc = false;
836 9
        if ($message_type == 'post_submit') {
837 1
            $subject = __(stripslashes_deep(get_option('geodir_post_submited_success_email_subject_admin')), 'geodirectory');
838 1
            $message = __(stripslashes_deep(get_option('geodir_post_submited_success_email_content_admin')), 'geodirectory');
839
840 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#]');
841 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);
842 1
            $message = str_replace($search_array, $replace_array, $message);
843
844 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#]');
845 1
            $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $toEmailName, $posted_date, $user_login, $user_login);
846 1
            $subject = str_replace($search_array, $replace_array, $subject);
847
848 1
            $subject .= ' - ADMIN BCC COPY';
849 1
            $admin_bcc = true;
850
851 1
        }
852 8
        elseif ($message_type == 'registration' && get_option('geodir_bcc_new_user')) {
853 2
            $subject .= ' - ADMIN BCC COPY';
854 2
            $admin_bcc = true;
855 2
        }
856 6
        elseif ($message_type == 'send_friend' && get_option('geodir_bcc_friend')) {
857 2
            $subject .= ' - ADMIN BCC COPY';
858 2
            $admin_bcc = true;
859 2
        }
860 4
        elseif ($message_type == 'send_enquiry' && get_option('geodir_bcc_enquiry')) {
861 2
            $subject .= ' - ADMIN BCC COPY';
862 2
            $admin_bcc = true;
863 2
        }
864 2
        elseif ($message_type == 'listing_published' && get_option('geodir_bcc_listing_published')) {
865 1
            $subject .= ' - ADMIN BCC COPY';
866 1
            $admin_bcc = true;
867 1
        }
868
869 9 View Code Duplication
        if($admin_bcc===true){
870 8
            $sent = wp_mail($to, $subject, $message, $headers);
871
872 8
            if( ! $sent ) {
873
                if ( is_array( $to ) ) {
874
                    $to = implode( ',', $to );
875
                }
876
                $log_message = sprintf(
877
                    __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
878
                    $message_type,
879
                    date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
880
                    $to,
881
                    $subject
882
                );
883
                geodir_error_log( $log_message );
884
            }
885 8
        }
886
887 9
    }
888
}
889
890
891
/**
892
 * Generates breadcrumb for taxonomy (category, tags etc.) pages.
893
 *
894
 * @since 1.0.0
895
 * @package GeoDirectory
896
 */
897
function geodir_taxonomy_breadcrumb()
898
{
899
900
    $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
901
    $parent = $term->parent;
902
903
    while ($parent):
904
        $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...
905
        $new_parent = get_term_by('id', $parent, get_query_var('taxonomy'));
906
        $parent = $new_parent->parent;
907
    endwhile;
908
909
    if (!empty($parents)):
910
        $parents = array_reverse($parents);
911
912
        foreach ($parents as $parent):
913
            $item = get_term_by('id', $parent, get_query_var('taxonomy'));
914
            $url = get_term_link($item, get_query_var('taxonomy'));
915
            echo '<li> > <a href="' . $url . '">' . $item->name . '</a></li>';
916
        endforeach;
917
918
    endif;
919
920
    echo '<li> > ' . $term->name . '</li>';
921
}
922
923
924
/**
925
 * Main function that generates breadcrumb for all pages.
926
 *
927
 * @since 1.0.0
928
 * @since 1.5.7 Changes for the neighbourhood system improvement.
929
 * @package GeoDirectory
930
 * @global object $wp_query WordPress Query object.
931
 * @global object $post The current post object.
932
 * @global object $gd_session GeoDirectory Session object.
933
 */
934
function geodir_breadcrumb()
935
{
936 5
    global $wp_query, $geodir_add_location_url;
937
938
    /**
939
     * Filter breadcrumb separator.
940
     *
941
     * @since 1.0.0
942
     */
943 5
    $separator = apply_filters('geodir_breadcrumb_separator', ' > ');
944
945 5
    if (!geodir_is_page('home')) {
946 5
        $breadcrumb = '';
947 5
        $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...
948 5
        $breadcrumb .= '<div class="geodir-breadcrumb clearfix"><ul id="breadcrumbs">';
949
        /**
950
         * Filter breadcrumb's first link.
951
         *
952
         * @since 1.0.0
953
         */
954 5
        $breadcrumb .= '<li>' . apply_filters('geodir_breadcrumb_first_link', '<a href="' . home_url() . '">' . __('Home', 'geodirectory') . '</a>') . '</li>';
955
956 5
        $gd_post_type = geodir_get_current_posttype();
957 5
        $post_type_info = get_post_type_object($gd_post_type);
958
959 5
        remove_filter('post_type_archive_link', 'geodir_get_posttype_link');
960
961 5
        $listing_link = get_post_type_archive_link($gd_post_type);
962
963 5
        add_filter('post_type_archive_link', 'geodir_get_posttype_link', 10, 2);
964 5
        $listing_link = rtrim($listing_link, '/');
965 5
        $listing_link .= '/';
966
967 5
        $post_type_for_location_link = $listing_link;
968 5
        $location_terms = geodir_get_current_location_terms('query_vars', $gd_post_type);
969
970 5
        global $wp, $gd_session;
971 5
        $location_link = $post_type_for_location_link;
972
973 5
        if (geodir_is_page('detail') || geodir_is_page('listing')) {
974 2
            global $post;
975 2
            $location_manager = defined('POST_LOCATION_TABLE') ? true : false;
976 2
			$neighbourhood_active = $location_manager && get_option('location_neighbourhoods') ? true : false;
977
				
978 2 View Code Duplication
			if(geodir_is_page('detail') && isset($post->country_slug)){
979
                $location_terms = array(
980
                    'gd_country' => $post->country_slug,
981
                    'gd_region' => $post->region_slug,
982
                    'gd_city' => $post->city_slug
983
                );
984
				
985
				if ($neighbourhood_active && !empty($location_terms['gd_city']) && $gd_ses_neighbourhood = $gd_session->get('gd_neighbourhood')) {
986
					$location_terms['gd_neighbourhood'] = $gd_ses_neighbourhood;
987
				}
988
            }
989
990 2
            $geodir_show_location_url = get_option('geodir_show_location_url');
991
992 2
            $hide_url_part = array();
993 2
            if ($location_manager) {
994
                $hide_country_part = get_option('geodir_location_hide_country_part');
995
                $hide_region_part = get_option('geodir_location_hide_region_part');
996
997
                if ($hide_region_part && $hide_country_part) {
998
                    $hide_url_part = array('gd_country', 'gd_region');
999
                } else if ($hide_region_part && !$hide_country_part) {
1000
                    $hide_url_part = array('gd_region');
1001
                } else if (!$hide_region_part && $hide_country_part) {
1002
                    $hide_url_part = array('gd_country');
1003
                }
1004
            }
1005
1006 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...
1007 2
            if ($geodir_show_location_url == 'country_city') {
1008
                $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...
1009
1010
                if (isset($location_terms['gd_region']) && !$location_manager) {
1011
                    unset($location_terms['gd_region']);
1012
                }
1013 2
            } else if ($geodir_show_location_url == 'region_city') {
1014
                $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...
1015
1016
                if (isset($location_terms['gd_country']) && !$location_manager) {
1017
                    unset($location_terms['gd_country']);
1018
                }
1019 2
            } else if ($geodir_show_location_url == 'city') {
1020
                $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...
1021
1022
                if (isset($location_terms['gd_country']) && !$location_manager) {
1023
                    unset($location_terms['gd_country']);
1024
                }
1025
                if (isset($location_terms['gd_region']) && !$location_manager) {
1026
                    unset($location_terms['gd_region']);
1027
                }
1028
            }
1029
1030 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...
1031 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...
1032 2
            $breadcrumb .= '<li>';
1033 2
            if (get_query_var($gd_post_type . 'category'))
1034 2
                $gd_taxonomy = $gd_post_type . 'category';
1035 2
            elseif (get_query_var($gd_post_type . '_tags'))
1036
                $gd_taxonomy = $gd_post_type . '_tags';
1037
1038 2
            $breadcrumb .= $separator . '<a href="' . $listing_link . '">' . __(ucfirst($post_type_info->label), 'geodirectory') . '</a>';
1039 2
            if (!empty($gd_taxonomy) || geodir_is_page('detail'))
1040 2
                $is_location_last = false;
1041
            else
1042 1
                $is_location_last = true;
1043
1044 2
            if (!empty($gd_taxonomy) && geodir_is_page('listing'))
1045 2
                $is_taxonomy_last = true;
1046
            else
1047 2
                $is_taxonomy_last = false;
1048
1049 2
            if (!empty($location_terms)) {
1050
                $geodir_get_locations = function_exists('get_actual_location_name') ? true : false;
1051
1052
                foreach ($location_terms as $key => $location_term) {
1053
                    if ($location_term != '') {
1054
                        if (!empty($hide_url_part) && in_array($key, $hide_url_part)) { // Hide location part from url & breadcrumb.
1055
                            continue;
1056
                        }
1057
1058
                        $gd_location_link_text = preg_replace('/-(\d+)$/', '', $location_term);
1059
                        $gd_location_link_text = preg_replace('/[_-]/', ' ', $gd_location_link_text);
1060
                        $gd_location_link_text = ucfirst($gd_location_link_text);
1061
1062
                        $location_term_actual_country = '';
1063
                        $location_term_actual_region = '';
1064
                        $location_term_actual_city = '';
1065
                        if ($geodir_get_locations) {
1066
                            if ($key == 'gd_country') {
1067
                                $location_term_actual_country = get_actual_location_name('country', $location_term, true);
1068
                            } else if ($key == 'gd_region') {
1069
                                $location_term_actual_region = get_actual_location_name('region', $location_term, true);
1070
                            } else if ($key == 'gd_city') {
1071
                                $location_term_actual_city = get_actual_location_name('city', $location_term, true);
1072
                            }
1073
                        } else {
1074
                            $location_info = geodir_get_location();
1075
1076
                            if (!empty($location_info) && isset($location_info->location_id)) {
1077
                                if ($key == 'gd_country') {
1078
                                    $location_term_actual_country = __($location_info->country, 'geodirectory');
1079
                                } else if ($key == 'gd_region') {
1080
                                    $location_term_actual_region = __($location_info->region, 'geodirectory');
1081
                                } else if ($key == 'gd_city') {
1082
                                    $location_term_actual_city = __($location_info->city, 'geodirectory');
1083
                                }
1084
                            }
1085
                        }
1086
1087
                        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'] != '')) {
1088
                            $breadcrumb .= $location_term_actual_country != '' ? $separator . $location_term_actual_country : $separator . $gd_location_link_text;
1089
                        } else if ($is_location_last && $key == 'gd_region' && !(isset($location_terms['gd_city']) && $location_terms['gd_city'] != '')) {
1090
                            $breadcrumb .= $location_term_actual_region != '' ? $separator . $location_term_actual_region : $separator . $gd_location_link_text;
1091
                        } else if ($is_location_last && $key == 'gd_city' && empty($location_terms['gd_neighbourhood'])) {
1092
                            $breadcrumb .= $location_term_actual_city != '' ? $separator . $location_term_actual_city : $separator . $gd_location_link_text;
1093
                        } else if ($is_location_last && $key == 'gd_neighbourhood') {
1094
                            $breadcrumb .= $separator . $gd_location_link_text;
1095
                        } else {
1096
                            if (get_option('permalink_structure') != '') {
1097
                                $location_link .= $location_term . '/';
1098
                            } else {
1099
                                $location_link .= "&$key=" . $location_term;
1100
                            }
1101
1102
                            if ($key == 'gd_country' && $location_term_actual_country != '') {
1103
                                $gd_location_link_text = $location_term_actual_country;
1104
                            } else if ($key == 'gd_region' && $location_term_actual_region != '') {
1105
                                $gd_location_link_text = $location_term_actual_region;
1106
                            } else if ($key == 'gd_city' && $location_term_actual_city != '') {
1107
                                $gd_location_link_text = $location_term_actual_city;
1108
                            }
1109
1110
                            /*
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...
1111
                            if (geodir_is_page('detail') && !empty($hide_text_part) && in_array($key, $hide_text_part)) {
1112
                                continue;
1113
                            }
1114
                            */
1115
1116
                            $breadcrumb .= $separator . '<a href="' . $location_link . '">' . $gd_location_link_text . '</a>';
1117
                        }
1118
                    }
1119
                }
1120
            }
1121
1122 2
            if (!empty($gd_taxonomy)) {
1123
                $term_index = 1;
1124
1125
                //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...
1126
                {
1127
                    if (get_query_var($gd_post_type . '_tags')) {
1128
                        $cat_link = $listing_link . 'tags/';
1129
                    } else
1130
                        $cat_link = $listing_link;
1131
1132
                    foreach ($location_terms as $key => $location_term) {
1133
                        if ($location_manager && in_array($key, $hide_url_part)) {
1134
                            continue;
1135
                        }
1136
1137
                        if ($location_term != '') {
1138
                            if (get_option('permalink_structure') != '') {
1139
                                $cat_link .= $location_term . '/';
1140
                            }
1141
                        }
1142
                    }
1143
1144
                    $term_array = explode("/", trim($wp_query->query[$gd_taxonomy], "/"));
1145
                    foreach ($term_array as $term) {
1146
                        $term_link_text = preg_replace('/-(\d+)$/', '', $term);
1147
                        $term_link_text = preg_replace('/[_-]/', ' ', $term_link_text);
1148
1149
                        // get term actual name
1150
                        $term_info = get_term_by('slug', $term, $gd_taxonomy, 'ARRAY_A');
1151
                        if (!empty($term_info) && isset($term_info['name']) && $term_info['name'] != '') {
1152
                            $term_link_text = urldecode($term_info['name']);
1153
                        } else {
1154
                            $term_link_text = geodir_ucwords(urldecode($term_link_text));
1155
                        }
1156
1157
                        if ($term_index == count($term_array) && $is_taxonomy_last)
1158
                            $breadcrumb .= $separator . $term_link_text;
1159
                        else {
1160
                            $cat_link .= $term . '/';
1161
                            $breadcrumb .= $separator . '<a href="' . $cat_link . '">' . $term_link_text . '</a>';
1162
                        }
1163
                        $term_index++;
1164
                    }
1165
                }
1166
1167
1168
            }
1169
1170 2
            if (geodir_is_page('detail'))
1171 2
                $breadcrumb .= $separator . get_the_title();
1172
1173 2
            $breadcrumb .= '</li>';
1174
1175
1176 5
        } elseif (geodir_is_page('author')) {
1177 1
            $user_id = get_current_user_id();
1178 1
            $author_link = get_author_posts_url($user_id);
1179 1
            $default_author_link = geodir_getlink($author_link, array('geodir_dashbord' => 'true', 'stype' => 'gd_place'), false);
1180
1181
            /**
1182
             * Filter author page link.
1183
             *
1184
             * @since 1.0.0
1185
             * @param string $default_author_link Default author link.
1186
             * @param int $user_id Author ID.
1187
             */
1188 1
            $default_author_link = apply_filters('geodir_dashboard_author_link', $default_author_link, $user_id);
1189
1190 1
            $breadcrumb .= '<li>';
1191 1
            $breadcrumb .= $separator . '<a href="' . $default_author_link . '">' . __('My Dashboard', 'geodirectory') . '</a>';
1192
1193 1
            if (isset($_REQUEST['list'])) {
1194
                $author_link = geodir_getlink($author_link, array('geodir_dashbord' => 'true', 'stype' => $_REQUEST['stype']), false);
1195
1196
                /**
1197
                 * Filter author page link.
1198
                 *
1199
                 * @since 1.0.0
1200
                 * @param string $author_link Author page link.
1201
                 * @param int $user_id Author ID.
1202
                 * @param string $_REQUEST['stype'] Post type.
1203
                 */
1204
                $author_link = apply_filters('geodir_dashboard_author_link', $author_link, $user_id, $_REQUEST['stype']);
1205
1206
                $breadcrumb .= $separator . '<a href="' . $author_link . '">' . __(ucfirst($post_type_info->label), 'geodirectory') . '</a>';
1207
                $breadcrumb .= $separator . ucfirst(__('My', 'geodirectory') . ' ' . $_REQUEST['list']);
1208
            } else
1209 1
                $breadcrumb .= $separator . __(ucfirst($post_type_info->label), 'geodirectory');
1210
1211 1
            $breadcrumb .= '</li>';
1212 4
        } elseif (is_category() || is_single()) {
1213
            $category = get_the_category();
1214
            if (is_category()) {
1215
                $breadcrumb .= '<li>' . $separator . $category[0]->cat_name . '</li>';
1216
            }
1217
            if (is_single()) {
1218
                $breadcrumb .= '<li>' . $separator . '<a href="' . get_category_link($category[0]->term_id) . '">' . $category[0]->cat_name . '</a></li>';
1219
                $breadcrumb .= '<li>' . $separator . get_the_title() . '</li>';
1220
            }
1221
            /* End of my version ##################################################### */
1222 3
        } else if (is_page()) {
1223 2
            $page_title = get_the_title();
1224
1225 2
            if (geodir_is_page('location')) {
1226 1
                $page_title = defined('GD_LOCATION') ? GD_LOCATION : __('Location', 'geodirectory');
1227 1
            }
1228
1229 2
            $breadcrumb .= '<li>' . $separator;
1230 2
            $breadcrumb .= stripslashes_deep($page_title);
1231 2
            $breadcrumb .= '</li>';
1232 3
        } else if (is_tag()) {
1233
            $breadcrumb .=  "<li> " . $separator . single_tag_title('',false) . '</li>';
1234 1
        } else if (is_day()) {
1235
            $breadcrumb .= "<li> " . $separator . __(" Archive for", 'geodirectory') . " ";
1236
            the_time('F jS, Y');
1237
            $breadcrumb .= '</li>';
1238 1
        } else if (is_month()) {
1239
            $breadcrumb .= "<li> " . $separator . __(" Archive for", 'geodirectory') . " ";
1240
            the_time('F, Y');
1241
            $breadcrumb .= '</li>';
1242 1
        } else if (is_year()) {
1243
            $breadcrumb .= "<li> " . $separator . __(" Archive for", 'geodirectory') . " ";
1244
            the_time('Y');
1245
            $breadcrumb .= '</li>';
1246 1
        } else if (is_author()) {
1247
            $breadcrumb .= "<li> " . $separator . __(" Author Archive", 'geodirectory');
1248
            $breadcrumb .= '</li>';
1249 1
        } else if (isset($_GET['paged']) && !empty($_GET['paged'])) {
1250
            $breadcrumb .= "<li>" . $separator . __("Blog Archives", 'geodirectory');
1251
            $breadcrumb .= '</li>';
1252 1
        } else if (is_search()) {
1253 1
            $breadcrumb .= "<li> " . $separator . __(" Search Results", 'geodirectory');
1254 1
            $breadcrumb .= '</li>';
1255 1
        }
1256 5
        $breadcrumb .= '</ul></div>';
1257
1258
        /**
1259
         * Filter breadcrumb html output.
1260
         *
1261
         * @since 1.0.0
1262
         * @param string $breadcrumb Breadcrumb HTML.
1263
         * @param string $separator Breadcrumb separator.
1264
         */
1265 5
        echo $breadcrumb = apply_filters('geodir_breadcrumb', $breadcrumb, $separator);
1266 5
    }
1267 5
}
1268
1269
1270
add_action("admin_init", "geodir_allow_wpadmin"); // check user is admin
1271
if (!function_exists('geodir_allow_wpadmin')) {
1272
    /**
1273
     * Allow only admins to access wp-admin.
1274
     *
1275
     * Normal users will be redirected to home page.
1276
     *
1277
     * @since 1.0.0
1278
     * @package GeoDirectory
1279
     * @global object $wpdb WordPress Database object.
1280
     */
1281
    function geodir_allow_wpadmin()
1282
    {
1283 1
        global $wpdb;
1284 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
1285 1
        {
1286
            if (current_user_can('manage_options')) {
1287
            } else {
1288
1289
                wp_redirect(home_url());
1290
                exit;
1291
            }
1292
1293
        }
1294 1
    }
1295
}
1296
1297
1298
/**
1299
 * Move Images from a remote url to upload directory.
1300
 *
1301
 * @since 1.0.0
1302
 * @package GeoDirectory
1303
 * @param string $url The remote image url.
1304
 * @return array|WP_Error The uploaded data as array. When failure returns error.
1305
 */
1306
function fetch_remote_file($url)
1307
{
1308
    // extract the file name and extension from the url
1309 1
    require_once(ABSPATH . 'wp-includes/pluggable.php');
1310 1
    $file_name = basename($url);
1311 1
    if (strpos($file_name, '?') !== false) {
1312
        list($file_name) = explode('?', $file_name);
1313
    }
1314 1
    $dummy = false;
1315 1
    $add_to_cache = false;
1316 1
    $key = null;
1317 1
    if (strpos($url, '/dummy/') !== false) {
1318 1
        $dummy = true;
1319 1
        $key = "dummy_".str_replace('.', '_', $file_name);
1320 1
        $value = get_transient('cached_dummy_images');
1321 1
        if ($value) {
1322 1
            if (isset($value[$key])) {
1323 1
                return $value[$key];
1324
            } else {
1325 1
                $add_to_cache = true;
1326
            }
1327 1
        } else {
1328
            $add_to_cache = true;
1329
        }
1330 1
    }
1331
1332
    // get placeholder file in the upload dir with a unique, sanitized filename
1333
1334 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...
1335
1336 1
    $upload = wp_upload_bits($file_name, 0, '', $post_upload_date);
1337 1
    if ($upload['error'])
1338 1
        return new WP_Error('upload_dir_error', $upload['error']);
1339
1340
    // fetch the remote url and write it to the placeholder file
1341 1
    $headers = wp_remote_get($url, array('stream' => true,'filename' => $upload['file']));
1342
1343 1
    $log_message = '';
1344 1
    $filesize = filesize($upload['file']);
1345
    // request failed
1346 1
    if (!$headers) {
1347
        $log_message = __('Remote server did not respond', 'geodirectory');
1348
    }
1349
    // make sure the fetch was successful
1350 1
    elseif ($headers['response']['code'] != '200') {
1351
        $log_message = sprintf(__('Remote server returned error response %1$d %2$s', 'geodirectory'), esc_html($headers['response']), get_status_header_desc($headers['response']));
1352
    }
1353 1
    elseif (isset($headers['headers']['content-length']) && $filesize != $headers['headers']['content-length']) {
1354
        $log_message =  __('Remote file is incorrect size', 'geodirectory');
1355
    }
1356 1
    elseif (0 == $filesize) {
1357
        $log_message = __('Zero size file downloaded', 'geodirectory');
1358
    }
1359
1360 1
    if($log_message){
1361
        $del = unlink($upload['file']);
1362
        if(!$del){geodir_error_log(__('GeoDirectory: fetch_remote_file() failed to delete temp file.', 'geodirectory'));}
1363
        return new WP_Error('import_file_error',$log_message );
1364
    }
1365
1366 1
    if ($dummy && $add_to_cache && is_array($upload)) {
1367 1
        $images = get_transient('cached_dummy_images');
1368 1
        if(is_array($images))
1369 1
            $images[$key] = $upload;
1370
        else
1371
            $images = array($key => $upload);
1372
1373
        //setting the cache using the WP Transient API
1374 1
        set_transient('cached_dummy_images', $images, 60 * 10); //10 minutes cache
1375 1
    }
1376
1377 1
    return $upload;
1378
}
1379
1380
/**
1381
 * Get maximum file upload size.
1382
 *
1383
 * @since 1.0.0
1384
 * @package GeoDirectory
1385
 * @return string|void Max upload size.
1386
 */
1387 View Code Duplication
function geodir_max_upload_size()
0 ignored issues
show
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 (L3496-3507) 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...
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...
1388
{
1389 1
    $max_filesize = (float)get_option('geodir_upload_max_filesize', 2);
1390
1391 1
    if ($max_filesize > 0 && $max_filesize < 1) {
1392
        $max_filesize = (int)($max_filesize * 1024) . 'kb';
1393
    } else {
1394 1
        $max_filesize = $max_filesize > 0 ? $max_filesize . 'mb' : '2mb';
1395
    }
1396
1397
    /**
1398
     * Filter default image upload size limit.
1399
     *
1400
     * @since 1.0.0
1401
     * @param string $max_filesize Max file upload size. Ex. 10mb, 512kb.
1402
     */
1403 1
    return apply_filters('geodir_default_image_upload_size_limit', $max_filesize);
1404
}
1405
1406
/**
1407
 * Check if dummy folder exists or not.
1408
 *
1409
 * Check if dummy folder exists or not , if not then fetch from live url.
1410
 *
1411
 * @since 1.0.0
1412
 * @package GeoDirectory
1413
 * @return bool If dummy folder exists returns true, else false.
1414
 */
1415
function geodir_dummy_folder_exists()
1416
{
1417 1
    $path = geodir_plugin_path() . '/geodirectory-admin/dummy/';
1418 1
    if (!is_dir($path))
1419 1
        return false;
1420
    else
1421
        return true;
1422
1423
}
1424
1425
/**
1426
 * Get the author info.
1427
 *
1428
 * @since 1.0.0
1429
 * @package GeoDirectory
1430
 * @global object $wpdb WordPress Database object.
1431
 * @param int $aid The author ID.
1432
 * @return object Author info.
1433
 */
1434
function  geodir_get_author_info($aid)
1435
{
1436
    global $wpdb;
1437
    /*$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...
1438
    $infosql = $wpdb->prepare("select * from $wpdb->users where ID=%d", array($aid));
1439
    $info = $wpdb->get_results($infosql);
1440
    if ($info) {
1441
        return $info[0];
1442
    }
1443
}
1444
1445
if (!function_exists('adminEmail')) {
1446
    /**
1447
     * Send emails to client on post submission, renew etc.
1448
     *
1449
     * @since 1.0.0
1450
     * @package GeoDirectory
1451
     * @global object $wpdb WordPress Database object.
1452
     * @param int|string $page_id Page ID.
1453
     * @param int|string $user_id User ID.
1454
     * @param string $message_type Can be 'expiration','post_submited','renew','upgrade','claim_approved','claim_rejected','claim_requested','auto_claim','payment_success','payment_fail'.
1455
     * @param string $custom_1 Custom data to be sent.
1456
     */
1457
    function adminEmail($page_id, $user_id, $message_type, $custom_1 = '')
1458
    {
1459
        global $wpdb;
1460
        if ($message_type == 'expiration') {
1461
            $subject = stripslashes(__(get_option('renew_email_subject'),'geodirectory'));
1462
            $client_message = stripslashes(__(get_option('renew_email_content'),'geodirectory'));
1463
        } elseif ($message_type == 'post_submited') {
1464
            $subject = __(get_option('post_submited_success_email_subject_admin'),'geodirectory');
1465
            $client_message = __(get_option('post_submited_success_email_content_admin'),'geodirectory');
1466
        } elseif ($message_type == 'renew') {
1467
            $subject = __(get_option('post_renew_success_email_subject_admin'),'geodirectory');
1468
            $client_message = __(get_option('post_renew_success_email_content_admin'),'geodirectory');
1469
        } elseif ($message_type == 'upgrade') {
1470
            $subject = __(get_option('post_upgrade_success_email_subject_admin'),'geodirectory');
1471
            $client_message = __(get_option('post_upgrade_success_email_content_admin'),'geodirectory');
1472
        } elseif ($message_type == 'claim_approved') {
1473
            $subject = __(get_option('claim_approved_email_subject'),'geodirectory');
1474
            $client_message = __(get_option('claim_approved_email_content'),'geodirectory');
1475
        } elseif ($message_type == 'claim_rejected') {
1476
            $subject = __(get_option('claim_rejected_email_subject'),'geodirectory');
1477
            $client_message = __(get_option('claim_rejected_email_content'),'geodirectory');
1478
        } elseif ($message_type == 'claim_requested') {
1479
            $subject = __(get_option('claim_email_subject_admin'),'geodirectory');
1480
            $client_message = __(get_option('claim_email_content_admin'),'geodirectory');
1481
        } elseif ($message_type == 'auto_claim') {
1482
            $subject = __(get_option('auto_claim_email_subject'),'geodirectory');
1483
            $client_message = __(get_option('auto_claim_email_content'),'geodirectory');
1484
        } elseif ($message_type == 'payment_success') {
1485
            $subject = __(get_option('post_payment_success_admin_email_subject'),'geodirectory');
1486
            $client_message = __(get_option('post_payment_success_admin_email_content'),'geodirectory');
1487
        } elseif ($message_type == 'payment_fail') {
1488
            $subject = __(get_option('post_payment_fail_admin_email_subject'),'geodirectory');
1489
            $client_message = __(get_option('post_payment_fail_admin_email_content'),'geodirectory');
1490
        }
1491
        $transaction_details = $custom_1;
1492
        $fromEmail = get_option('site_email');
1493
        $fromEmailName = get_site_emailName();
1494
//$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...
1495
        $pkg_limit = get_property_price_info_listing($page_id);
1496
        $alivedays = $pkg_limit['days'];
1497
        $productlink = get_permalink($page_id);
1498
        $post_info = get_post($page_id);
1499
        $post_date = date('dS F,Y', strtotime($post_info->post_date));
1500
        $listingLink = '<a href="' . $productlink . '"><b>' . $post_info->post_title . '</b></a>';
1501
        $loginurl = geodir_login_url();
1502
        $loginurl_link = '<a href="' . $loginurl . '">login</a>';
1503
        $siteurl = home_url();
1504
        $siteurl_link = '<a href="' . $siteurl . '">' . $fromEmailName . '</a>';
1505
        $user_info = get_userdata($user_id);
1506
        $user_email = $user_info->user_email;
1507
        $display_name = geodir_get_client_name($user_id);
1508
        $user_login = $user_info->user_login;
1509
        $number_of_grace_days = get_option('ptthemes_listing_preexpiry_notice_days');
1510
        if ($number_of_grace_days == '') {
1511
            $number_of_grace_days = 1;
1512
        }
1513
        if ($post_info->post_type == 'event') {
1514
            $post_type = 'event';
1515
        } else {
1516
            $post_type = 'listing';
1517
        }
1518
        $renew_link = '<a href="' . $siteurl . '?ptype=post_' . $post_type . '&renew=1&pid=' . $page_id . '">' . RENEW_LINK . '</a>';
1519
        $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#]');
1520
        $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);
1521
        $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...
1522
        $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...
1523
        $headers = 'MIME-Version: 1.0' . "\r\n";
1524
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
1525
        $headers .= 'From: ' . $fromEmailName . ' <' . $fromEmail . '>' . "\r\n";
1526
1527
        $to = $fromEmail;
1528
        $message = $client_message;
1529
1530
1531
        /**
1532
         * Filter the admin email to address.
1533
         *
1534
         * @since 1.6.1
1535
         * @package GeoDirectory
1536
         * @param string $to The email address the email is being sent to.
1537
         * @param int|string $page_id Page ID.
1538
         * @param int|string $user_id User ID.
1539
         * @param string $message_type Can be 'expiration','post_submited','renew','upgrade','claim_approved','claim_rejected','claim_requested','auto_claim','payment_success','payment_fail'.
1540
         * @param string $custom_1 Custom data to be sent.
1541
         */
1542
        $to = apply_filters('geodir_adminEmail_to',$to,$page_id, $user_id, $message_type, $custom_1 );
1543
        /**
1544
         * Filter the admin email subject.
1545
         *
1546
         * @since 1.6.1
1547
         * @package GeoDirectory_Payment_Manager
1548
         * @param string $subject The email subject.
1549
         * @param int|string $page_id Page ID.
1550
         * @param int|string $user_id User ID.
1551
         * @param string $message_type Can be 'expiration','post_submited','renew','upgrade','claim_approved','claim_rejected','claim_requested','auto_claim','payment_success','payment_fail'.
1552
         * @param string $custom_1 Custom data to be sent.
1553
         */
1554
        $subject = apply_filters('geodir_adminEmail_subject',$subject,$page_id, $user_id, $message_type, $custom_1);
1555
        /**
1556
         * Filter the admin email message.
1557
         *
1558
         * @since 1.6.1
1559
         * @package GeoDirectory_Payment_Manager
1560
         * @param string $message The email message text.
1561
         * @param int|string $page_id Page ID.
1562
         * @param int|string $user_id User ID.
1563
         * @param string $message_type Can be 'expiration','post_submited','renew','upgrade','claim_approved','claim_rejected','claim_requested','auto_claim','payment_success','payment_fail'.
1564
         * @param string $custom_1 Custom data to be sent.
1565
         */
1566
        $message = apply_filters('geodir_adminEmail_message',$message,$page_id, $user_id, $message_type, $custom_1);
1567
        /**
1568
         * Filter the admin email headers.
1569
         *
1570
         * @since 1.6.1
1571
         * @package GeoDirectory_Payment_Manager
1572
         * @param string $headers The email headers.
1573
         * @param int|string $page_id Page ID.
1574
         * @param int|string $user_id User ID.
1575
         * @param string $message_type Can be 'expiration','post_submited','renew','upgrade','claim_approved','claim_rejected','claim_requested','auto_claim','payment_success','payment_fail'.
1576
         * @param string $custom_1 Custom data to be sent.
1577
         */
1578
        $headers = apply_filters('geodir_adminEmail_headers',$headers,$page_id, $user_id, $message_type, $custom_1);
1579
1580
1581
1582
        $sent = wp_mail($to, $subject, $message, $headers);
1583
        if( ! $sent ) {
1584
            if ( is_array( $to ) ) {
1585
                $to = implode( ',', $to );
1586
            }
1587
            $log_message = sprintf(
1588
                __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
1589
                $message_type,
1590
                date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
1591
                $to,
1592
                $subject
1593
            );
1594
            geodir_error_log( $log_message );
1595
        }
1596
    }
1597
}
1598
1599
if (!function_exists('sendEmail')) {
1600
    /**
1601
     * @todo could be a duplicate of geodir_sendEmail.
1602
     *
1603
     * @since 1.0.0
1604
     * @package GeoDirectory
1605
     * @param string $fromEmail Sender email address.
1606
     * @param string $fromEmailName Sender name.
1607
     * @param string $toEmail Receiver email address.
1608
     * @param string $toEmailName Receiver name.
1609
     * @param string $to_subject Email subject.
1610
     * @param string $to_message Email content.
1611
     * @param string $extra Not being used.
1612
     * @param string $message_type The message type. Can be send_friend, send_enquiry, forgot_password, registration.
1613
     * @param string $post_id The post ID.
1614
     * @param string $user_id The user ID.
1615
     */
1616
    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...
1617
    {
1618
        $login_details = '';
1619
        if ($message_type == 'send_friend') {
1620
            $subject = stripslashes(__(get_option('email_friend_subject'),'geodirectory'));
1621
            $message = stripslashes(__(get_option('email_friend_content'),'geodirectory'));
1622
        } elseif ($message_type == 'send_enquiry') {
1623
            $subject = __(get_option('email_enquiry_subject'),'geodirectory');
1624
            $message = __(get_option('email_enquiry_content'),'geodirectory');
1625
        } elseif ($message_type == 'forgot_password') {
1626
            $subject = __(get_option('forgot_password_subject'),'geodirectory');
1627
            $message = __(get_option('forgot_password_content'),'geodirectory');
1628
            $login_details = $to_message;
1629
        } elseif ($message_type == 'registration') {
1630
            $subject = __(get_option('registration_success_email_subject'),'geodirectory');
1631
            $message = __(get_option('registration_success_email_content'),'geodirectory');
1632
            $login_details = $to_message;
1633
        }
1634
        $to_message = nl2br($to_message);
1635
        $sitefromEmail = get_option('site_email');
1636
        $sitefromEmailName = get_site_emailName();
1637
        $productlink = get_permalink($post_id);
1638
        $post_info = get_post($post_id);
1639
        $listingLink = '<a href="' . $productlink . '"><b>' . $post_info->post_title . '</b></a>';
1640
        $siteurl = home_url();
1641
        $siteurl_link = '<a href="' . $siteurl . '">' . $siteurl . '</a>';
1642
        $loginurl = geodir_login_url();
1643
        $loginurl_link = '<a href="' . $loginurl . '">login</a>';
1644
        if ($fromEmail == '') {
1645
            $fromEmail = get_option('site_email');
1646
        }
1647
        if ($fromEmailName == '') {
1648
            $fromEmailName = get_option('site_email_name');
1649
        }
1650
        $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#comments#]', '[#login_url#]', '[#login_details#]', '[#client_name#]');
1651
        $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $to_message, $loginurl_link, $login_details, $toEmailName);
1652
        $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...
1653
1654
        $search_array = array('[#listing_link#]', '[#site_name_url#]', '[#post_id#]', '[#site_name#]', '[#to_name#]', '[#from_name#]', '[#subject#]', '[#client_name#]');
1655
        $replace_array = array($listingLink, $siteurl_link, $post_id, $sitefromEmailName, $toEmailName, $fromEmailName, $to_subject, $toEmailName);
1656
        $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...
1657
        $headers = 'MIME-Version: 1.0' . "\r\n";
1658
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
1659
        $headers .= "Reply-To: " . $fromEmail . "\r\n";
1660
        $headers .= 'From: ' . $sitefromEmailName . ' <' . $sitefromEmail . '>' . "\r\n";
1661
1662
        $to = $toEmail;
1663
1664
        $sent = wp_mail($to, $subject, $message, $headers);
1665
        if( ! $sent ) {
1666
            if ( is_array( $to ) ) {
1667
                $to = implode( ',', $to );
1668
            }
1669
            $log_message = sprintf(
1670
                __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
1671
                $message_type,
1672
                date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
1673
                $to,
1674
                $subject
1675
            );
1676
            geodir_error_log( $log_message );
1677
        }
1678
1679
        ///////// ADMIN BCC EMIALS
1680
        $admin_bcc = false;
1681
        if ($message_type == 'registration') {
1682
            $message_raw = explode(__("Password:", 'geodirectory'), $message);
1683
            $message_raw2 = explode("</p>", $message_raw[1], 2);
1684
            $message = $message_raw[0] . __('Password:', 'geodirectory') . ' **********</p>' . $message_raw2[1];
1685
        }
1686
        $adminEmail = get_bloginfo('admin_email');
1687
        $to = $adminEmail;
1688
1689
        if ($message_type == 'registration' && get_option('bcc_new_user')) {
1690
            $subject .= ' - ADMIN BCC COPY';
1691
            $admin_bcc = true;
1692
        }
1693
        elseif ($message_type == 'send_friend' && get_option('bcc_friend')) {
1694
            $subject .= ' - ADMIN BCC COPY';
1695
            $admin_bcc = true;
1696
        }
1697
        elseif ($message_type == 'send_enquiry' && get_option('bcc_enquiry')) {
1698
            $subject .= ' - ADMIN BCC COPY';
1699
            $admin_bcc = true;
1700
        }
1701
1702 View Code Duplication
        if($admin_bcc === true){
1703
            $sent = wp_mail($to, $subject, $message, $headers);
1704
            if( ! $sent ) {
1705
                if ( is_array( $to ) ) {
1706
                    $to = implode( ',', $to );
1707
                }
1708
                $log_message = sprintf(
1709
                    __( "Email from GeoDirectory failed to send.\nMessage type: %s\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'geodirectory' ),
1710
                    $message_type,
1711
                    date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ),
1712
                    $to,
1713
                    $subject
1714
                );
1715
                geodir_error_log( $log_message );
1716
            }
1717
        }
1718
1719
    }
1720
}
1721
1722
/*
1723
Language translation helper functions
1724
*/
1725
1726
/**
1727
 * Function to get the translated category id's.
1728
 *
1729
 * @since 1.0.0
1730
 * @package GeoDirectory
1731
 * @param array $ids_array Category IDs.
1732
 * @param string $type Category taxonomy.
1733
 * @return array Category IDs.
1734
 */
1735
function gd_lang_object_ids($ids_array, $type)
1736
{
1737
    if (function_exists('icl_object_id')) {
1738
        $res = array();
1739
        foreach ($ids_array as $id) {
1740
            $xlat = icl_object_id($id, $type, false);
1741
            if (!is_null($xlat)) $res[] = $xlat;
1742
        }
1743
        return $res;
1744
    } else {
1745
        return $ids_array;
1746
    }
1747
}
1748
1749
1750
/**
1751
 * function to add class to body when multi post type is active.
1752
 *
1753
 * @since 1.0.0
1754
 * @since 1.5.6 Add geodir-page class to body for all gd pages.
1755
 * @package GeoDirectory
1756
 * @global object $wpdb WordPress Database object.
1757
 * @param array $classes Body CSS classes.
1758
 * @return array Modified Body CSS classes.
1759
 */
1760
function geodir_custom_posts_body_class($classes) {
1761 7
    global $wpdb, $wp;
1762 7
    $post_types = geodir_get_posttypes('object');
1763 7
    if (!empty($post_types) && count((array)$post_types) > 1) {
1764
        $classes[] = 'geodir_custom_posts';
1765
    }
1766
1767
    // fix body class for signup page
1768 7
    if (geodir_is_page('login')) {
1769
        $new_classes = array();
1770
        $new_classes[] = 'signup page-geodir-signup';
1771
        if (!empty($classes)) {
1772
            foreach ($classes as $class) {
1773
                if ($class && $class != 'home' && $class != 'blog') {
1774
                    $new_classes[] = $class;
1775
                }
1776
            }
1777
        }
1778
        $classes = $new_classes;
1779
    }
1780
1781 7
    if (geodir_is_geodir_page()) {
1782
        $classes[] = 'geodir-page';
1783
    }
1784
1785 7
    return $classes;
1786
}
1787
1788
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
1789
1790
1791
/**
1792
 * Returns available map zoom levels.
1793
 *
1794
 * @since 1.0.0
1795
 * @package GeoDirectory
1796
 * @return array Available map zoom levels.
1797
 */
1798
function geodir_map_zoom_level()
1799
{
1800
    /**
1801
     * Filter GD map zoom level.
1802
     *
1803
     * @since 1.0.0
1804
     */
1805 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));
1806
1807
}
1808
1809
1810
/**
1811
 * This function takes backup of an option so they can be restored later.
1812
 *
1813
 * @since 1.0.0
1814
 * @package GeoDirectory
1815
 * @param string $geodir_option_name Option key.
1816
 */
1817
function geodir_option_version_backup($geodir_option_name)
1818
{
1819
    $version_date = time();
1820
    $geodir_option = get_option($geodir_option_name);
1821
1822
    if (!empty($geodir_option)) {
1823
        add_option($geodir_option_name . '_' . $version_date, $geodir_option);
1824
    }
1825
}
1826
1827
/**
1828
 * display add listing page for wpml.
1829
 *
1830
 * @since 1.0.0
1831
 * @package GeoDirectory
1832
 * @param int $page_id The page ID.
1833
 * @return int Page ID.
1834
 */
1835
function get_page_id_geodir_add_listing_page($page_id)
1836
{
1837 18
    if (geodir_wpml_multilingual_status()) {
1838
        $post_type = 'post_page';
1839
        $page_id = geodir_get_wpml_element_id($page_id, $post_type);
1840
    }
1841 18
    return $page_id;
1842
}
1843
1844
/**
1845
 * Returns wpml multilingual status.
1846
 *
1847
 * @since 1.0.0
1848
 * @package GeoDirectory
1849
 * @return bool Returns true when sitepress multilingual CMS active. else returns false.
1850
 */
1851
function geodir_wpml_multilingual_status()
1852
{
1853 18
    if (function_exists('icl_object_id')) {
1854
        return true;
1855
    }
1856 18
    return false;
1857
}
1858
1859
/**
1860
 * Returns WPML element ID.
1861
 *
1862
 * @since 1.0.0
1863
 * @package GeoDirectory
1864
 * @param int $page_id The page ID.
1865
 * @param string $post_type The post type.
1866
 * @return int Element ID when exists. Else the page id.
1867
 */
1868
function geodir_get_wpml_element_id($page_id, $post_type)
1869
{
1870
    global $sitepress;
1871
    if (geodir_wpml_multilingual_status() && !empty($sitepress) && isset($sitepress->queries)) {
1872
        $trid = $sitepress->get_element_trid($page_id, $post_type);
1873
1874
        if ($trid > 0) {
1875
            $translations = $sitepress->get_element_translations($trid, $post_type);
1876
1877
            $lang = $sitepress->get_current_language();
1878
            $lang = $lang ? $lang : $sitepress->get_default_language();
1879
1880
            if (!empty($translations) && !empty($lang) && isset($translations[$lang]) && isset($translations[$lang]->element_id) && !empty($translations[$lang]->element_id)) {
1881
                $page_id = $translations[$lang]->element_id;
1882
            }
1883
        }
1884
    }
1885
    return $page_id;
1886
}
1887
1888
/**
1889
 * WPML check elemet ID.
1890
 *
1891
 * @since 1.0.0
1892
 * @package GeoDirectory
1893
 * @deprecated 1.4.6 No longer needed as we handel translating GD pages as normal now.
1894
 */
1895
function geodir_wpml_check_element_id()
1896
{
1897
    global $sitepress;
1898
    if (geodir_wpml_multilingual_status() && !empty($sitepress) && isset($sitepress->queries)) {
1899
        $el_type = 'post_page';
1900
        $el_id = get_option('geodir_add_listing_page');
1901
        $default_lang = $sitepress->get_default_language();
1902
        $el_details = $sitepress->get_element_language_details($el_id, $el_type);
1903
1904
        if (!($el_id > 0 && $default_lang && !empty($el_details) && isset($el_details->language_code) && $el_details->language_code == $default_lang)) {
1905
            if (!$el_details->source_language_code) {
1906
                $sitepress->set_element_language_details($el_id, $el_type, '', $default_lang);
1907
                $sitepress->icl_translations_cache->clear();
1908
            }
1909
        }
1910
    }
1911
}
1912
1913
/**
1914
 * Returns orderby SQL using the given query args.
1915
 *
1916
 * @since 1.0.0
1917
 * @package GeoDirectory
1918
 * @global object $wpdb WordPress Database object.
1919
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1920
 * @param array $query_args The query array.
1921
 * @return string Orderby SQL.
1922
 */
1923
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...
1924
{
1925 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
1926
1927 8
    $query_args = $gd_query_args_widgets;
1928 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
1929
        return $wpdb->posts . ".post_date DESC, ";
1930
    }
1931
1932 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
1933 8
    $table = $plugin_prefix . $post_type . '_detail';
1934
1935 8
    $sort_by = !empty($query_args['order_by']) ? $query_args['order_by'] : '';
1936
1937
    switch ($sort_by) {
1938 8
        case 'latest':
1939 8
        case 'newest':
1940 4
            $orderby = $wpdb->posts . ".post_date DESC, ";
1941 4
            break;
1942 4
        case 'featured':
1943
            $orderby = $table . ".is_featured ASC, ";
1944
            break;
1945 4
        case 'az':
1946
            $orderby = $wpdb->posts . ".post_title ASC, ";
1947
            break;
1948 4
        case 'high_review':
1949 3
            $orderby = $table . ".rating_count DESC, " . $table . ".overall_rating DESC, ";
1950 3
            break;
1951 1
        case 'high_rating':
1952
            $orderby = "( " . $table . ".overall_rating  ) DESC, ";
1953
            break;
1954 1
        case 'random':
1955
            $orderby = "RAND(), ";
1956
            break;
1957 1
        default:
1958 1
            $orderby = $wpdb->posts . ".post_title ASC, ";
1959 1
            break;
1960 1
    }
1961
1962 8
    return $orderby;
1963
}
1964
1965
/**
1966
 * Retrieve listings/count using requested filter parameters.
1967
 *
1968
 * @since 1.0.0
1969
 * @package GeoDirectory
1970
 * @since 1.4.2 New paramater $count_only added
1971
 * @global object $wpdb WordPress Database object.
1972
 * @global string $plugin_prefix Geodirectory plugin table prefix.
1973
 * @global string $table_prefix WordPress Database Table prefix.
1974
 * @param array $query_args The query array.
1975
 * @param  int|bool $count_only If true returns listings count only, otherwise returns array
1976
 * @return mixed Result object.
1977
 */
1978
function geodir_get_widget_listings($query_args = array(), $count_only = false)
1979
{
1980 8
    global $wpdb, $plugin_prefix, $table_prefix;
1981 8
    $GLOBALS['gd_query_args_widgets'] = $query_args;
1982 8
    $gd_query_args_widgets = $query_args;
1983
1984 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
1985 8
    $table = $plugin_prefix . $post_type . '_detail';
1986
1987 8
    $fields = $wpdb->posts . ".*, " . $table . ".*";
1988
    /**
1989
     * Filter widget listing fields string part that is being used for query.
1990
     *
1991
     * @since 1.0.0
1992
     * @param string $fields Fields string.
1993
     * @param string $table Table name.
1994
     * @param string $post_type Post type.
1995
     */
1996 8
    $fields = apply_filters('geodir_filter_widget_listings_fields', $fields, $table, $post_type);
1997
1998 8
    $join = "INNER JOIN " . $table . " ON (" . $table . ".post_id = " . $wpdb->posts . ".ID)";
1999
2000
    ########### WPML ###########
2001
2002 8
    if (function_exists('icl_object_id')) {
2003
        global $sitepress;
2004
        $lang_code = ICL_LANGUAGE_CODE;
2005
        if ($lang_code) {
2006
            $join .= " JOIN " . $table_prefix . "icl_translations icl_t ON icl_t.element_id = " . $table_prefix . "posts.ID";
2007
        }
2008
    }
2009
2010
    ########### WPML ###########
2011
2012
    /**
2013
     * Filter widget listing join clause string part that is being used for query.
2014
     *
2015
     * @since 1.0.0
2016
     * @param string $join Join clause string.
2017
     * @param string $post_type Post type.
2018
     */
2019 8
    $join = apply_filters('geodir_filter_widget_listings_join', $join, $post_type);
2020
2021 8
    $post_status = is_super_admin() ? " OR " . $wpdb->posts . ".post_status = 'private'" : '';
2022
2023 8
    $where = " AND ( " . $wpdb->posts . ".post_status = 'publish' " . $post_status . " ) AND " . $wpdb->posts . ".post_type = '" . $post_type . "'";
2024
2025
    ########### WPML ###########
2026 8
    if (function_exists('icl_object_id')) {
2027
        if ($lang_code) {
2028
            $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...
2029
        }
2030
    }
2031
    ########### WPML ###########
2032
    /**
2033
     * Filter widget listing where clause string part that is being used for query.
2034
     *
2035
     * @since 1.0.0
2036
     * @param string $where Where clause string.
2037
     * @param string $post_type Post type.
2038
     */
2039 8
    $where = apply_filters('geodir_filter_widget_listings_where', $where, $post_type);
2040 8
    $where = $where != '' ? " WHERE 1=1 " . $where : '';
2041
2042 8
    $groupby = " GROUP BY $wpdb->posts.ID ";
2043
    /**
2044
     * Filter widget listing groupby clause string part that is being used for query.
2045
     *
2046
     * @since 1.0.0
2047
     * @param string $groupby Group by clause string.
2048
     * @param string $post_type Post type.
2049
     */
2050 8
    $groupby = apply_filters('geodir_filter_widget_listings_groupby', $groupby, $post_type);
2051
2052 8
    if ($count_only) {
2053 1
        $sql = "SELECT COUNT(" . $wpdb->posts . ".ID) AS total FROM " . $wpdb->posts . "
2054 1
			" . $join . "
2055 1
			" . $where;
2056 1
        $rows = (int)$wpdb->get_var($sql);
2057 1
    } else {
2058 8
        $orderby = geodir_widget_listings_get_order($query_args);
2059
        /**
2060
         * Filter widget listing orderby clause string part that is being used for query.
2061
         *
2062
         * @since 1.0.0
2063
         * @param string $orderby Order by clause string.
2064
         * @param string $table Table name.
2065
         * @param string $post_type Post type.
2066
         */
2067 8
        $orderby = apply_filters('geodir_filter_widget_listings_orderby', $orderby, $table, $post_type);
2068 8
        $orderby .= $wpdb->posts . ".post_title ASC";
2069 8
        $orderby = $orderby != '' ? " ORDER BY " . $orderby : '';
2070
2071 8
        $limit = !empty($query_args['posts_per_page']) ? $query_args['posts_per_page'] : 5;
2072
        /**
2073
         * Filter widget listing limit that is being used for query.
2074
         *
2075
         * @since 1.0.0
2076
         * @param int $limit Query results limit.
2077
         * @param string $post_type Post type.
2078
         */
2079 8
        $limit = apply_filters('geodir_filter_widget_listings_limit', $limit, $post_type);
2080
2081 8
        $page = !empty($query_args['pageno']) ? absint($query_args['pageno']) : 1;
2082 8
        if ( !$page )
2083 8
            $page = 1;
2084
2085 8
        $limit = (int)$limit > 0 ? " LIMIT " . absint( ( $page - 1 ) * (int)$limit ) . ", " . (int)$limit : "";
2086
2087 8
        $sql = "SELECT SQL_CALC_FOUND_ROWS " . $fields . " FROM " . $wpdb->posts . "
2088 8
			" . $join . "
2089 8
			" . $where . "
2090 8
			" . $groupby . "
2091 8
			" . $orderby . "
2092 8
			" . $limit;
2093 8
        $rows = $wpdb->get_results($sql);
2094
    }
2095
2096 8
    unset($GLOBALS['gd_query_args_widgets']);
2097 8
    unset($gd_query_args_widgets);
2098
2099 8
    return $rows;
2100
}
2101
2102
/**
2103
 * Listing query fields SQL part for widgets.
2104
 *
2105
 * @since 1.0.0
2106
 * @package GeoDirectory
2107
 * @global object $wpdb WordPress Database object.
2108
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2109
 * @param string $fields Fields SQL.
2110
 * @return string Modified fields SQL.
2111
 */
2112
function geodir_function_widget_listings_fields($fields)
2113
{
2114 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2115
2116 8
    $query_args = $gd_query_args_widgets;
2117 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2118
        return $fields;
2119
    }
2120
    
2121 8
    return $fields;
2122
}
2123
2124
/**
2125
 * Listing query join clause SQL part for widgets.
2126
 *
2127
 * @since 1.0.0
2128
 * @package GeoDirectory
2129
 * @global object $wpdb WordPress Database object.
2130
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2131
 * @param string $join Join clause SQL.
2132
 * @return string Modified join clause SQL.
2133
 */
2134
function geodir_function_widget_listings_join($join)
2135
{
2136 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2137
2138 8
    $query_args = $gd_query_args_widgets;
2139 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2140
        return $join;
2141
    }
2142
2143 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
2144 8
    $table = $plugin_prefix . $post_type . '_detail';
2145
2146 8 View Code Duplication
    if (!empty($query_args['with_pics_only'])) {
2147
        $join .= " LEFT JOIN " . GEODIR_ATTACHMENT_TABLE . " ON ( " . GEODIR_ATTACHMENT_TABLE . ".post_id=" . $table . ".post_id AND " . GEODIR_ATTACHMENT_TABLE . ".mime_type LIKE '%image%' )";
2148
    }
2149
2150 8 View Code Duplication
    if (!empty($query_args['tax_query'])) {
2151 4
        $tax_queries = get_tax_sql($query_args['tax_query'], $wpdb->posts, 'ID');
2152 4
        if (!empty($tax_queries['join']) && !empty($tax_queries['where'])) {
2153 2
            $join .= $tax_queries['join'];
2154 2
        }
2155 4
    }
2156
2157 8
    return $join;
2158
}
2159
2160
/**
2161
 * Listing query where clause SQL part for widgets.
2162
 *
2163
 * @since 1.0.0
2164
 * @package GeoDirectory
2165
 * @global object $wpdb WordPress Database object.
2166
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2167
 * @param string $where Where clause SQL.
2168
 * @return string Modified where clause SQL.
2169
 */
2170
function geodir_function_widget_listings_where($where)
2171
{
2172 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2173
2174 8
    $query_args = $gd_query_args_widgets;
2175 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2176
        return $where;
2177
    }
2178 8
    $post_type = empty($query_args['post_type']) ? 'gd_place' : $query_args['post_type'];
2179 8
    $table = $plugin_prefix . $post_type . '_detail';
2180
2181 8
    if (!empty($query_args)) {
2182 8
        if (!empty($query_args['gd_location']) && function_exists('geodir_default_location_where')) {
2183
            $where = geodir_default_location_where($where, $table);
2184
        }
2185
2186 8
        if (!empty($query_args['post_author'])) {
2187
            $where .= " AND " . $wpdb->posts . ".post_author = " . (int)$query_args['post_author'];
2188
        }
2189
        
2190 8
        if (!empty($query_args['show_featured_only'])) {
2191 2
            $where .= " AND " . $table . ".is_featured = '1'";
2192 2
        }
2193
2194 8
        if (!empty($query_args['show_special_only'])) {
2195
            $where .= " AND ( " . $table . ".geodir_special_offers != '' AND " . $table . ".geodir_special_offers IS NOT NULL )";
2196
        }
2197
2198 8
        if (!empty($query_args['with_pics_only'])) {
2199
            $where .= " AND " . GEODIR_ATTACHMENT_TABLE . ".ID IS NOT NULL ";
2200
        }
2201
2202 8
        if (!empty($query_args['featured_image_only'])) {
2203 2
            $where .= " AND " . $table . ".featured_image IS NOT NULL AND " . $table . ".featured_image!='' ";
2204 2
        }
2205
2206 8
        if (!empty($query_args['with_videos_only'])) {
2207
            $where .= " AND ( " . $table . ".geodir_video != '' AND " . $table . ".geodir_video IS NOT NULL )";
2208
        }
2209
2210 8 View Code Duplication
        if (!empty($query_args['tax_query'])) {
2211 4
            $tax_queries = get_tax_sql($query_args['tax_query'], $wpdb->posts, 'ID');
2212
2213 4
            if (!empty($tax_queries['join']) && !empty($tax_queries['where'])) {
2214 2
                $where .= $tax_queries['where'];
2215 2
            }
2216 4
        }
2217 8
    }
2218
2219 8
    return $where;
2220
}
2221
2222
/**
2223
 * Listing query orderby clause SQL part for widgets.
2224
 *
2225
 * @since 1.0.0
2226
 * @package GeoDirectory
2227
 * @global object $wpdb WordPress Database object.
2228
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2229
 * @param string $orderby Orderby clause SQL.
2230
 * @return string Modified orderby clause SQL.
2231
 */
2232
function geodir_function_widget_listings_orderby($orderby)
2233
{
2234 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2235
2236 8
    $query_args = $gd_query_args_widgets;
2237 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2238
        return $orderby;
2239
    }
2240
2241 8
    return $orderby;
2242
}
2243
2244
/**
2245
 * Listing query limit for widgets.
2246
 *
2247
 * @since 1.0.0
2248
 * @package GeoDirectory
2249
 * @global object $wpdb WordPress Database object.
2250
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2251
 * @param int $limit Query limit.
2252
 * @return int Query limit.
2253
 */
2254
function geodir_function_widget_listings_limit($limit)
2255
{
2256 8
    global $wpdb, $plugin_prefix, $gd_query_args_widgets;
2257
2258 8
    $query_args = $gd_query_args_widgets;
2259 8
    if (empty($query_args) || empty($query_args['is_geodir_loop'])) {
2260
        return $limit;
2261
    }
2262
2263 8
    if (!empty($query_args) && !empty($query_args['posts_per_page'])) {
2264 8
        $limit = (int)$query_args['posts_per_page'];
2265 8
    }
2266
2267 8
    return $limit;
2268
}
2269
2270
/**
2271
 * WP media large width.
2272
 *
2273
 * @since 1.0.0
2274
 * @package GeoDirectory
2275
 * @param int $default Default width.
2276
 * @param string|array $params Image parameters.
2277
 * @return int Large size width.
2278
 */
2279 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...
2280
{
2281 2
    $large_size_w = get_option('large_size_w');
2282 2
    $large_size_w = $large_size_w > 0 ? $large_size_w : $default;
2283 2
    $large_size_w = absint($large_size_w);
2284
2285 2
    if (!get_option('geodir_use_wp_media_large_size')) {
2286 2
        $large_size_w = 800;
2287 2
    }
2288
2289
    /**
2290
     * Filter large image width.
2291
     *
2292
     * @since 1.0.0
2293
     * @param int $large_size_w Large image width.
2294
     * @param int $default Default width.
2295
     * @param string|array $params Image parameters.
2296
     */
2297 2
    $large_size_w = apply_filters('geodir_filter_media_image_large_width', $large_size_w, $default, $params);
2298 2
    return $large_size_w;
2299
}
2300
2301
/**
2302
 * WP media large height.
2303
 *
2304
 * @since 1.0.0
2305
 * @package GeoDirectory
2306
 * @param int $default Default height.
2307
 * @param string $params Image parameters.
2308
 * @return int Large size height.
2309
 */
2310 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...
2311
{
2312 2
    $large_size_h = get_option('large_size_h');
2313 2
    $large_size_h = $large_size_h > 0 ? $large_size_h : $default;
2314 2
    $large_size_h = absint($large_size_h);
2315
2316 2
    if (!get_option('geodir_use_wp_media_large_size')) {
2317 2
        $large_size_h = 800;
2318 2
    }
2319
2320
    /**
2321
     * Filter large image height.
2322
     *
2323
     * @since 1.0.0
2324
     * @param int $large_size_h Large image height.
2325
     * @param int $default Default height.
2326
     * @param string|array $params Image parameters.
2327
     */
2328 2
    $large_size_h = apply_filters('geodir_filter_media_image_large_height', $large_size_h, $default, $params);
2329
2330 2
    return $large_size_h;
2331
}
2332
2333
/**
2334
 * Sanitize location name.
2335
 *
2336
 * @since 1.0.0
2337
 * @package GeoDirectory
2338
 * @param string $type Location type. Can be gd_country, gd_region, gd_city.
2339
 * @param string $name Location name.
2340
 * @param bool $translate Do you want to translate the name? Default: true.
2341
 * @return string Sanitized name.
2342
 */
2343
function geodir_sanitize_location_name($type, $name, $translate = true)
2344
{
2345
    if ($name == '') {
2346
        return NULL;
2347
    }
2348
2349
    $type = $type == 'gd_country' ? 'country' : $type;
2350
    $type = $type == 'gd_region' ? 'region' : $type;
2351
    $type = $type == 'gd_city' ? 'city' : $type;
2352
2353
    $return = $name;
2354
    if (function_exists('get_actual_location_name')) {
2355
        $return = get_actual_location_name($type, $name, $translate);
2356
    } else {
2357
        $return = preg_replace('/-(\d+)$/', '', $return);
2358
        $return = preg_replace('/[_-]/', ' ', $return);
2359
        $return = geodir_ucwords($return);
2360
        $return = $translate ? __($return, 'geodirectory') : $return;
2361
    }
2362
2363
    return $return;
2364
}
2365
2366
2367
/**
2368
 * Pluralize comment number.
2369
 *
2370
 * @since 1.0.0
2371
 * @package GeoDirectory
2372
 * @param int $number Comments number.
2373
 */
2374
function geodir_comments_number($number)
2375
{
2376
2377 9
    if ($number > 1) {
2378
        $output = str_replace('%', number_format_i18n($number), __('% Reviews', 'geodirectory'));
2379 9
    } elseif ($number == 0 || $number == '') {
2380 9
        $output = __('No Reviews', 'geodirectory');
2381 9
    } else { // must be one
2382 4
        $output = __('1 Review', 'geodirectory');
2383
    }
2384 9
    echo $output;
2385 9
}
2386
2387
/**
2388
 * Checks whether the current page is geodirectory home page or not.
2389
 *
2390
 * @since 1.0.0
2391
 * @package GeoDirectory
2392
 * @global object $wpdb WordPress Database object.
2393
 * @return bool If current page is GD home page returns true, else false.
2394
 */
2395
function is_page_geodir_home()
2396
{
2397 8
    global $wpdb;
2398 8
    $cur_url = str_replace(array("https://", "http://", "www."), array('', '', ''), geodir_curPageURL());
2399 8
    if (function_exists('geodir_location_geo_home_link')) {
2400
        remove_filter('home_url', 'geodir_location_geo_home_link', 100000);
2401
    }
2402 8
    $home_url = home_url('', 'http');
2403 8
    if (function_exists('geodir_location_geo_home_link')) {
2404
        add_filter('home_url', 'geodir_location_geo_home_link', 100000, 2);
2405
    }
2406 8
    $home_url = str_replace("www.", "", $home_url);
2407 8
    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')) ) {
2408
        return true;
2409 8
    }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')){
2410
        return true;
2411
    } else {
2412 8
        return false;
2413
    }
2414
2415
}
2416
2417
2418
/**
2419
 * Returns homepage canonical url for SEO plugins.
2420
 *
2421
 * @since 1.0.0
2422
 * @package GeoDirectory
2423
 * @global object $post The current post object.
2424
 * @param string $url The old url.
2425
 * @return string The canonical URL.
2426
 */
2427
function geodir_wpseo_homepage_canonical($url)
2428
{
2429
    global $post;
2430
2431
    if (is_page_geodir_home()) {
2432
        return home_url();
2433
    }
2434
2435
    return $url;
2436
}
2437
2438
add_filter('wpseo_canonical', 'geodir_wpseo_homepage_canonical', 10);
2439
add_filter('aioseop_canonical_url', 'geodir_wpseo_homepage_canonical', 10);
2440
2441
/**
2442
 * Add extra fields to google maps script call.
2443
 *
2444
 * @since 1.0.0
2445
 * @package GeoDirectory
2446
 * @global object $post The current post object.
2447
 * @param string $extra Old extra string.
2448
 * @return string Modified extra string.
2449
 */
2450
function geodir_googlemap_script_extra_details_page($extra)
2451
{
2452 7
    global $post;
2453 7
    $add_google_places_api = false;
2454 7
    if (isset($post->post_content) && has_shortcode($post->post_content, 'gd_add_listing')) {
2455
        $add_google_places_api = true;
2456
    }
2457 7
    if (!str_replace('libraries=places', '', $extra) && (geodir_is_page('detail') || $add_google_places_api)) {
2458 1
        $extra .= "&amp;libraries=places";
2459 1
    }
2460
2461 7
    return $extra;
2462
}
2463
2464
add_filter('geodir_googlemap_script_extra', 'geodir_googlemap_script_extra_details_page', 101, 1);
2465
2466
2467
/**
2468
 * Generates popular post category HTML.
2469
 *
2470
 * @since 1.0.0
2471
 * @since 1.5.1 Added option to set default post type.
2472
 * @package GeoDirectory
2473
 * @global object $wpdb WordPress Database object.
2474
 * @global string $plugin_prefix Geodirectory plugin table prefix.
2475
 * @global string $geodir_post_category_str The geodirectory post category.
2476
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2477
 * @param array|string $instance The settings for the particular instance of the widget.
2478
 */
2479
function geodir_popular_post_category_output($args = '', $instance = '')
2480
{
2481
    // prints the widget
2482 3
    global $wpdb, $plugin_prefix, $geodir_post_category_str;
2483 3
    extract($args, EXTR_SKIP);
2484
2485 3
    echo $before_widget;
2486
2487
    /** This filter is documented in geodirectory_widgets.php */
2488 3
    $title = empty($instance['title']) ? __('Popular Categories', 'geodirectory') : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2489
2490 3
    $gd_post_type = geodir_get_current_posttype();
2491
2492 3
    $category_limit = isset($instance['category_limit']) && $instance['category_limit'] > 0 ? (int)$instance['category_limit'] : 15;
2493 3
    if(!empty($gd_post_type)){
2494
        $default_post_type = $gd_post_type;
2495 3
    }elseif(isset($instance['default_post_type']) && gdsc_is_post_type_valid($instance['default_post_type']) ){
2496
        $default_post_type = $instance['default_post_type'];
2497
    }else{
2498 3
        $all_gd_post_type = geodir_get_posttypes();
2499 3
        $default_post_type = (isset($all_gd_post_type[0])) ? $all_gd_post_type[0] : '';
2500
    }
2501
2502 3
    $taxonomy = array();
2503 3
    if (!empty($gd_post_type)) {
2504
        $taxonomy[] = $gd_post_type . "category";
2505
    } else {
2506 3
        $taxonomy = geodir_get_taxonomies($gd_post_type);
2507
    }
2508
2509 3
    $terms = get_terms($taxonomy);
2510 3
    $a_terms = array();
2511 3
    $b_terms = array();
2512
2513 3
    foreach ($terms as $term) {
2514 3
        if ($term->count > 0) {
2515 3
            $a_terms[$term->taxonomy][] = $term;
2516 3
        }
2517 3
    }
2518
2519 3
    if (!empty($a_terms)) {
2520 3
        foreach ($a_terms as $b_key => $b_val) {
2521 3
            $b_terms[$b_key] = geodir_sort_terms($b_val, 'count');
2522 3
        }
2523
2524 3
        $default_taxonomy = $default_post_type != '' && isset($b_terms[$default_post_type . 'category']) ? $default_post_type . 'category' : '';
2525
2526 3
        $tax_change_output = '';
2527 3
        if (count($b_terms) > 1) {
2528
            $tax_change_output .= "<select data-limit='$category_limit' class='geodir-cat-list-tax'  onchange='geodir_get_post_term(this);'>";
2529
            foreach ($b_terms as $key => $val) {
2530
                $ptype = get_post_type_object(str_replace("category", "", $key));
2531
                $cpt_name = __($ptype->labels->singular_name, 'geodirectory');
2532
                $tax_change_output .= "<option value='$key' ". selected($key, $default_taxonomy, false) .">" . sprintf(__('%s Categories', 'geodirectory'),$cpt_name) . "</option>";
2533
            }
2534
            $tax_change_output .= "</select>";
2535
        }
2536
2537 3
        if (!empty($b_terms)) {
2538 3
            $terms = $default_taxonomy != '' && isset($b_terms[$default_taxonomy]) ? $b_terms[$default_taxonomy] : reset($b_terms);// get the first array
2539 3
            global $cat_count;//make global so we can change via function
2540 3
            $cat_count = 0;
2541
            ?>
2542
            <div class="geodir-category-list-in clearfix">
2543
                <div class="geodir-cat-list clearfix">
2544
                    <?php
2545 3
                    echo $before_title . __($title) . $after_title;
2546
2547 3
                    echo $tax_change_output;
2548
2549 3
                    echo '<ul class="geodir-popular-cat-list">';
2550
2551 3
                    geodir_helper_cat_list_output($terms, $category_limit);
2552
2553 3
                    echo '</ul>';
2554
                    ?>
2555
                </div>
2556
                <?php
2557 3
                $hide = '';
2558 3
                if ($cat_count < $category_limit) {
2559 3
                    $hide = 'style="display:none;"';
2560 3
                }
2561 3
                echo "<div class='geodir-cat-list-more' $hide >";
2562 3
                echo '<a href="javascript:void(0)" class="geodir-morecat geodir-showcat">' . __('More Categories', 'geodirectory') . '</a>';
2563 3
                echo '<a href="javascript:void(0)" class="geodir-morecat geodir-hidecat geodir-hide">' . __('Less Categories', 'geodirectory') . '</a>';
2564 3
                echo "</div>";
2565
                /* add scripts */
2566 3
                add_action('wp_footer', 'geodir_popular_category_add_scripts', 100);
2567
                ?>
2568
            </div>
2569
        <?php
2570 3
        }
2571 3
    }
2572 3
    echo $after_widget;
2573 3
}
2574
2575
/**
2576
 * Generates category list HTML.
2577
 *
2578
 * @since 1.0.0
2579
 * @package GeoDirectory
2580
 * @global string $geodir_post_category_str The geodirectory post category.
2581
 * @param array $terms An array of term objects.
2582
 * @param int $category_limit Number of categories to display by default.
2583
 */
2584
function geodir_helper_cat_list_output($terms, $category_limit)
2585
{
2586 3
    global $geodir_post_category_str, $cat_count;
2587 3
    $term_icons = geodir_get_term_icon();
2588
2589 3
    $geodir_post_category_str = array();
2590
2591
2592 3
    foreach ($terms as $cat) {
2593 3
        $post_type = str_replace("category", "", $cat->taxonomy);
2594 3
        $term_icon_url = !empty($term_icons) && isset($term_icons[$cat->term_id]) ? $term_icons[$cat->term_id] : '';
2595
2596 3
        $cat_count++;
2597
2598 3
        $geodir_post_category_str[] = array('posttype' => $post_type, 'termid' => $cat->term_id);
2599
2600 3
        $class_row = $cat_count > $category_limit ? 'geodir-pcat-hide geodir-hide' : 'geodir-pcat-show';
2601 3
        $total_post = $cat->count;
2602
2603 3
        $term_link = get_term_link( $cat, $cat->taxonomy );
2604
        /**
2605
         * Filer the category term link.
2606
         *
2607
         * @since 1.4.5
2608
         * @param string $term_link The term permalink.
2609
         * @param int    $cat->term_id The term id.
2610
         * @param string $post_type Wordpress post type.
2611
         */
2612 3
        $term_link = apply_filters( 'geodir_category_term_link', $term_link, $cat->term_id, $post_type );
2613
2614 3
        echo '<li class="' . $class_row . '"><a href="' . $term_link . '">';
2615 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> ';
2616 3
        echo '</a></li>';
2617 3
    }
2618 3
}
2619
2620
/**
2621
 * Generates listing slider HTML.
2622
 *
2623
 * @since 1.0.0
2624
 * @package GeoDirectory
2625
 * @global object $post The current post object.
2626
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2627
 * @param array|string $instance The settings for the particular instance of the widget.
2628
 */
2629
function geodir_listing_slider_widget_output($args = '', $instance = '')
2630
{
2631
    // prints the widget
2632 2
    extract($args, EXTR_SKIP);
2633
2634 2
    echo $before_widget;
2635
2636
    /** This filter is documented in geodirectory_widgets.php */
2637 2
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2638
    /**
2639
     * Filter the widget post type.
2640
     *
2641
     * @since 1.0.0
2642
     * @param string $instance['post_type'] Post type of listing.
2643
     */
2644 2
    $post_type = empty($instance['post_type']) ? 'gd_place' : apply_filters('widget_post_type', $instance['post_type']);
2645
    /**
2646
     * Filter the widget's term.
2647
     *
2648
     * @since 1.0.0
2649
     * @param string $instance['category'] Filter by term. Can be any valid term.
2650
     */
2651 2
    $category = empty($instance['category']) ? '0' : apply_filters('widget_category', $instance['category']);
2652
    /**
2653
     * Filter the widget listings limit.
2654
     *
2655
     * @since 1.0.0
2656
     * @param string $instance['post_number'] Number of listings to display.
2657
     */
2658 2
    $post_number = empty($instance['post_number']) ? '5' : apply_filters('widget_post_number', $instance['post_number']);
2659
    /**
2660
     * Filter the widget listings limit shown at one time.
2661
     *
2662
     * @since 1.5.0
2663
     * @param string $instance['max_show'] Number of listings to display on screen.
2664
     */
2665 2
    $max_show = empty($instance['max_show']) ? '1' : apply_filters('widget_max_show', $instance['max_show']);
2666
    /**
2667
     * Filter the widget slide width.
2668
     *
2669
     * @since 1.5.0
2670
     * @param string $instance['slide_width'] Width of the slides shown.
2671
     */
2672 2
    $slide_width = empty($instance['slide_width']) ? '' : apply_filters('widget_slide_width', $instance['slide_width']);
2673
    /**
2674
     * Filter widget's "show title" value.
2675
     *
2676
     * @since 1.0.0
2677
     * @param string|bool $instance['show_title'] Do you want to display title? Can be 1 or 0.
2678
     */
2679 2
    $show_title = empty($instance['show_title']) ? '' : apply_filters('widget_show_title', $instance['show_title']);
2680
    /**
2681
     * Filter widget's "slideshow" value.
2682
     *
2683
     * @since 1.0.0
2684
     * @param int $instance['slideshow'] Setup a slideshow for the slider to animate automatically.
2685
     */
2686 2
    $slideshow = empty($instance['slideshow']) ? 0 : apply_filters('widget_slideshow', $instance['slideshow']);
2687
    /**
2688
     * Filter widget's "animationLoop" value.
2689
     *
2690
     * @since 1.0.0
2691
     * @param int $instance['animationLoop'] Gives the slider a seamless infinite loop.
2692
     */
2693 2
    $animationLoop = empty($instance['animationLoop']) ? 0 : apply_filters('widget_animationLoop', $instance['animationLoop']);
2694
    /**
2695
     * Filter widget's "directionNav" value.
2696
     *
2697
     * @since 1.0.0
2698
     * @param int $instance['directionNav'] Enable previous/next arrow navigation?. Can be 1 or 0.
2699
     */
2700 2
    $directionNav = empty($instance['directionNav']) ? 0 : apply_filters('widget_directionNav', $instance['directionNav']);
2701
    /**
2702
     * Filter widget's "slideshowSpeed" value.
2703
     *
2704
     * @since 1.0.0
2705
     * @param int $instance['slideshowSpeed'] Set the speed of the slideshow cycling, in milliseconds.
2706
     */
2707 2
    $slideshowSpeed = empty($instance['slideshowSpeed']) ? 5000 : apply_filters('widget_slideshowSpeed', $instance['slideshowSpeed']);
2708
    /**
2709
     * Filter widget's "animationSpeed" value.
2710
     *
2711
     * @since 1.0.0
2712
     * @param int $instance['animationSpeed'] Set the speed of animations, in milliseconds.
2713
     */
2714 2
    $animationSpeed = empty($instance['animationSpeed']) ? 600 : apply_filters('widget_animationSpeed', $instance['animationSpeed']);
2715
    /**
2716
     * Filter widget's "animation" value.
2717
     *
2718
     * @since 1.0.0
2719
     * @param string $instance['animation'] Controls the animation type, "fade" or "slide".
2720
     */
2721 2
    $animation = empty($instance['animation']) ? 'slide' : apply_filters('widget_animation', $instance['animation']);
2722
    /**
2723
     * Filter widget's "list_sort" type.
2724
     *
2725
     * @since 1.0.0
2726
     * @param string $instance['list_sort'] Listing sort by type.
2727
     */
2728 2
    $list_sort = empty($instance['list_sort']) ? 'latest' : apply_filters('widget_list_sort', $instance['list_sort']);
2729 2
    $show_featured_only = !empty($instance['show_featured_only']) ? 1 : NULL;
2730
2731 2
    wp_enqueue_script('geodirectory-jquery-flexslider-js');
2732
    ?>
2733
    <script type="text/javascript">
2734
        jQuery(window).load(function () {
2735
            jQuery('#geodir_widget_carousel').flexslider({
2736
                animation: "slide",
2737
                selector: ".geodir-slides > li",
2738
                namespace: "geodir-",
2739
                controlNav: false,
2740
                directionNav: false,
2741
                animationLoop: false,
2742
                slideshow: false,
2743
                itemWidth: 75,
2744
                itemMargin: 5,
2745
                asNavFor: '#geodir_widget_slider',
2746
                rtl: <?php echo ( is_rtl() ? 'true' : 'false' ); /* fix rtl issue */ ?>
2747
            });
2748
2749
            jQuery('#geodir_widget_slider').flexslider({
2750
                animation: "<?php echo $animation;?>",
2751
                selector: ".geodir-slides > li",
2752
                namespace: "geodir-",
2753
                controlNav: true,
2754
                animationLoop: <?php echo $animationLoop;?>,
2755
                slideshow: <?php echo $slideshow;?>,
2756
                slideshowSpeed: <?php echo $slideshowSpeed;?>,
2757
                animationSpeed: <?php echo $animationSpeed;?>,
2758
                directionNav: <?php echo $directionNav;?>,
2759
                maxItems: <?php echo $max_show;?>,
2760
                move: 1,
2761
                <?php if($slide_width){ echo "itemWidth: ".$slide_width.",";}?>
2762
                sync: "#geodir_widget_carousel",
2763
                start: function (slider) {
2764
                    jQuery('.geodir-listing-flex-loader').hide();
2765
                    jQuery('#geodir_widget_slider').css({'visibility': 'visible'});
2766
                    jQuery('#geodir_widget_carousel').css({'visibility': 'visible'});
2767
                },
2768
                rtl: <?php echo ( is_rtl() ? 'true' : 'false' ); /* fix rtl issue */ ?>
2769
            });
2770
        });
2771
    </script>
2772
    <?php
2773
    $query_args = array(
2774 2
        'posts_per_page' => $post_number,
2775 2
        'is_geodir_loop' => true,
2776 2
        'post_type' => $post_type,
2777
        'order_by' => $list_sort
2778 2
    );
2779 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...
2780 1
        $query_args['show_featured_only'] = 1;
2781 1
    }
2782
2783 2
    if ($category != 0 || $category != '') {
2784 2
        $category_taxonomy = geodir_get_taxonomies($post_type);
2785
        $tax_query = array(
2786 2
            'taxonomy' => $category_taxonomy[0],
2787 2
            'field' => 'id',
2788
            'terms' => $category
2789 2
        );
2790
2791 2
        $query_args['tax_query'] = array($tax_query);
2792 2
    }
2793
2794
    // we want listings with featured image only
2795 2
    $query_args['featured_image_only'] = 1;
2796
2797 2
    if ($post_type == 'gd_event') {
2798
        $query_args['gedir_event_listing_filter'] = 'upcoming';
2799
    }// show only upcomming events
2800
2801 2
    $widget_listings = geodir_get_widget_listings($query_args);
2802 2
    if (!empty($widget_listings) || (isset($with_no_results) && $with_no_results)) {
2803 1
        if ($title) {
2804
            echo $before_title . $title . $after_title;
2805
        }
2806
2807 1
        global $post;
2808
2809 1
        $current_post = $post;// keep current post info
2810
2811 1
        $widget_main_slides = '';
2812 1
        $nav_slides = '';
2813 1
        $widget_slides = 0;
2814
2815 1
        foreach ($widget_listings as $widget_listing) {
2816 1
            global $gd_widget_listing_type;
2817 1
            $post = $widget_listing;
2818 1
            $widget_image = geodir_get_featured_image($post->ID, 'thumbnail', get_option('geodir_listing_no_img'));
2819
2820 1
            if (!empty($widget_image)) {
2821 1
                if ($widget_image->height >= 200) {
2822 1
                    $widget_spacer_height = 0;
2823 1
                } else {
2824 1
                    $widget_spacer_height = ((200 - $widget_image->height) / 2);
2825
                }
2826
2827 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" />';
2828
2829 1
                $title = '';
2830 1
                if ($show_title) {
2831
                    $title_html = '<div class="geodir-slider-title"><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></div>';
2832
                    $post_id = $post->ID;
2833
                    $post_permalink = get_permalink($post->ID);
2834
                    $post_title = get_the_title($post->ID);
2835
                    /**
2836
                     * Filter the listing slider widget title.
2837
                     *
2838
                     * @since 1.6.1
2839
                     * @param string $title_html The html output of the title.
2840
                     * @param int $post_id The post id.
2841
                     * @param string $post_permalink The post permalink url.
2842
                     * @param string $post_title The post title text.
2843
                     */
2844
                    $title = apply_filters('geodir_listing_slider_title',$title_html,$post_id,$post_permalink,$post_title);
2845
                }
2846
2847 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>';
2848 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>';
2849 1
                $widget_slides++;
2850 1
            }
2851 1
        }
2852
        ?>
2853
        <div class="flex-container" style="min-height:200px;">
2854
            <div class="geodir-listing-flex-loader"><i class="fa fa-refresh fa-spin"></i></div>
2855
            <div id="geodir_widget_slider" class="geodir_flexslider">
2856
                <ul class="geodir-slides clearfix"><?php echo $widget_main_slides; ?></ul>
2857
            </div>
2858
            <?php if ($widget_slides > 1) { ?>
2859
                <div id="geodir_widget_carousel" class="geodir_flexslider">
2860
                    <ul class="geodir-slides clearfix"><?php echo $nav_slides; ?></ul>
2861
                </div>
2862
            <?php } ?>
2863
        </div>
2864
        <?php
2865 1
        $GLOBALS['post'] = $current_post;
2866 1
        setup_postdata($current_post);
2867 1
    }
2868 2
    echo $after_widget;
2869 2
}
2870
2871
2872
/**
2873
 * Generates login box HTML.
2874
 *
2875
 * @since 1.0.0
2876
 * @package GeoDirectory
2877
 * @global object $current_user Current user object.
2878
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
2879
 * @param array|string $instance The settings for the particular instance of the widget.
2880
 */
2881
function geodir_loginwidget_output($args = '', $instance = '')
2882
{
2883
    //print_r($args);
2884
    //print_r($instance);
2885
    // prints the widget
2886 2
    extract($args, EXTR_SKIP);
2887
2888
    /** This filter is documented in geodirectory_widgets.php */
2889 2
    $title = empty($instance['title']) ? __('My Dashboard', 'geodirectory') : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
2890
2891 2
    echo $before_widget;
2892 2
    echo $before_title . $title . $after_title;
2893
2894 2
    if (is_user_logged_in()) {
2895 2
        global $current_user;
2896
2897 2
        $author_link = get_author_posts_url($current_user->data->ID);
2898 2
        $author_link = geodir_getlink($author_link, array('geodir_dashbord' => 'true'), false);
2899
2900 2
        echo '<ul class="geodir-loginbox-list">';
2901 2
        ob_start();
2902
        ?>
2903
        <li><a class="signin"
2904
               href="<?php echo wp_logout_url(home_url()); ?>"><?php _e('Logout', 'geodirectory'); ?></a></li>
2905
        <?php
2906 2
        $post_types = geodir_get_posttypes('object');
2907 2
        $show_add_listing_post_types_main_nav = get_option('geodir_add_listing_link_user_dashboard');
2908 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...
2909
2910 2
        if (!empty($show_add_listing_post_types_main_nav)) {
2911 2
            $addlisting_links = '';
2912 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...
2913
2914 2
                if (in_array($key, $show_add_listing_post_types_main_nav)) {
2915
2916 2
                    if ($add_link = geodir_get_addlisting_link($key)) {
2917
2918 2
                        $name = $postobj->labels->name;
2919
2920 2
                        $selected = '';
2921 2
                        if (geodir_get_current_posttype() == $key && geodir_is_page('add-listing'))
2922 2
                            $selected = 'selected="selected"';
2923
2924
                        /**
2925
                         * Filter add listing link.
2926
                         *
2927
                         * @since 1.0.0
2928
                         * @param string $add_link Add listing link.
2929
                         * @param string $key Add listing array key.
2930
                         * @param int $current_user->ID Current user ID.
2931
                         */
2932 2
                        $add_link = apply_filters('geodir_dashboard_link_add_listing', $add_link, $key, $current_user->ID);
2933
2934 2
                        $addlisting_links .= '<option ' . $selected . ' value="' . $add_link . '">' . __(ucfirst($name), 'geodirectory') . '</option>';
2935
2936 2
                    }
2937 2
                }
2938
2939 2
            }
2940
2941 View Code Duplication
            if ($addlisting_links != '') { ?>
2942
2943
                <li><select id="geodir_add_listing" class="chosen_select" onchange="window.location.href=this.value"
2944
                            option-autoredirect="1" name="geodir_add_listing" option-ajaxchosen="false"
2945
                            data-placeholder="<?php echo esc_attr(__('Add Listing', 'geodirectory')); ?>">
2946
                        <option value="" disabled="disabled" selected="selected" style='display:none;'><?php echo esc_attr(__('Add Listing', 'geodirectory')); ?></option>
2947
                        <?php echo $addlisting_links; ?>
2948
                    </select></li> <?php
2949
2950 2
            }
2951
2952 2
        }
2953
        // My Favourites in Dashboard
2954 2
        $show_favorite_link_user_dashboard = get_option('geodir_favorite_link_user_dashboard');
2955 2
        $user_favourite = geodir_user_favourite_listing_count();
2956
2957 2
        if (!empty($show_favorite_link_user_dashboard) && !empty($user_favourite)) {
2958
            $favourite_links = '';
2959
2960
            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...
2961
                if (in_array($key, $show_favorite_link_user_dashboard) && array_key_exists($key, $user_favourite)) {
2962
                    $name = $postobj->labels->name;
2963
                    $post_type_link = geodir_getlink($author_link, array('stype' => $key, 'list' => 'favourite'), false);
2964
2965
                    $selected = '';
2966
2967 View Code Duplication
                    if (isset($_REQUEST['list']) && $_REQUEST['list'] == 'favourite' && isset($_REQUEST['stype']) && $_REQUEST['stype'] == $key && isset($_REQUEST['geodir_dashbord'])) {
2968
                        $selected = 'selected="selected"';
2969
                    }
2970
                    /**
2971
                     * Filter favorite listing link.
2972
                     *
2973
                     * @since 1.0.0
2974
                     * @param string $post_type_link Favorite listing link.
2975
                     * @param string $key Favorite listing array key.
2976
                     * @param int $current_user->ID Current user ID.
2977
                     */
2978
                    $post_type_link = apply_filters('geodir_dashboard_link_favorite_listing', $post_type_link, $key, $current_user->ID);
2979
2980
                    $favourite_links .= '<option ' . $selected . ' value="' . $post_type_link . '">' . __(ucfirst($name), 'geodirectory') . '</option>';
2981
                }
2982
            }
2983
2984 View Code Duplication
            if ($favourite_links != '') {
2985
                ?>
2986
                <li>
2987
                    <select id="geodir_my_favourites" class="chosen_select" onchange="window.location.href=this.value"
2988
                            option-autoredirect="1" name="geodir_my_favourites" option-ajaxchosen="false"
2989
                            data-placeholder="<?php echo esc_attr(__('My Favorites', 'geodirectory')); ?>">
2990
                        <option value="" disabled="disabled" selected="selected" style='display:none;'><?php echo esc_attr(__('My Favorites', 'geodirectory')); ?></option>
2991
                        <?php echo $favourite_links; ?>
2992
                    </select>
2993
                </li>
2994
            <?php
2995
            }
2996
        }
2997
2998
2999 2
        $show_listing_link_user_dashboard = get_option('geodir_listing_link_user_dashboard');
3000 2
        $user_listing = geodir_user_post_listing_count();
3001
3002 2
        if (!empty($show_listing_link_user_dashboard) && !empty($user_listing)) {
3003 2
            $listing_links = '';
3004
3005 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...
3006 2
                if (in_array($key, $show_listing_link_user_dashboard) && array_key_exists($key, $user_listing)) {
3007 2
                    $name = $postobj->labels->name;
3008 2
                    $listing_link = geodir_getlink($author_link, array('stype' => $key), false);
3009
3010 2
                    $selected = '';
3011 2 View Code Duplication
                    if (!isset($_REQUEST['list']) && isset($_REQUEST['geodir_dashbord']) && isset($_REQUEST['stype']) && $_REQUEST['stype'] == $key) {
3012 1
                        $selected = 'selected="selected"';
3013 1
                    }
3014
3015
                    /**
3016
                     * Filter my listing link.
3017
                     *
3018
                     * @since 1.0.0
3019
                     * @param string $listing_link My listing link.
3020
                     * @param string $key My listing array key.
3021
                     * @param int $current_user->ID Current user ID.
3022
                     */
3023 2
                    $listing_link = apply_filters('geodir_dashboard_link_my_listing', $listing_link, $key, $current_user->ID);
3024
3025 2
                    $listing_links .= '<option ' . $selected . ' value="' . $listing_link . '">' . __(ucfirst($name), 'geodirectory') . '</option>';
3026 2
                }
3027 2
            }
3028
3029 2 View Code Duplication
            if ($listing_links != '') {
3030
                ?>
3031
                <li>
3032
                    <select id="geodir_my_listings" class="chosen_select" onchange="window.location.href=this.value"
3033
                            option-autoredirect="1" name="geodir_my_listings" option-ajaxchosen="false"
3034
                            data-placeholder="<?php echo esc_attr(__('My Listings', 'geodirectory')); ?>">
3035
                        <option value="" disabled="disabled" selected="selected" style='display:none;'><?php echo esc_attr(__('My Listings', 'geodirectory')); ?></option>
3036
                        <?php echo $listing_links; ?>
3037
                    </select>
3038
                </li>
3039
            <?php
3040 2
            }
3041 2
        }
3042
3043 2
        $dashboard_link = ob_get_clean();
3044
        /**
3045
         * Filter dashboard links HTML.
3046
         *
3047
         * @since 1.0.0
3048
         * @param string $dashboard_link Dashboard links HTML.
3049
         */
3050 2
        echo apply_filters('geodir_dashboard_links', $dashboard_link);
3051 2
        echo '</ul>';
3052 2
    } else {
3053
        ?>
3054
        <?php
3055
        /**
3056
         * Filter signup form action link.
3057
         *
3058
         * @since 1.0.0
3059
         */
3060
        ?>
3061
        <form name="loginform" class="loginform1"
3062
              action="<?php echo geodir_login_url(); ?>"
3063
              method="post">
3064
            <div class="geodir_form_row"><input placeholder="<?php _e('Email', 'geodirectory'); ?>" name="log"
3065
                                                type="text" class="textfield user_login1"/> <span
3066
                    class="user_loginInfo"></span></div>
3067
            <div class="geodir_form_row"><input placeholder="<?php _e('Password', 'geodirectory'); ?>"
3068
                                                name="pwd" type="password"
3069
                                                class="textfield user_pass1 input-text"/><span
3070
                    class="user_passInfo"></span></div>
3071
3072
            <input type="hidden" name="redirect_to" value="<?php echo htmlspecialchars(geodir_curPageURL()); ?>"/>
3073
            <input type="hidden" name="testcookie" value="1"/>
3074
3075
            <div class="geodir_form_row clearfix"><input type="submit" name="submit"
3076
                                                         value="<?php echo SIGN_IN_BUTTON; ?>" class="b_signin"/>
3077
3078
                <p class="geodir-new-forgot-link">
3079
                    <?php
3080
                    /**
3081
                     * Filter signup page register form link.
3082
                     *
3083
                     * @since 1.0.0
3084
                     */
3085
                    ?>
3086
                    <a href="<?php echo geodir_login_url(array('signup' => true)); ?>"
3087
                       class="goedir-newuser-link"><?php echo NEW_USER_TEXT; ?></a>
3088
3089
                    <?php
3090
                    /**
3091
                     * Filter signup page forgot password form link.
3092
                     *
3093
                     * @since 1.0.0
3094
                     */
3095
                    ?>
3096
                    <a href="<?php echo geodir_login_url(array('forgot' => true)); ?>"
3097
                       class="goedir-forgot-link"><?php echo FORGOT_PW_TEXT; ?></a></p></div>
3098
        </form>
3099
    <?php }
3100
3101 2
    echo $after_widget;
3102 2
}
3103
3104
3105
/**
3106
 * Generates popular postview HTML.
3107
 *
3108
 * @since 1.0.0
3109
 * @since 1.5.1 View all link fixed for location filter disabled.
3110
 * @package GeoDirectory
3111
 * @global object $post The current post object.
3112
 * @global string $gridview_columns_widget The girdview style of the listings for widget.
3113
 * @global bool $geodir_is_widget_listing Is this a widget listing?. Default: false.
3114
 * @global object $gd_session GeoDirectory Session object.
3115
 *
3116
 * @param array|string $args Display arguments including before_title, after_title, before_widget, and after_widget.
3117
 * @param array|string $instance The settings for the particular instance of the widget.
3118
 */
3119
function geodir_popular_postview_output($args = '', $instance = '') {
3120 2
    global $gd_session;
3121
	
3122
    // prints the widget
3123 2
    extract($args, EXTR_SKIP);
3124
3125 2
    echo $before_widget;
3126
3127
    /** This filter is documented in geodirectory_widgets.php */
3128 2
    $title = empty($instance['title']) ? geodir_ucwords($instance['category_title']) : apply_filters('widget_title', __($instance['title'], 'geodirectory'));
3129
    /**
3130
     * Filter the widget post type.
3131
     *
3132
     * @since 1.0.0
3133
     * @param string $instance['post_type'] Post type of listing.
3134
     */
3135 2
    $post_type = empty($instance['post_type']) ? 'gd_place' : apply_filters('widget_post_type', $instance['post_type']);
3136
    /**
3137
     * Filter the widget's term.
3138
     *
3139
     * @since 1.0.0
3140
     * @param string $instance['category'] Filter by term. Can be any valid term.
3141
     */
3142 2
    $category = empty($instance['category']) ? '0' : apply_filters('widget_category', $instance['category']);
3143
    /**
3144
     * Filter the widget listings limit.
3145
     *
3146
     * @since 1.0.0
3147
     * @param string $instance['post_number'] Number of listings to display.
3148
     */
3149 2
    $post_number = empty($instance['post_number']) ? '5' : apply_filters('widget_post_number', $instance['post_number']);
3150
    /**
3151
     * Filter widget's "layout" type.
3152
     *
3153
     * @since 1.0.0
3154
     * @param string $instance['layout'] Widget layout type.
3155
     */
3156 2
    $layout = empty($instance['layout']) ? 'gridview_onehalf' : apply_filters('widget_layout', $instance['layout']);
3157
    /**
3158
     * Filter widget's "add_location_filter" value.
3159
     *
3160
     * @since 1.0.0
3161
     * @param string|bool $instance['add_location_filter'] Do you want to add location filter? Can be 1 or 0.
3162
     */
3163 2
    $add_location_filter = empty($instance['add_location_filter']) ? '0' : apply_filters('widget_add_location_filter', $instance['add_location_filter']);
3164
    /**
3165
     * Filter widget's listing width.
3166
     *
3167
     * @since 1.0.0
3168
     * @param string $instance['listing_width'] Listing width.
3169
     */
3170 2
    $listing_width = empty($instance['listing_width']) ? '' : apply_filters('widget_listing_width', $instance['listing_width']);
3171
    /**
3172
     * Filter widget's "list_sort" type.
3173
     *
3174
     * @since 1.0.0
3175
     * @param string $instance['list_sort'] Listing sort by type.
3176
     */
3177 2
    $list_sort = empty($instance['list_sort']) ? 'latest' : apply_filters('widget_list_sort', $instance['list_sort']);
3178 2
    $use_viewing_post_type = !empty($instance['use_viewing_post_type']) ? true : false;
3179
3180
    // set post type to current viewing post type
3181 2 View Code Duplication
    if ($use_viewing_post_type) {
3182 1
        $current_post_type = geodir_get_current_posttype();
3183 1
        if ($current_post_type != '' && $current_post_type != $post_type) {
3184
            $post_type = $current_post_type;
3185
            $category = array(); // old post type category will not work for current changed post type
3186
        }
3187 1
    }
3188
    // replace widget title dynamically
3189 2
    $posttype_plural_label = __(get_post_type_plural_label($post_type), 'geodirectory');
3190 2
    $posttype_singular_label = __(get_post_type_singular_label($post_type), 'geodirectory');
3191
3192 2
    $title = str_replace("%posttype_plural_label%", $posttype_plural_label, $title);
3193 2
    $title = str_replace("%posttype_singular_label%", $posttype_singular_label, $title);
3194
3195 2 View Code Duplication
    if (isset($instance['character_count'])) {
3196
        /**
3197
         * Filter the widget's excerpt character count.
3198
         *
3199
         * @since 1.0.0
3200
         * @param int $instance['character_count'] Excerpt character count.
3201
         */
3202 1
        $character_count = apply_filters('widget_list_character_count', $instance['character_count']);
3203 1
    } else {
3204 1
        $character_count = '';
3205
    }
3206
3207 2
    if (empty($title) || $title == 'All') {
3208 2
        $title .= ' ' . __(get_post_type_plural_label($post_type), 'geodirectory');
3209 2
    }
3210
3211 2
    $location_url = array();
3212 2
    $city = get_query_var('gd_city');
3213 2
    if (!empty($city)) {
3214
        $country = get_query_var('gd_country');
3215
        $region = get_query_var('gd_region');
3216
3217
        $geodir_show_location_url = get_option('geodir_show_location_url');
3218
3219
        if ($geodir_show_location_url == 'all') {
3220
            if ($country != '') {
3221
                $location_url[] = $country;
3222
            }
3223
3224
            if ($region != '') {
3225
                $location_url[] = $region;
3226
            }
3227
        } else if ($geodir_show_location_url == 'country_city') {
3228
            if ($country != '') {
3229
                $location_url[] = $country;
3230
            }
3231
        } else if ($geodir_show_location_url == 'region_city') {
3232
            if ($region != '') {
3233
                $location_url[] = $region;
3234
            }
3235
        }
3236
3237
        $location_url[] = $city;
3238
    }
3239
3240 2
    $location_url = implode('/', $location_url);
3241 2
    $skip_location = false;
3242 2
    if (!$add_location_filter && $gd_session->get('gd_multi_location')) {
3243
        $skip_location = true;
3244
        $gd_session->un_set('gd_multi_location');
3245
    }
3246
3247 2
    if (get_option('permalink_structure')) {
3248
        $viewall_url = get_post_type_archive_link($post_type);
3249
    } else {
3250 2
        $viewall_url = get_post_type_archive_link($post_type);
3251
    }
3252
3253 2
    if (!empty($category) && $category[0] != '0') {
3254
        global $geodir_add_location_url;
3255
3256
        $geodir_add_location_url = '0';
3257
3258
        if ($add_location_filter != '0') {
3259
            $geodir_add_location_url = '1';
3260
        }
3261
3262
        $viewall_url = get_term_link((int)$category[0], $post_type . 'category');
3263
3264
        $geodir_add_location_url = NULL;
3265
    }
3266 2
    if ($skip_location) {
3267
        $gd_session->set('gd_multi_location', 1);
3268
    }
3269
3270 2
    if(is_wp_error( $viewall_url  )){$viewall_url = '';}
3271
3272
    $query_args = array(
3273 2
        'posts_per_page' => $post_number,
3274 2
        'is_geodir_loop' => true,
3275 2
        'gd_location' => $add_location_filter ? true : false,
3276 2
        'post_type' => $post_type,
3277
        'order_by' => $list_sort
3278 2
    );
3279
3280 2
    if ($character_count) {
3281 1
        $query_args['excerpt_length'] = $character_count;
3282 1
    }
3283
3284 2
    if (!empty($instance['show_featured_only'])) {
3285 1
        $query_args['show_featured_only'] = 1;
3286 1
    }
3287
3288 2
    if (!empty($instance['show_special_only'])) {
3289
        $query_args['show_special_only'] = 1;
3290
    }
3291
3292 2 View Code Duplication
    if (!empty($instance['with_pics_only'])) {
3293
        $query_args['with_pics_only'] = 0;
3294
        $query_args['featured_image_only'] = 1;
3295
    }
3296
3297 2
    if (!empty($instance['with_videos_only'])) {
3298
        $query_args['with_videos_only'] = 1;
3299
    }
3300 2
    $with_no_results = !empty($instance['without_no_results']) ? false : true;
3301
3302 2 View Code Duplication
    if (!empty($category) && $category[0] != '0') {
3303
        $category_taxonomy = geodir_get_taxonomies($post_type);
3304
3305
        ######### WPML #########
3306
        if (function_exists('icl_object_id')) {
3307
            $category = gd_lang_object_ids($category, $category_taxonomy[0]);
3308
        }
3309
        ######### WPML #########
3310
3311
        $tax_query = array(
3312
            'taxonomy' => $category_taxonomy[0],
3313
            'field' => 'id',
3314
            'terms' => $category
3315
        );
3316
3317
        $query_args['tax_query'] = array($tax_query);
3318
    }
3319
3320 2
    global $gridview_columns_widget, $geodir_is_widget_listing;
3321
3322 2
    $widget_listings = geodir_get_widget_listings($query_args);
3323
3324 2
    if (!empty($widget_listings) || $with_no_results) {
3325
        ?>
3326
        <div class="geodir_locations geodir_location_listing">
3327
3328
            <?php
3329
            /**
3330
             * Called before the div containing the title and view all link in popular post view widget.
3331
             *
3332
             * @since 1.0.0
3333
             */
3334
            do_action('geodir_before_view_all_link_in_widget'); ?>
3335
            <div class="geodir_list_heading clearfix">
3336
                <?php echo $before_title . $title . $after_title; ?>
3337
                <a href="<?php echo $viewall_url; ?>"
3338
                   class="geodir-viewall"><?php _e('View all', 'geodirectory'); ?></a>
3339
            </div>
3340
            <?php
3341
            /**
3342
             * Called after the div containing the title and view all link in popular post view widget.
3343
             *
3344
             * @since 1.0.0
3345
             */
3346
            do_action('geodir_after_view_all_link_in_widget'); ?>
3347
            <?php
3348 2 View Code Duplication
            if (strstr($layout, 'gridview')) {
3349 2
                $listing_view_exp = explode('_', $layout);
3350 2
                $gridview_columns_widget = $layout;
3351 2
                $layout = $listing_view_exp[0];
3352 2
            } else {
3353
                $gridview_columns_widget = '';
3354
            }
3355
3356
            /**
3357
             * Filter the widget listing listview template path.
3358
             *
3359
             * @since 1.0.0
3360
             */
3361 2
            $template = apply_filters("geodir_template_part-widget-listing-listview", geodir_locate_template('widget-listing-listview'));
3362 2
            if (!isset($character_count)) {
3363
                /**
3364
                 * Filter the widget's excerpt character count.
3365
                 *
3366
                 * @since 1.0.0
3367
                 * @param int $instance['character_count'] Excerpt character count.
3368
                 */
3369
                $character_count = $character_count == '' ? 50 : apply_filters('widget_character_count', $character_count);
3370
            }
3371
3372 2
            global $post, $map_jason, $map_canvas_arr;
3373
3374 2
            $current_post = $post;
3375 2
            $current_map_jason = $map_jason;
3376 2
            $current_map_canvas_arr = $map_canvas_arr;
3377 2
            $geodir_is_widget_listing = true;
3378
3379
            /**
3380
             * Includes related listing listview template.
3381
             *
3382
             * @since 1.0.0
3383
             */
3384 2
            include($template);
3385
3386 2
            $geodir_is_widget_listing = false;
3387
3388 2
            $GLOBALS['post'] = $current_post;
3389 2
            if (!empty($current_post))
3390 2
                setup_postdata($current_post);
3391 2
            $map_jason = $current_map_jason;
3392 2
            $map_canvas_arr = $current_map_canvas_arr;
3393
            ?>
3394
        </div>
3395
    <?php
3396 2
    }
3397 2
    echo $after_widget;
3398
3399 2
}
3400
3401
3402
/*-----------------------------------------------------------------------------------*/
3403
/*  Review count functions
3404
/*-----------------------------------------------------------------------------------*/
3405
/**
3406
 * Count reviews by term ID.
3407
 *
3408
 * @since 1.0.0
3409
 * @since 1.5.1 Added filter to change SQL.
3410
 * @package GeoDirectory
3411
 * @global object $wpdb WordPress Database object.
3412
 * @global string $plugin_prefix Geodirectory plugin table prefix.
3413
 * @param int $term_id The term ID.
3414
 * @param int $taxonomy The taxonomy Id.
3415
 * @param string $post_type The post type.
3416
 * @return int Reviews count.
3417
 */
3418
function geodir_count_reviews_by_term_id($term_id, $taxonomy, $post_type)
3419
{
3420 2
    global $wpdb, $plugin_prefix;
3421
3422 2
    $detail_table = $plugin_prefix . $post_type . '_detail';
3423
3424 2
    $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 . ")";
3425
3426
    /**
3427
     * Filter count review sql query.
3428
     *
3429
     * @since 1.5.1
3430
     * @param string $sql Database sql query..
3431
     * @param int $term_id The term ID.
3432
     * @param int $taxonomy The taxonomy Id.
3433
     * @param string $post_type The post type.
3434
     */
3435 2
    $sql = apply_filters('geodir_count_reviews_by_term_sql', $sql, $term_id, $taxonomy, $post_type);
3436
3437 2
    $count = $wpdb->get_var($sql);
3438
3439 2
    return $count;
3440
}
3441
3442
/**
3443
 * Count reviews by terms.
3444
 *
3445
 * @since 1.0.0
3446
 * @since 1.6.1 Fixed add listing page load time.
3447
 * @package GeoDirectory
3448
 *
3449
 * @global object $gd_session GeoDirectory Session object.
3450
 *
3451
 * @param bool $force_update Force update option value?. Default.false.
3452
 * @return array Term array data.
3453
 */
3454
function geodir_count_reviews_by_terms($force_update = false, $post_ID = 0) {
3455
    /**
3456
     * Filter review count option data.
3457
     *
3458
     * @since 1.0.0
3459
     * @since 1.6.1 Added $post_ID param.
3460
     * @param bool $force_update Force update option value?. Default.false.
3461
     * @param int $post_ID The post id to update if any.
3462
     */
3463 8
    $option_data = apply_filters('geodir_count_reviews_by_terms_before', '', $force_update,$post_ID);
3464 8
    if (!empty($option_data)) {
3465
        return $option_data;
3466
    }
3467
3468 8
    $option_data = get_option('geodir_global_review_count');
3469
3470 8
    if (!$option_data || $force_update) {
3471 7
        if ((int)$post_ID > 0) { // Update reviews count for specific post categories only.
3472 7
            global $gd_session;
3473 7
            $term_array = (array)$option_data;
3474 7
            $post_type = get_post_type($post_ID);
3475 7
            $taxonomy = $post_type . 'category';
3476 7
            $terms = wp_get_object_terms($post_ID, $taxonomy, array('fields' => 'ids'));
3477
3478 7 View Code Duplication
            if (!empty($terms) && !is_wp_error($terms)) {
3479 2
                foreach ($terms as $term_id) {
3480 2
                    $count = geodir_count_reviews_by_term_id($term_id, $taxonomy, $post_type);
3481 2
                    $children = get_term_children($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...
3482 2
                    $term_array[$term_id] = $count;
3483 2
                }
3484 2
            }
3485
            
3486 7
            $session_listing = $gd_session->get('listing');
3487
            
3488 7
            $terms = array();
3489 7
            if (isset($_POST['post_category'][$taxonomy])) {
3490
                $terms = (array)$_POST['post_category'][$taxonomy];
3491 7
            } else if (!empty($session_listing) && isset($session_listing['post_category'][$taxonomy])) {
3492
                $terms = (array)$session_listing['post_category'][$taxonomy];
3493
            }
3494
            
3495 7 View Code Duplication
            if (!empty($terms)) {
3496
                foreach ($terms as $term_id) {
3497
                    if ($term_id > 0) {
3498
                        $count = geodir_count_reviews_by_term_id($term_id, $taxonomy, $post_type);
3499
                        $children = get_term_children($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...
3500
                        $term_array[$term_id] = $count;
3501
                    }
3502
                }
3503
            }
3504 7
        } else { // Update reviews count for all post categories.
3505
            $term_array = array();
3506
            $post_types = geodir_get_posttypes();
3507
            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...
3508
3509
                $taxonomy = geodir_get_taxonomies($post_type);
3510
                $taxonomy = $taxonomy[0];
3511
3512
                $args = array(
3513
                    'hide_empty' => false
3514
                );
3515
3516
                $terms = get_terms($taxonomy, $args);
3517
3518
                foreach ($terms as $term) {
3519
                    $count = geodir_count_reviews_by_term_id($term->term_id, $taxonomy, $post_type);
3520
                    $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...
3521
                    /*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...
3522
                        foreach ( $children as $child_id ) {
3523
                            $child_count = geodir_count_reviews_by_term_id($child_id, $taxonomy, $post_type);
3524
                            $count = $count + $child_count;
3525
                        }
3526
                    }*/
3527
                    $term_array[$term->term_id] = $count;
3528
                }
3529
            }
3530
        }
3531
3532 7
        update_option('geodir_global_review_count', $term_array);
3533
        //clear cache
3534 7
        wp_cache_delete('geodir_global_review_count');
3535 7
        return $term_array;
3536
    } else {
3537 1
        return $option_data;
3538
    }
3539
}
3540
3541
/**
3542
 * Force update review count.
3543
 *
3544
 * @since 1.0.0
3545
 * @since 1.6.1 Fixed add listing page load time.
3546
 * @package GeoDirectory
3547
 * @return bool
3548
 */
3549
function geodir_term_review_count_force_update($new_status, $old_status = '', $post = '') {
3550 8
    if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'geodir_import_export') {
3551
        return; // do not run if importing listings
3552
    }
3553
    
3554 8
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
3555
        return;
3556
    }
3557
3558 8
    $post_ID = 0;
3559 8
    if (!empty($post)) {
3560 8
        if (isset($post->post_type) && strpos($post->post_type, 'gd_') !== 0) {
3561 2
            return;
3562
        }
3563
        
3564 6
        if ($new_status == 'auto-draft' && $old_status == 'new') {
3565
            return;
3566
        }
3567
        
3568 6
        if (!empty($post->ID)) {
3569 6
            $post_ID = $post->ID;
3570 6
        }
3571 6
    }
3572
3573 6
    if ($new_status != $old_status) {
3574 5
        geodir_count_reviews_by_terms(true, $post_ID);
3575 5
    }
3576
3577 6
    return true;
3578
}
3579
3580
function geodir_term_review_count_force_update_single_post($post_id){
3581 4
    geodir_count_reviews_by_terms(true, $post_id); 
3582 4
}
3583
3584
/*-----------------------------------------------------------------------------------*/
3585
/*  Term count functions
3586
/*-----------------------------------------------------------------------------------*/
3587
/**
3588
 * Count posts by term.
3589
 *
3590
 * @since 1.0.0
3591
 * @package GeoDirectory
3592
 * @param array $data Count data array.
3593
 * @param object $term The term object.
3594
 * @return int Post count.
3595
 */
3596
function geodir_count_posts_by_term($data, $term)
3597
{
3598
3599
    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...
3600
        if (isset($data[$term->term_id])) {
3601
            return $data[$term->term_id];
3602
        } else {
3603
            return 0;
3604
        }
3605
    } else {
3606
        return $term->count;
3607
    }
3608
}
3609
3610
/**
3611
 * Sort terms object by post count.
3612
 *
3613
 * @since 1.0.0
3614
 * @package GeoDirectory
3615
 * param array $terms An array of term objects.
3616
 * @return array Sorted terms array.
3617
 */
3618
function geodir_sort_terms_by_count($terms)
3619
{
3620 4
    usort($terms, "geodir_sort_by_count_obj");
3621 4
    return $terms;
3622
}
3623
3624
/**
3625
 * Sort terms object by review count.
3626
 *
3627
 * @since 1.0.0
3628
 * @package GeoDirectory
3629
 * @param array $terms An array of term objects.
3630
 * @return array Sorted terms array.
3631
 */
3632
function geodir_sort_terms_by_review_count($terms)
3633
{
3634 1
    usort($terms, "geodir_sort_by_review_count_obj");
3635 1
    return $terms;
3636
}
3637
3638
/**
3639
 * Sort terms either by post count or review count.
3640
 *
3641
 * @since 1.0.0
3642
 * @package GeoDirectory
3643
 * @param array $terms An array of term objects.
3644
 * @param string $sort The sort type. Can be count (Post Count) or review_count. Default. count.
3645
 * @return array Sorted terms array.
3646
 */
3647
function geodir_sort_terms($terms, $sort = 'count')
3648
{
3649 5
    if ($sort == 'count') {
3650 4
        return geodir_sort_terms_by_count($terms);
3651
    }
3652 1
    if ($sort == 'review_count') {
3653 1
        return geodir_sort_terms_by_review_count($terms);
3654
    }
3655
}
3656
3657
/*-----------------------------------------------------------------------------------*/
3658
/*  Utils
3659
/*-----------------------------------------------------------------------------------*/
3660
/**
3661
 * Compares post count from array for sorting.
3662
 *
3663
 * @since 1.0.0
3664
 * @package GeoDirectory
3665
 * @param array $a The left side array to compare.
3666
 * @param array $b The right side array to compare.
3667
 * @return bool
3668
 */
3669
function geodir_sort_by_count($a, $b)
3670
{
3671
    return $a['count'] < $b['count'];
3672
}
3673
3674
/**
3675
 * Compares post count from object for sorting.
3676
 *
3677
 * @since 1.0.0
3678
 * @package GeoDirectory
3679
 * @param object $a The left side object to compare.
3680
 * @param object $b The right side object to compare.
3681
 * @return bool
3682
 */
3683
function geodir_sort_by_count_obj($a, $b)
3684
{
3685 4
    return $a->count < $b->count;
3686
}
3687
3688
/**
3689
 * Compares review count from object for sorting.
3690
 *
3691
 * @since 1.0.0
3692
 * @package GeoDirectory
3693
 * @param object $a The left side object to compare.
3694
 * @param object $b The right side object to compare.
3695
 * @return bool
3696
 */
3697
function geodir_sort_by_review_count_obj($a, $b)
3698
{
3699 1
    return $a->review_count < $b->review_count;
3700
}
3701
3702
/**
3703
 * Load geodirectory plugin textdomain.
3704
 *
3705
 * @since 1.4.2
3706
 * @package GeoDirectory
3707
 */
3708
function geodir_load_textdomain() {
3709
    /**
3710
     * Filter the plugin locale.
3711
     *
3712
     * @since 1.4.2
3713
     * @package GeoDirectory
3714
     */
3715
    $locale = apply_filters('plugin_locale', get_locale(), 'geodirectory');
3716
3717
    load_textdomain('geodirectory', WP_LANG_DIR . '/' . 'geodirectory' . '/' . 'geodirectory' . '-' . $locale . '.mo');
3718
    load_plugin_textdomain('geodirectory', false, plugin_basename(dirname(dirname(__FILE__))) . '/geodirectory-languages');
3719
3720
    /**
3721
     * Define language constants.
3722
     *
3723
     * @since 1.0.0
3724
     */
3725
    require_once(geodir_plugin_path() . '/language.php');
3726
3727
    $language_file = geodir_plugin_path() . '/db-language.php';
3728
3729
    // Load language string file if not created yet
3730
    if (!file_exists($language_file)) {
3731
        geodirectory_load_db_language();
3732
    }
3733
3734
    if (file_exists($language_file)) {
3735
        /**
3736
         * Language strings from database.
3737
         *
3738
         * @since 1.4.2
3739
         */
3740
        try {
3741
            require_once($language_file);
3742
        } catch(Exception $e) {
3743
            error_log('Language Error: ' . $e->getMessage());
3744
        }
3745
    }
3746
}
3747
3748
/**
3749
 * Load language strings in to file to translate via po editor
3750
 *
3751
 * @since 1.4.2
3752
 * @package GeoDirectory
3753
 *
3754
 * @global null|object $wp_filesystem WP_Filesystem object.
3755
 *
3756
 * @return bool True if file created otherwise false
3757
 */
3758
function geodirectory_load_db_language() {
3759 1
    global $wp_filesystem;
3760 1
    if( empty( $wp_filesystem ) ) {
3761 1
        require_once( ABSPATH .'/wp-admin/includes/file.php' );
3762 1
        WP_Filesystem();
3763 1
        global $wp_filesystem;
3764 1
    }
3765
3766 1
    $language_file = geodir_plugin_path() . '/db-language.php';
3767
3768 1
    if(is_file($language_file) && !is_writable($language_file))
3769 1
        return false; // Not possible to create.
3770
3771 1
    if(!is_file($language_file) && !is_writable(dirname($language_file)))
3772 1
        return false; // Not possible to create.
3773
3774 1
    $contents_strings = array();
3775
3776
    /**
3777
     * Filter the language string from database to translate via po editor
3778
     *
3779
     * @since 1.4.2
3780
     *
3781
     * @param array $contents_strings Array of strings.
3782
     */
3783 1
    $contents_strings = apply_filters('geodir_load_db_language', $contents_strings);
3784
3785 1
    $contents_strings = array_unique($contents_strings);
3786
3787 1
    $contents_head = array();
3788 1
    $contents_head[] = "<?php";
3789 1
    $contents_head[] = "/**";
3790 1
    $contents_head[] = " * Translate language string stored in database. Ex: Custom Fields";
3791 1
    $contents_head[] = " *";
3792 1
    $contents_head[] = " * @package GeoDirectory";
3793 1
    $contents_head[] = " * @since 1.4.2";
3794 1
    $contents_head[] = " */";
3795 1
    $contents_head[] = "";
3796 1
    $contents_head[] = "// Language keys";
3797
3798 1
    $contents_foot = array();
3799 1
    $contents_foot[] = "";
3800 1
    $contents_foot[] = "";
3801
3802 1
    $contents = implode(PHP_EOL, $contents_head);
3803
3804 1
    if (!empty($contents_strings)) {
3805 1
        foreach ( $contents_strings as $string ) {
3806 1
            if (is_scalar($string) && $string != '') {
3807 1
                $string = str_replace("'", "\'", $string);
3808 1
                $contents .= PHP_EOL . "__('" . $string . "', 'geodirectory');";
3809 1
            }
3810 1
        }
3811 1
    }
3812
3813 1
    $contents .= implode(PHP_EOL, $contents_foot);
3814
3815 1
    if($wp_filesystem->put_contents( $language_file, $contents, FS_CHMOD_FILE))
3816 1
        return false; // Failure; could not write file.
3817
3818
    return true;
3819
}
3820
3821
/**
3822
 * Get the custom fields texts for translation
3823
 *
3824
 * @since 1.4.2
3825
 * @since 1.5.7 Option values are translatable via db translation.
3826
 * @package GeoDirectory
3827
 *
3828
 * @global object $wpdb WordPress database abstraction object.
3829
 *
3830
 * @param  array $translation_texts Array of text strings.
3831
 * @return array Translation texts.
3832
 */
3833
function geodir_load_custom_field_translation($translation_texts = array()) {
3834 1
    global $wpdb;
3835
3836
    // Custom fields table
3837 1
    $sql = "SELECT admin_title, admin_desc, site_title, clabels, required_msg, default_value, option_values FROM " . GEODIR_CUSTOM_FIELDS_TABLE;
3838 1
    $rows = $wpdb->get_results($sql);
3839
3840 1
    if (!empty($rows)) {
3841 1
        foreach($rows as $row) {
3842 1
            if (!empty($row->admin_title))
3843 1
                $translation_texts[] = stripslashes_deep($row->admin_title);
3844
			
3845 1
            if (!empty($row->admin_desc))
3846 1
                $translation_texts[] = stripslashes_deep($row->admin_desc);
3847
3848 1
            if (!empty($row->site_title))
3849 1
                $translation_texts[] = stripslashes_deep($row->site_title);
3850
3851 1
            if (!empty($row->clabels))
3852 1
                $translation_texts[] = stripslashes_deep($row->clabels);
3853
3854 1
            if (!empty($row->required_msg))
3855 1
                $translation_texts[] = stripslashes_deep($row->required_msg);
3856
			
3857 1
			if (!empty($row->default_value))
3858 1
                $translation_texts[] = stripslashes_deep($row->default_value);
3859
			
3860 1
			if (!empty($row->option_values)) {
3861 1
				$option_values = geodir_string_values_to_options(stripslashes_deep($row->option_values));
3862
				
3863 1
				if (!empty($option_values)) {
3864 1
					foreach ($option_values as $option_value) {
3865 1
						if (!empty($option_value['label'])) {
3866 1
							$translation_texts[] = $option_value['label'];
3867 1
						}
3868 1
					}
3869 1
				}
3870 1
			}
3871 1
        }
3872 1
    }
3873
	
3874
    // Custom sorting fields table
3875 1
    $sql = "SELECT site_title, asc_title, desc_title FROM " . GEODIR_CUSTOM_SORT_FIELDS_TABLE;
3876 1
    $rows = $wpdb->get_results($sql);
3877
3878 1 View Code Duplication
    if (!empty($rows)) {
3879
        foreach($rows as $row) {
3880
            if (!empty($row->site_title))
3881
                $translation_texts[] = stripslashes_deep($row->site_title);
3882
3883
            if (!empty($row->asc_title))
3884
                $translation_texts[] = stripslashes_deep($row->asc_title);
3885
3886
            if (!empty($row->desc_title))
3887
                $translation_texts[] = stripslashes_deep($row->desc_title);
3888
        }
3889
    }
3890
	
3891
	// Advance search filter fields table
3892 1
	if (defined('GEODIR_ADVANCE_SEARCH_TABLE')) {
3893
		$sql = "SELECT field_site_name, front_search_title, field_desc FROM " . GEODIR_ADVANCE_SEARCH_TABLE;
3894
		$rows = $wpdb->get_results($sql);
3895
3896 View Code Duplication
		if (!empty($rows)) {
3897
			foreach($rows as $row) {
3898
				if (!empty($row->field_site_name))
3899
					$translation_texts[] = stripslashes_deep($row->field_site_name);
3900
3901
				if (!empty($row->front_search_title))
3902
					$translation_texts[] = stripslashes_deep($row->front_search_title);
3903
3904
				if (!empty($row->field_desc))
3905
					$translation_texts[] = stripslashes_deep($row->field_desc);
3906
			}
3907
		}
3908
	}
3909
3910 1
    $translation_texts = !empty($translation_texts) ? array_unique($translation_texts) : $translation_texts;
3911
3912 1
    return $translation_texts;
3913
}
3914
3915
/**
3916
 * Retrieve list of mime types and file extensions allowed for file upload.
3917
 *
3918
 * @since 1.4.7
3919
 * @package GeoDirectory
3920
 *
3921
 * @return array Array of mime types.
3922
 */
3923
function geodir_allowed_mime_types() {
3924
    /**
3925
     * Filter the list of mime types and file extensions allowed for file upload.
3926
     *
3927
     * @since 1.4.7
3928
     * @package GeoDirectory
3929
     *
3930
     * @param array $geodir_allowed_mime_types and file extensions.
3931
     */
3932
    return apply_filters( 'geodir_allowed_mime_types', array(
3933
            'Image' => array( // Image formats.
3934
                'jpg' => 'image/jpeg',
3935
                'jpe' => 'image/jpeg',
3936
                'jpeg' => 'image/jpeg',
3937
                'gif' => 'image/gif',
3938
                'png' => 'image/png',
3939
                'bmp' => 'image/bmp',
3940
                'ico' => 'image/x-icon',
3941
            ),
3942
            'Video' => array( // Video formats.
3943
                'asf' => 'video/x-ms-asf',
3944
                'avi' => 'video/avi',
3945
                'flv' => 'video/x-flv',
3946
                'mkv' => 'video/x-matroska',
3947
                'mp4' => 'video/mp4',
3948
                'mpeg' => 'video/mpeg',
3949
                'mpg' => 'video/mpeg',
3950
                'wmv' => 'video/x-ms-wmv',
3951
                '3gp' => 'video/3gpp',
3952
            ),
3953
            'Audio' => array( // Audio formats.
3954
                'ogg' => 'audio/ogg',
3955
                'mp3' => 'audio/mpeg',
3956
                'wav' => 'audio/wav',
3957
                'wma' => 'audio/x-ms-wma',
3958
            ),
3959
            'Text' => array( // Text formats.
3960
                'css' => 'text/css',
3961
                'csv' => 'text/csv',
3962
                'htm' => 'text/html',
3963
                'html' => 'text/html',
3964
                'txt' => 'text/plain',
3965
                'rtx' => 'text/richtext',
3966
                'vtt' => 'text/vtt',
3967
            ),
3968
            'Application' => array( // Application formats.
3969
                'doc' => 'application/msword',
3970
                'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3971
                'exe' => 'application/x-msdownload',
3972
                'js' => 'application/javascript',
3973
                'odt' => 'application/vnd.oasis.opendocument.text',
3974
                'pdf' => 'application/pdf',
3975
                'pot' => 'application/vnd.ms-powerpoint',
3976
                'ppt' => 'application/vnd.ms-powerpoint',
3977
                'pptx' => 'application/vnd.ms-powerpoint',
3978
                'psd' => 'application/octet-stream',
3979
                'rar' => 'application/rar',
3980
                'rtf' => 'application/rtf',
3981
                'swf' => 'application/x-shockwave-flash',
3982
                'tar' => 'application/x-tar',
3983
                'xls' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3984
                'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3985
                'zip' => 'application/zip',
3986
            )
3987
        )
3988
    );
3989
}
3990
3991
/**
3992
 * Retrieve list of user display name for user id.
3993
 *
3994
 * @since 1.5.0
3995
 *
3996
 * @param  string $user_id The WP user id.
3997
 * @return string User display name.
3998
 */
3999
function geodir_get_client_name($user_id) {
4000 9
    $client_name = '';
4001
4002 9
    $user_data = get_userdata($user_id);
4003
4004 9
    if (!empty($user_data)) {
4005 2
        if (isset($user_data->display_name) && trim($user_data->display_name) != '') {
4006 2
            $client_name = trim($user_data->display_name);
4007 2
        } else if (isset($user_data->user_nicename) && trim($user_data->user_nicename) != '') {
4008
            $client_name = trim($user_data->user_nicename);
4009
        } else {
4010
            $client_name = trim($user_data->user_login);
4011
        }
4012 2
    }
4013
4014 9
    return $client_name;
4015
}
4016
4017
4018
4019
4020
4021
add_filter('wpseo_replacements','geodir_wpseo_replacements',10,1);
4022
/*
4023
 * Add location variables to wpseo replacements.
4024
 *
4025
 * @since 1.5.4
4026
 */
4027
function geodir_wpseo_replacements($vars){
4028
4029
    global $wp;
4030
    $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...
4031
    // location variables
4032
    $gd_post_type = geodir_get_current_posttype();
4033
    $location_array = geodir_get_current_location_terms('query_vars', $gd_post_type);
4034
    /**
4035
     * Filter the title variables location variables array
4036
     *
4037
     * @since 1.5.5
4038
     * @package GeoDirectory
4039
     * @param array $location_array The array of location variables.
4040
     * @param array $vars The page title variables.
4041
     */
4042
    $location_array = apply_filters('geodir_filter_title_variables_location_arr_seo',$location_array, $vars);
4043
    $location_titles = array();
4044 View Code Duplication
    if(get_query_var( 'gd_country_full' )){
4045
        if(get_query_var( 'gd_country_full' )){$location_array['gd_country'] = get_query_var( 'gd_country_full' );}
4046
        if(get_query_var( 'gd_region_full' )){$location_array['gd_region'] = get_query_var( 'gd_region_full' );}
4047
        if(get_query_var( 'gd_city_full' )){$location_array['gd_city'] = get_query_var( 'gd_city_full' );}
4048
    }
4049
    $location_single = '';
4050
    $gd_country = (isset($wp->query_vars['gd_country']) && $wp->query_vars['gd_country'] != '') ? $wp->query_vars['gd_country'] : '';
4051
    $gd_region = (isset($wp->query_vars['gd_region']) && $wp->query_vars['gd_region'] != '') ? $wp->query_vars['gd_region'] : '';
4052
    $gd_city = (isset($wp->query_vars['gd_city']) && $wp->query_vars['gd_city'] != '') ? $wp->query_vars['gd_city'] : '';
4053
4054
    $gd_country_actual = $gd_region_actual = $gd_city_actual = '';
4055
4056 View Code Duplication
    if (function_exists('get_actual_location_name')) {
4057
        $gd_country_actual = $gd_country != '' ? get_actual_location_name('country', $gd_country, true) : $gd_country;
4058
        $gd_region_actual = $gd_region != '' ? get_actual_location_name('region', $gd_region) : $gd_region;
4059
        $gd_city_actual = $gd_city != '' ? get_actual_location_name('city', $gd_city) : $gd_city;
4060
    }
4061
4062 View Code Duplication
    if ($gd_city != '') {
4063
        if ($gd_city_actual != '') {
4064
            $gd_city = $gd_city_actual;
4065
        } else {
4066
            $gd_city = preg_replace('/-(\d+)$/', '', $gd_city);
4067
            $gd_city = preg_replace('/[_-]/', ' ', $gd_city);
4068
            $gd_city = __(geodir_ucwords($gd_city), 'geodirectory');
4069
        }
4070
        $location_single = $gd_city;
4071
4072
    } else if ($gd_region != '') {
4073
        if ($gd_region_actual != '') {
4074
            $gd_region = $gd_region_actual;
4075
        } else {
4076
            $gd_region = preg_replace('/-(\d+)$/', '', $gd_region);
4077
            $gd_region = preg_replace('/[_-]/', ' ', $gd_region);
4078
            $gd_region = __(geodir_ucwords($gd_region), 'geodirectory');
4079
        }
4080
4081
        $location_single = $gd_region;
4082
    } else if ($gd_country != '') {
4083
        if ($gd_country_actual != '') {
4084
            $gd_country = $gd_country_actual;
4085
        } else {
4086
            $gd_country = preg_replace('/-(\d+)$/', '', $gd_country);
4087
            $gd_country = preg_replace('/[_-]/', ' ', $gd_country);
4088
            $gd_country = __(geodir_ucwords($gd_country), 'geodirectory');
4089
        }
4090
4091
        $location_single = $gd_country;
4092
    }
4093
4094 View Code Duplication
    if (!empty($location_array)) {
4095
4096
        $actual_location_name = function_exists('get_actual_location_name') ? true : false;
4097
        $location_array = array_reverse($location_array);
4098
4099
        foreach ($location_array as $location_type => $location) {
4100
            $gd_location_link_text = preg_replace('/-(\d+)$/', '', $location);
4101
            $gd_location_link_text = preg_replace('/[_-]/', ' ', $gd_location_link_text);
4102
4103
            $location_name = geodir_ucwords($gd_location_link_text);
4104
            $location_name = __($location_name, 'geodirectory');
4105
4106
            if ($actual_location_name) {
4107
                $location_type = strpos($location_type, 'gd_') === 0 ? substr($location_type, 3) : $location_type;
4108
                $location_name = get_actual_location_name($location_type, $location, true);
4109
            }
4110
4111
            $location_titles[] = $location_name;
4112
        }
4113
        if (!empty($location_titles)) {
4114
            $location_titles = array_unique($location_titles);
4115
        }
4116
    }
4117
4118
4119
    if(!empty($location_titles)) {
4120
        $vars['%%location%%'] = implode(", ", $location_titles);
4121
    }
4122
4123
4124
    if(!empty($location_titles)) {
4125
        $vars['%%in_location%%'] = __('in ', 'geodirectory') . implode(", ", $location_titles);
4126
    }
4127
4128
4129
4130
    if($location_single) {
4131
        $vars['%%in_location_single%%'] = __('in', 'geodirectory') . ' ' .$location_single;
4132
    }
4133
4134
4135
    if($location_single) {
4136
        $vars['%%location_single%%'] = $location_single;
4137
    }
4138
4139
    /**
4140
     * Filter the title variables after standard ones have been filtered for wpseo.
4141
     *
4142
     * @since 1.5.7
4143
     * @package GeoDirectory
4144
     * @param string $vars The title with variables.
4145
     * @param array $location_array The array of location variables.
4146
     */
4147
    return apply_filters('geodir_wpseo_replacements_vars',$vars,$location_array);
4148
}
4149
4150
4151
add_filter('geodir_seo_meta_title','geodir_filter_title_variables',10,3);
4152
add_filter('geodir_seo_page_title','geodir_filter_title_variables',10,2);
4153
add_filter('geodir_seo_meta_description_pre','geodir_filter_title_variables',10,3);
4154
function geodir_filter_title_variables($title, $gd_page, $sep=''){
4155
4156
4157 7
    if(!$gd_page || !$title){return $title;}// if no a GD page then bail.
4158 5
    global $post;
4159
    //print_r($post);
4160
    /*
4161
    %%date%%	                Replaced with the date of the post/page
4162
    %%title%%	                Replaced with the title of the post/page
4163
    %%sitename%%	            The site's name
4164
    %%sitedesc%%	            The site's tagline / description
4165
    %%excerpt%%	                Replaced with the post/page excerpt (or auto-generated if it does not exist)
4166
    %%tag%%	                    Replaced with the current tag/tags
4167
    %%category%%	            Replaced with the post categories (comma separated)
4168
    %%category_description%%	Replaced with the category description
4169
    %%tag_description%%	        Replaced with the tag description
4170
    %%term_description%%	    Replaced with the term description
4171
    %%term_title%%	            Replaced with the term name
4172
    %%searchphrase%%	        Replaced with the current search phrase
4173
    %%sep%%	                    The separator defined in your theme's wp_title() tag.
4174
4175
    ADVANCED
4176
    %%pt_single%%	            Replaced with the post type single label
4177
    %%pt_plural%%	            Replaced with the post type plural label
4178
    %%modified%%	            Replaced with the post/page modified time
4179
    %%id%%	                    Replaced with the post/page ID
4180
    %%name%%	                Replaced with the post/page author's 'nicename'
4181
    %%userid%%	                Replaced with the post/page author's userid
4182
    %%page%%	                Replaced with the current page number (i.e. page 2 of 4)
4183
    %%pagetotal%%	            Replaced with the current page total
4184
    %%pagenumber%%	            Replaced with the current page number
4185
     */
4186
4187 5
    if ($sep == '') {
4188
        /**
4189
         * Filter the page title separator.
4190
         *
4191
         * @since 1.0.0
4192
         * @package GeoDirectory
4193
         * @param string $sep The separator, default: `|`.
4194
         */
4195 2
        $sep = apply_filters('geodir_page_title_separator', '|');
4196 2
    }
4197
4198
4199 5
    if(strpos($title,'%%title%%') !== false){
4200 3
        $title = str_replace("%%title%%",$post->post_title,$title);
4201 3
    }
4202
4203 5 View Code Duplication
    if(strpos($title,'%%sitename%%') !== false){
4204 5
        $title = str_replace("%%sitename%%",get_bloginfo('name'),$title);
4205 5
    }
4206
4207 5 View Code Duplication
    if(strpos($title,'%%sitedesc%%') !== false){
4208
        $title = str_replace("%%sitedesc%%",get_bloginfo('description'),$title);
4209
    }
4210
4211 5
    if(strpos($title,'%%excerpt%%') !== false){
4212
        $title = str_replace("%%excerpt%%",strip_tags(get_the_excerpt()),$title);
4213
    }
4214
4215 5
    if(strpos($title,'%%pt_single%%') !== false){
4216 1
        $single_name = '';
4217 1
        if($gd_page=='search' || $gd_page=='author'){
4218
            $geodir_post_types = get_option('geodir_post_types');
4219
            $spt = esc_attr($_REQUEST['stype']);
4220
            if(isset($geodir_post_types[$spt]['labels']['singular_name'])){
4221
                $single_name = __($geodir_post_types[$spt]['labels']['singular_name'],'geodirectory');
4222
            }
4223 1
        }elseif($gd_page=='add-listing'){
4224 1
            $geodir_post_types = get_option('geodir_post_types');
4225 1
            $spt = isset($_REQUEST['listing_type']) ? esc_attr($_REQUEST['listing_type']) : '';
4226 1
            if(!$spt && isset($_REQUEST['pid'])){
4227
                $spt = get_post_type( $_REQUEST['pid'] );
4228
            }
4229 1
            if(!$spt){$spt='gd_place';}
4230 1
            if(isset($geodir_post_types[$spt]['labels']['singular_name'])){
4231 1
                $single_name = __($geodir_post_types[$spt]['labels']['singular_name'],'geodirectory');
4232 1
            }
4233 1
        }
4234 View Code Duplication
        elseif($post->post_type){
4235
            $geodir_post_types = get_option('geodir_post_types');
4236
            if(isset($geodir_post_types[$post->post_type]['labels']['singular_name'])){
4237
                $single_name = __($geodir_post_types[$post->post_type]['labels']['singular_name'],'geodirectory');
4238
            }
4239
4240
4241
        }
4242 1
        $title = str_replace("%%pt_single%%",$single_name,$title);
4243 1
    }
4244
4245 5
    if(strpos($title,'%%pt_plural%%') !== false){
4246 2
        $plural_name = '';
4247 2
        if($gd_page=='search' || $gd_page=='author'){
4248 2
            $geodir_post_types = get_option('geodir_post_types');
4249 2
            $spt = esc_attr($_REQUEST['stype']);
4250 2
            if(isset($geodir_post_types[$spt]['labels']['name'])){
4251 2
                $plural_name = __($geodir_post_types[$spt]['labels']['name'],'geodirectory');
4252 2
            }
4253 2
        }elseif($gd_page=='add-listing'){
4254
            $geodir_post_types = get_option('geodir_post_types');
4255
            $spt = sanitize_text_field($_REQUEST['listing_type']);
4256
            if(!$spt){$spt='gd_place';}
4257
            if(isset($geodir_post_types[$spt]['labels']['name'])){
4258
                $plural_name = __($geodir_post_types[$spt]['labels']['name'],'geodirectory');
4259
            }
4260
        }
4261 1 View Code Duplication
        elseif(isset($post->post_type) && $post->post_type){
4262 1
            $geodir_post_types = get_option('geodir_post_types');
4263 1
            if(isset($geodir_post_types[$post->post_type]['labels']['name'])){
4264 1
                $plural_name = __($geodir_post_types[$post->post_type]['labels']['name'],'geodirectory');
4265 1
            }
4266
4267 1
        }
4268 2
        $title = str_replace("%%pt_plural%%",$plural_name,$title);
4269 2
    }
4270
4271
4272
4273 5 View Code Duplication
    if(strpos($title,'%%category%%') !== false){
4274
        $cat_name = '';
4275
4276
        if($gd_page=='detail') {
4277
            if ($post->default_category) {
4278
                $cat = get_term($post->default_category, $post->post_type . 'category');
4279
                $cat_name = (isset($cat->name)) ? $cat->name : '';
4280
            }
4281
        }elseif($gd_page=='listing'){
4282
            $queried_object = get_queried_object();
4283
            if(isset($queried_object->name)){
4284
                $cat_name = $queried_object->name;
4285
            }
4286
        }
4287
        $title = str_replace("%%category%%",$cat_name,$title);
4288
    }
4289
4290 5 View Code Duplication
    if(strpos($title,'%%tag%%') !== false){
4291
        $cat_name = '';
4292
4293
        if($gd_page=='detail') {
4294
            if ($post->default_category) {
4295
                $cat = get_term($post->default_category, $post->post_type . 'category');
4296
                $cat_name = (isset($cat->name)) ? $cat->name : '';
4297
            }
4298
        }elseif($gd_page=='listing'){
4299
            $queried_object = get_queried_object();
4300
            if(isset($queried_object->name)){
4301
                $cat_name = $queried_object->name;
4302
            }
4303
        }
4304
        $title = str_replace("%%tag%%",$cat_name,$title);
4305
    }
4306
4307
4308
4309 5
    if(strpos($title,'%%id%%') !== false){
4310
        $ID = (isset($post->ID)) ? $post->ID : '';
4311
        $title = str_replace("%%id%%",$ID,$title);
4312
    }
4313
4314 5
    if(strpos($title,'%%sep%%') !== false){
4315 5
        $title = str_replace("%%sep%%",$sep,$title);
4316 5
    }
4317
4318
4319 5
    global $wp;
4320
    // location variables
4321 5
    $gd_post_type = geodir_get_current_posttype();
4322 5
    $location_array = geodir_get_current_location_terms('query_vars', $gd_post_type);
4323
    /**
4324
     * Filter the title variables location variables array
4325
     *
4326
     * @since 1.5.5
4327
     * @package GeoDirectory
4328
     * @param array $location_array The array of location variables.
4329
     * @param string $title The title with variables..
4330
     * @param string $gd_page The page being filtered.
4331
     * @param string $sep The separator, default: `|`.
4332
     */
4333 5
    $location_array = apply_filters('geodir_filter_title_variables_location_arr',$location_array,$title, $gd_page, $sep);
4334 5
    $location_titles = array();
4335 5 View Code Duplication
    if($gd_page=='location' && get_query_var( 'gd_country_full' )){
4336
        if(get_query_var( 'gd_country_full' )){$location_array['gd_country'] = get_query_var( 'gd_country_full' );}
4337
        if(get_query_var( 'gd_region_full' )){$location_array['gd_region'] = get_query_var( 'gd_region_full' );}
4338
        if(get_query_var( 'gd_city_full' )){$location_array['gd_city'] = get_query_var( 'gd_city_full' );}
4339
    }
4340 5
    $location_single = '';
4341 5
    $gd_country = (isset($wp->query_vars['gd_country']) && $wp->query_vars['gd_country'] != '') ? $wp->query_vars['gd_country'] : '';
4342 5
    $gd_region = (isset($wp->query_vars['gd_region']) && $wp->query_vars['gd_region'] != '') ? $wp->query_vars['gd_region'] : '';
4343 5
    $gd_city = (isset($wp->query_vars['gd_city']) && $wp->query_vars['gd_city'] != '') ? $wp->query_vars['gd_city'] : '';
4344
4345 5
    $gd_country_actual = $gd_region_actual = $gd_city_actual = '';
4346
4347 5 View Code Duplication
    if (function_exists('get_actual_location_name')) {
4348
        $gd_country_actual = $gd_country != '' ? get_actual_location_name('country', $gd_country, true) : $gd_country;
4349
        $gd_region_actual = $gd_region != '' ? get_actual_location_name('region', $gd_region) : $gd_region;
4350
        $gd_city_actual = $gd_city != '' ? get_actual_location_name('city', $gd_city) : $gd_city;
4351
    }
4352
4353 5 View Code Duplication
    if ($gd_city != '') {
4354
        if ($gd_city_actual != '') {
4355
            $gd_city = $gd_city_actual;
4356
        } else {
4357
            $gd_city = preg_replace('/-(\d+)$/', '', $gd_city);
4358
            $gd_city = preg_replace('/[_-]/', ' ', $gd_city);
4359
            $gd_city = __(geodir_ucwords($gd_city), 'geodirectory');
4360
        }
4361
        $location_single = $gd_city;
4362
4363 5
    } else if ($gd_region != '') {
4364
        if ($gd_region_actual != '') {
4365
            $gd_region = $gd_region_actual;
4366
        } else {
4367
            $gd_region = preg_replace('/-(\d+)$/', '', $gd_region);
4368
            $gd_region = preg_replace('/[_-]/', ' ', $gd_region);
4369
            $gd_region = __(geodir_ucwords($gd_region), 'geodirectory');
4370
        }
4371
4372
        $location_single = $gd_region;
4373 5
    } else if ($gd_country != '') {
4374
        if ($gd_country_actual != '') {
4375
            $gd_country = $gd_country_actual;
4376
        } else {
4377
            $gd_country = preg_replace('/-(\d+)$/', '', $gd_country);
4378
            $gd_country = preg_replace('/[_-]/', ' ', $gd_country);
4379
            $gd_country = __(geodir_ucwords($gd_country), 'geodirectory');
4380
        }
4381
4382
        $location_single = $gd_country;
4383
    }
4384
4385 5 View Code Duplication
    if (!empty($location_array)) {
4386
4387
        $actual_location_name = function_exists('get_actual_location_name') ? true : false;
4388
        $location_array = array_reverse($location_array);
4389
4390
        foreach ($location_array as $location_type => $location) {
4391
            $gd_location_link_text = preg_replace('/-(\d+)$/', '', $location);
4392
            $gd_location_link_text = preg_replace('/[_-]/', ' ', $gd_location_link_text);
4393
4394
            $location_name = geodir_ucwords($gd_location_link_text);
4395
            $location_name = __($location_name, 'geodirectory');
4396
4397
            if ($actual_location_name) {
4398
                $location_type = strpos($location_type, 'gd_') === 0 ? substr($location_type, 3) : $location_type;
4399
                $location_name = get_actual_location_name($location_type, $location, true);
4400
            }
4401
4402
            $location_titles[] = $location_name;
4403
        }
4404
        if (!empty($location_titles)) {
4405
            $location_titles = array_unique($location_titles);
4406
        }
4407
    }
4408
4409
4410 5
    if(strpos($title,'%%location%%') !== false){
4411 1
        $location = '';
4412 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...
4413
            $location = implode(", ", $location_titles);
4414
        }
4415 1
        $title = str_replace("%%location%%",$location,$title);
4416 1
    }
4417
4418 5 View Code Duplication
    if(strpos($title,'%%in_location%%') !== false){
4419 1
        $location = '';
4420 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...
4421
            $location = __('in ', 'geodirectory') . implode(", ", $location_titles);
4422
        }
4423 1
        $title = str_replace("%%in_location%%",$location,$title);
4424 1
    }
4425
4426 5 View Code Duplication
    if(strpos($title,'%%in_location_single%%') !== false){
4427 1
        if($location_single) {
4428
            $location_single = __('in', 'geodirectory') . ' ' .$location_single;
4429
        }
4430 1
        $title = str_replace("%%in_location_single%%",$location_single,$title);
4431 1
    }
4432
4433 5
    if(strpos($title,'%%location_single%%') !== false){
4434
        $title = str_replace("%%location_single%%",$location_single,$title);
4435
    }
4436
4437
4438 5 View Code Duplication
    if(strpos($title,'%%search_term%%') !== false){
4439 1
        $search_term = '';
4440 1
        if(isset($_REQUEST['s'])){
4441
            $search_term = esc_attr($_REQUEST['s']);
4442
        }
4443 1
        $title = str_replace("%%search_term%%",$search_term,$title);
4444 1
    }
4445
4446 5 View Code Duplication
    if(strpos($title,'%%search_near%%') !== false){
4447 1
        $search_term = '';
4448 1
        if(isset($_REQUEST['snear'])){
4449
            $search_term = esc_attr($_REQUEST['snear']);
4450
        }
4451 1
        $title = str_replace("%%search_near%%",$search_term,$title);
4452 1
    }
4453
4454 5
    if(strpos($title,'%%name%%') !== false){
4455 1
        $author_name = get_the_author();
4456 1
        if (!$author_name || $author_name === '') {
4457 1
            $queried_object = get_queried_object();
4458
            
4459 1
            if (isset($queried_object->data->user_nicename)) {
4460 1
                $author_name = $queried_object->data->user_nicename;
4461 1
            }
4462 1
        }
4463 1
        $title = str_replace("%%name%%", $author_name, $title);
4464 1
    }
4465
    
4466 5
    if (strpos($title, '%%page%%') !== false) {
4467
        $page = geodir_title_meta_page($sep);
4468
        $title = str_replace("%%page%%", $page, $title);
4469
    }
4470 5
    if (strpos($title, '%%pagenumber%%') !== false) {
4471
        $pagenumber = geodir_title_meta_pagenumber();
4472
        $title = str_replace("%%pagenumber%%", $pagenumber, $title);
4473
    }
4474 5
    if (strpos($title, '%%pagetotal%%') !== false) {
4475
        $pagetotal = geodir_title_meta_pagetotal();
4476
        $title = str_replace("%%pagetotal%%", $pagetotal, $title);
4477
    }
4478
4479 5
    $title = wptexturize( $title );
4480 5
    $title = convert_chars( $title );
4481 5
    $title = esc_html( $title );
4482
4483
    /**
4484
     * Filter the title variables after standard ones have been filtered.
4485
     *
4486
     * @since 1.5.7
4487
     * @package GeoDirectory
4488
     * @param string $title The title with variables.
4489
     * @param array $location_array The array of location variables.
4490
     * @param string $gd_page The page being filtered.
4491
     * @param string $sep The separator, default: `|`.
4492
     */
4493
4494 5
    return apply_filters('geodir_filter_title_variables_vars',$title,$location_array, $gd_page, $sep);
4495
}
4496
4497
/**
4498
 * Get the cpt texts for translation.
4499
 *
4500
 * @since 1.5.5
4501
 * @package GeoDirectory
4502
 *
4503
 * @param  array $translation_texts Array of text strings.
4504
 * @return array Translation texts.
4505
 */
4506
function geodir_load_cpt_text_translation($translation_texts = array()) {
4507 1
    $gd_post_types = geodir_get_posttypes('array');
4508
4509 1
    if (!empty($gd_post_types)) {
4510 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...
4511 1
            $labels = isset($cpt_info['labels']) ? $cpt_info['labels'] : '';
4512 1
            $description = isset($cpt_info['description']) ? $cpt_info['description'] : '';
4513 1
            $seo = isset($cpt_info['seo']) ? $cpt_info['seo'] : '';
4514
4515 1
            if (!empty($labels)) {
4516 1 View Code Duplication
                if ($labels['name'] != '' && !in_array($labels['name'], $translation_texts))
4517 1
                    $translation_texts[] = $labels['name'];
4518 1 View Code Duplication
                if ($labels['singular_name'] != '' && !in_array($labels['singular_name'], $translation_texts))
4519 1
                    $translation_texts[] = $labels['singular_name'];
4520 1 View Code Duplication
                if ($labels['add_new'] != '' && !in_array($labels['add_new'], $translation_texts))
4521 1
                    $translation_texts[] = $labels['add_new'];
4522 1 View Code Duplication
                if ($labels['add_new_item'] != '' && !in_array($labels['add_new_item'], $translation_texts))
4523 1
                    $translation_texts[] = $labels['add_new_item'];
4524 1 View Code Duplication
                if ($labels['edit_item'] != '' && !in_array($labels['edit_item'], $translation_texts))
4525 1
                    $translation_texts[] = $labels['edit_item'];
4526 1 View Code Duplication
                if ($labels['new_item'] != '' && !in_array($labels['new_item'], $translation_texts))
4527 1
                    $translation_texts[] = $labels['new_item'];
4528 1 View Code Duplication
                if ($labels['view_item'] != '' && !in_array($labels['view_item'], $translation_texts))
4529 1
                    $translation_texts[] = $labels['view_item'];
4530 1 View Code Duplication
                if ($labels['search_items'] != '' && !in_array($labels['search_items'], $translation_texts))
4531 1
                    $translation_texts[] = $labels['search_items'];
4532 1 View Code Duplication
                if ($labels['not_found'] != '' && !in_array($labels['not_found'], $translation_texts))
4533 1
                    $translation_texts[] = $labels['not_found'];
4534 1 View Code Duplication
                if ($labels['not_found_in_trash'] != '' && !in_array($labels['not_found_in_trash'], $translation_texts))
4535 1
                    $translation_texts[] = $labels['not_found_in_trash'];
4536 1 View Code Duplication
                if (isset($labels['label_post_profile']) && $labels['label_post_profile'] != '' && !in_array($labels['label_post_profile'], $translation_texts))
4537 1
                    $translation_texts[] = $labels['label_post_profile'];
4538 1 View Code Duplication
                if (isset($labels['label_post_info']) && $labels['label_post_info'] != '' && !in_array($labels['label_post_info'], $translation_texts))
4539 1
                    $translation_texts[] = $labels['label_post_info'];
4540 1 View Code Duplication
                if (isset($labels['label_post_images']) && $labels['label_post_images'] != '' && !in_array($labels['label_post_images'], $translation_texts))
4541 1
                    $translation_texts[] = $labels['label_post_images'];
4542 1 View Code Duplication
                if (isset($labels['label_post_map']) && $labels['label_post_map'] != '' && !in_array($labels['label_post_map'], $translation_texts))
4543 1
                    $translation_texts[] = $labels['label_post_map'];
4544 1 View Code Duplication
                if (isset($labels['label_reviews']) && $labels['label_reviews'] != '' && !in_array($labels['label_reviews'], $translation_texts))
4545 1
                    $translation_texts[] = $labels['label_reviews'];
4546 1 View Code Duplication
                if (isset($labels['label_related_listing']) && $labels['label_related_listing'] != '' && !in_array($labels['label_related_listing'], $translation_texts))
4547 1
                    $translation_texts[] = $labels['label_related_listing'];
4548 1
            }
4549
4550 1
            if ($description != '' && !in_array($description, $translation_texts)) {
4551 1
                $translation_texts[] = normalize_whitespace($description);
4552 1
            }
4553
4554 1
            if (!empty($seo)) {
4555 View Code Duplication
                if (isset($seo['meta_keyword']) && $seo['meta_keyword'] != '' && !in_array($seo['meta_keyword'], $translation_texts))
4556
                    $translation_texts[] = normalize_whitespace($seo['meta_keyword']);
4557
4558 View Code Duplication
                if (isset($seo['meta_description']) && $seo['meta_description'] != '' && !in_array($seo['meta_description'], $translation_texts))
4559
                    $translation_texts[] = normalize_whitespace($seo['meta_description']);
4560
            }
4561 1
        }
4562 1
    }
4563 1
    $translation_texts = !empty($translation_texts) ? array_unique($translation_texts) : $translation_texts;
4564
4565 1
    return $translation_texts;
4566
}
4567
4568
/**
4569
 * Remove the location terms to hide term from location url.
4570
 *
4571
 * @since 1.5.5
4572
 * @package GeoDirectory
4573
 *
4574
 * @param  array $location_terms Array of location terms.
4575
 * @return array Location terms.
4576
 */
4577
function geodir_remove_location_terms($location_terms = array()) {
4578
    $location_manager = defined('POST_LOCATION_TABLE') ? true : false;
4579
4580
    if (!empty($location_terms) && $location_manager) {
4581
        $hide_country_part = get_option('geodir_location_hide_country_part');
4582
        $hide_region_part = get_option('geodir_location_hide_region_part');
4583
4584
        if ($hide_region_part && $hide_country_part) {
4585
            if (isset($location_terms['gd_country']))
4586
                unset($location_terms['gd_country']);
4587
            if (isset($location_terms['gd_region']))
4588
                unset($location_terms['gd_region']);
4589
        } else if ($hide_region_part && !$hide_country_part) {
4590
            if (isset($location_terms['gd_region']))
4591
                unset($location_terms['gd_region']);
4592
        } else if (!$hide_region_part && $hide_country_part) {
4593
            if (isset($location_terms['gd_country']))
4594
                unset($location_terms['gd_country']);
4595
        }
4596
    }
4597
4598
    return $location_terms;
4599
}
4600
4601
/**
4602
 * Send notification when a listing has been edited by it's author.
4603
 *
4604
 * @since 1.5.9
4605
 * @package GeoDirectory
4606
 *
4607
 * @param int $post_ID Post ID.
4608
 * @param WP_Post $post Post object.
4609
 * @param bool $update Whether this is an existing listing being updated or not.
4610
 */
4611
function geodir_on_wp_insert_post($post_ID, $post, $update) {
4612 8
    if (!$update) {
4613 7
        return;
4614
    }
4615
    
4616 1
    $action = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : '';
4617 1
    $is_admin = is_admin() && ( !defined('DOING_AJAX' ) || ( defined('DOING_AJAX') && !DOING_AJAX ) )  ? true : false;
4618 1
    $inline_save = $action == 'inline-save' ? true : false;
4619
4620 1
    if (empty($post->post_type) || $is_admin || $inline_save || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) {
4621
        return;
4622
    }
4623
    
4624 1
    if ($action != '' && in_array($action, array('geodir_import_export'))) {
4625
        return;
4626
    }
4627
4628 1
    $user_id = (int)get_current_user_id();
4629
        
4630 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())) {
4631
        $author_id = !empty($post->post_author) ? $post->post_author : 0;
4632
        
4633
        if ($user_id == $author_id && !is_super_admin()) {
4634
            $from_email = get_option('site_email');
4635
            $from_name = get_site_emailName();
4636
            $to_email = get_option('admin_email');
4637
            $to_name = get_option('name');
4638
            $message_type = 'listing_edited';
4639
            
4640
            $notify_edited = true;
4641
            /**
4642
             * Send notification when listing edited by author?
4643
             *
4644
             * @since 1.6.0
4645
             * @param bool $notify_edited Notify on listing edited by author?
4646
             * @param object $post The current post object.
4647
             */
4648
            $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...
4649
            
4650
            geodir_sendEmail($from_email, $from_name, $to_email, $to_name, '', '', '', $message_type, $post_ID);
4651
        }
4652
    }
4653 1
}
4654
4655
/**
4656
 * Retrieve the current page start & end numbering with context (i.e. 'page 2 of 4') for use as replacement string.
4657
 *
4658
 * @since 1.6.0
4659
 * @package GeoDirectory
4660
 *
4661
 * @param string $sep The separator tag.
4662
 *
4663
 * @return string|null The current page start & end numbering.
4664
 */
4665
function geodir_title_meta_page($sep) {
4666
    $replacement = null;
4667
4668
    $max = geodir_title_meta_pagenumbering('max');
4669
    $nr  = geodir_title_meta_pagenumbering('nr');
4670
4671
    if ($max > 1 && $nr > 1) {
4672
        $replacement = sprintf($sep . ' ' . __('Page %1$d of %2$d', 'geodirectory'), $nr, $max);
4673
    }
4674
4675
    return $replacement;
4676
}
4677
4678
/**
4679
 * Retrieve the current page number for use as replacement string.
4680
 *
4681
 * @since 1.6.0
4682
 * @package GeoDirectory
4683
 *
4684
 * @return string|null The current page number.
4685
 */
4686 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...
4687
    $replacement = null;
4688
4689
    $nr = geodir_title_meta_pagenumbering('nr');
4690
    if (isset($nr) && $nr > 0) {
4691
        $replacement = (string)$nr;
4692
    }
4693
4694
    return $replacement;
4695
}
4696
4697
/**
4698
 * Retrieve the current page total for use as replacement string.
4699
 *
4700
 * @since 1.6.0
4701
 * @package GeoDirectory
4702
 *
4703
 * @return string|null The current page total.
4704
 */
4705 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...
4706
    $replacement = null;
4707
4708
    $max = geodir_title_meta_pagenumbering('max');
4709
    if (isset($max) && $max > 0) {
4710
        $replacement = (string)$max;
4711
    }
4712
4713
    return $replacement;
4714
}
4715
4716
/**
4717
 * Determine the page numbering of the current post/page/cpt.
4718
 *
4719
 * @param string $request 'nr'|'max' - whether to return the page number or the max number of pages.
4720
 *
4721
 * @since 1.6.0
4722
 * @package GeoDirectory
4723
 *
4724
 * @global object $wp_query WordPress Query object.
4725
 * @global object $post The current post object.
4726
 *
4727
 * @return int|null The current page numbering.
4728
 */
4729
function geodir_title_meta_pagenumbering($request = 'nr') {
4730
    global $wp_query, $post;
4731
    $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...
4732
    $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...
4733
4734
    $max_num_pages = 1;
4735
4736
    if (!is_singular()) {
4737
        $page_number = get_query_var('paged');
4738
        if ($page_number === 0 || $page_number === '') {
4739
            $page_number = 1;
4740
        }
4741
4742
        if (isset($wp_query->max_num_pages) && ($wp_query->max_num_pages != '' && $wp_query->max_num_pages != 0)) {
4743
            $max_num_pages = $wp_query->max_num_pages;
4744
        }
4745
    } else {
4746
        $page_number = get_query_var('page');
4747
        if ($page_number === 0 || $page_number === '') {
4748
            $page_number = 1;
4749
        }
4750
4751
        if (isset($post->post_content)) {
4752
            $max_num_pages = (substr_count($post->post_content, '<!--nextpage-->' ) + 1);
4753
        }
4754
    }
4755
4756
    $return = null;
4757
4758
    switch ($request) {
4759
        case 'nr':
4760
            $return = $page_number;
4761
            break;
4762
        case 'max':
4763
            $return = $max_num_pages;
4764
            break;
4765
    }
4766
4767
    return $return;
4768
}
4769
4770
/**
4771
 * Filter the terms with count empty.
4772
 *
4773
 * @since 1.5.4
4774
 *
4775
 * @param array $terms Terms array.
4776
 * @return array Terms.
4777
 */
4778
function geodir_filter_empty_terms($terms) {
4779 3
    if (empty($terms)) {
4780 3
        return $terms;
4781
    }
4782
4783 3
    $return = array();
4784 3
    foreach ($terms as $term) {
4785 3
        if (isset($term->count) && $term->count > 0) {
4786 3
            $return[] = $term;
4787 3
        }
4788 3
    }
4789
    return $return;
4790
}