Test Failed
Pull Request — master (#375)
by Kiran
27:48
created

helper_functions.php ➔ geodir_utf8_ucfirst()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 3
dl 0
loc 16
ccs 0
cts 0
cp 0
crap 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Helper functions, this file contains functions made to make a developer's life easier.
4
 *
5
 * @since 1.4.6
6
 * @package GeoDirectory
7
 */
8
9
/**
10
 * Get the page ID of the add listing page.
11
 *
12
 * @package Geodirectory
13
 * @since 1.4.6
14
 * @return int|null Return the page ID if present or null if not.
15
 */
16
function geodir_add_listing_page_id(){
17 16
    $gd_page_id = get_option('geodir_add_listing_page');
18
19 16
    if (function_exists('icl_object_id')) {
20
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
21
    }
22
23 16
    return $gd_page_id;
24
}
25
26
/**
27
 * Get the page ID of the add listing preview page.
28
 *
29
 * @package Geodirectory
30
 * @since 1.4.6
31
 * @return int|null Return the page ID if present or null if not.
32
 */
33
function geodir_preview_page_id(){
34 6
    $gd_page_id = get_option('geodir_preview_page');
35
36 6
    if (function_exists('icl_object_id')) {
37
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
38
    }
39
40 6
    return $gd_page_id;
41
}
42
43
/**
44
 * Get the page ID of the add listing success page.
45
 *
46
 * @package Geodirectory
47
 * @since 1.4.6
48
 * @return int|null Return the page ID if present or null if not.
49
 */
50
function geodir_success_page_id(){
51 4
    $gd_page_id = get_option('geodir_success_page');
52
53 4
    if (function_exists('icl_object_id')) {
54
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
55
    }
56
57 4
    return $gd_page_id;
58
}
59
60
/**
61
 * Get the page ID of the add location page.
62
 *
63
 * @package Geodirectory
64
 * @since 1.4.6
65
 * @return int|null Return the page ID if present or null if not.
66
 */
67
function geodir_location_page_id(){
68 4
    $gd_page_id = get_option('geodir_location_page');
69
70 4
    if (function_exists('icl_object_id')) {
71
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
72
    }
73
74 4
    return $gd_page_id;
75
}
76
77
/**
78
 * Get the page ID of the GD home page.
79
 *
80
 * @package Geodirectory
81
 * @since 1.5.4
82
 * @return int|null Return the page ID if present or null if not.
83
 */
84
function geodir_home_page_id(){
85 5
    $gd_page_id = get_option('geodir_home_page');
86
87 5
    if (function_exists('icl_object_id')) {
88
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
89
    }
90
91 5
    return $gd_page_id;
92
}
93
94
/**
95
 * Get the page ID of the info page.
96
 *
97
 * @package Geodirectory
98
 * @since 1.5.3
99
 * @return int|null Return the page ID if present or null if not.
100
 */
101
function geodir_info_page_id(){
102
    $gd_page_id = get_option('geodir_info_page');
103
104
    if (function_exists('icl_object_id')) {
105
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
106
    }
107
108
    return $gd_page_id;
109
}
110
111
/**
112
 * Get the page ID of the login page.
113
 *
114
 * @package Geodirectory
115
 * @since 1.5.3
116
 * @return int|null Return the page ID if present or null if not.
117
 */
118
function geodir_login_page_id(){
119 5
    $gd_page_id = get_option('geodir_login_page');
120
121 5
    if (function_exists('icl_object_id')) {
122
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
123
    }
124
125 5
    return $gd_page_id;
126
}
127
128
129
/**
130
 * Get the page ID of the login page.
131
 *
132
 * @package Geodirectory
133
 * @since 1.5.3
134
 * @return int|null Return the page ID if present or null if not.
135
 */
136
function geodir_login_url($args=array()){
137 21
    $gd_page_id = get_option('geodir_login_page');
138
139 21
    if (function_exists('icl_object_id')) {
140
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
141
    }
142
143 21
    if (function_exists('geodir_location_geo_home_link')) {
144
        remove_filter('home_url', 'geodir_location_geo_home_link', 100000);
145
    }
146 21
147 21
    if (geodir_is_wpml()){
148
        $home_url = icl_get_home_url();
149
    }else{
150
        $home_url = home_url();
151 21
    }
152 21
153 21
    if (function_exists('geodir_location_geo_home_link')) {
154
        add_filter('home_url', 'geodir_location_geo_home_link', 100000, 2);
155 21
    }
156 21
157 View Code Duplication
    if($gd_page_id){
158
        $post = get_post($gd_page_id);
159
        $slug = $post->post_name;
160 21
        //$login_url = get_permalink($gd_page_id );// get_permalink can only be user after theme-Setup hook, any earlier and it errors
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...
161 10
        $login_url = trailingslashit($home_url)."$slug/";
162 10
    }else{
163
        $login_url = trailingslashit($home_url)."?geodir_signup=true";
164
    }
165
166
    if($args){
0 ignored issues
show
Bug Best Practice introduced by
The expression $args 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...
167
        $login_url = add_query_arg($args,$login_url );
168
    }
169
170
    /**
171
     * Filter the GeoDirectory login page url.
172
     *
173
     * This filter can be used to change the GeoDirectory page url.
174
     *
175 21
     * @since 1.5.3
176
     * @package GeoDirectory
177
     * @param string $login_url The url of the login page.
178
     * @param array $args The array of query args used.
179
     * @param int $gd_page_id The page id of the GD login page.
180
     */
181
	    return apply_filters('geodir_login_url',$login_url,$args,$gd_page_id);
182
}
183
184
/**
185
 * Returns info page url
186
 *
187
 * @package Geodirectory
188
 * @since 1.5.4
189
 * @since 1.5.16 Added WPML lang code to url.
190
 * @return string Info page url.
191
 */
192
function geodir_info_url($args=array()){
193
    $gd_page_id = get_option('geodir_info_page');
194
195
    if (function_exists('icl_object_id')) {
196
        $gd_page_id =  icl_object_id($gd_page_id, 'page', true);
197
    }
198
199
    if (function_exists('geodir_location_geo_home_link')) {
200
        remove_filter('home_url', 'geodir_location_geo_home_link', 100000);
201
    }
202
203
    if (geodir_is_wpml()){
204
        $home_url = icl_get_home_url();
205
    }else{
206
        $home_url = home_url();
207
    }
208
209
    if (function_exists('geodir_location_geo_home_link')) {
210
        add_filter('home_url', 'geodir_location_geo_home_link', 100000, 2);
211
    }
212
213 View Code Duplication
    if($gd_page_id){
214
        $post = get_post($gd_page_id);
215
        $slug = $post->post_name;
216
        //$login_url = get_permalink($gd_page_id );// get_permalink can only be user after theme-Setup hook, any earlier and it errors
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...
217
        $info_url = trailingslashit($home_url)."$slug/";
218
    }else{
219
        $info_url = trailingslashit($home_url);
220
    }
221
222
    if($args){
0 ignored issues
show
Bug Best Practice introduced by
The expression $args 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...
223
        $info_url = add_query_arg($args,$info_url );
224
    }
225
226
    return $info_url;
227
}
228
229 8
/**
230 8
 * Converts string to title case.
231
 *
232
 * This function converts string to title case. Ex: hello world -> Hello World.
233
 * When mbstring php extension available this function supports all unicode characters.
234
 *
235
 * @package Geodirectory
236
 * @since 1.5.4
237
 * @param string $string String to convert.
238
 * @param string $charset Character set to use for conversion.
239
 * @return string Returns converted string.
240
 */
241
function geodir_ucwords($string, $charset='UTF-8') {
242
    if (function_exists('mb_convert_case')) {
243
        return mb_convert_case($string, MB_CASE_TITLE, $charset);
244
    } else {
245
        return ucwords($string);
246
    }
247
}
248
249 16
/**
250 16
 * Converts string to lower case.
251
 *
252
 * This function converts string to lower case. Ex: HelLO WorLd -> hello world.
253
 * When mbstring php extension available this function supports all unicode characters.
254
 *
255
 * @package Geodirectory
256
 * @since 1.5.4
257
 * @param string $string String to convert.
258
 * @param string $charset Character set to use for conversion.
259
 * @return string Returns converted string.
260
 */
261
function geodir_strtolower($string, $charset='UTF-8') {
262
    if (function_exists('mb_convert_case')) {
263
        return mb_convert_case($string, MB_CASE_LOWER, $charset);
264
    } else {
265
        return strtolower($string);
266
    }
267
}
268
269 4
/**
270 4
 * Converts string to upper case.
271
 *
272
 * This function converts string to upper case. Ex: HelLO WorLd -> HELLO WORLD.
273
 * When mbstring php extension available this function supports all unicode characters.
274
 *
275
 * @package Geodirectory
276
 * @since 1.5.4
277
 * @param string $string String to convert.
278
 * @param string $charset Character set to use for conversion.
279
 * @return string Returns converted string.
280
 */
281
function geodir_strtoupper($string, $charset='UTF-8') {
282
    if (function_exists('mb_convert_case')) {
283
        return mb_convert_case($string, MB_CASE_UPPER, $charset);
284
    } else {
285
        return strtoupper($string);
286
    }
287
}
288
289 2
/**
290
 * Returns parsed url and title.
291
 *
292 2
 * This function converts string to url and title if there is "|" separator used in url.
293
 * Ex: "http://wpgeodirectory.com|GeoDirectory" will return array( url => http://wpgeodirectory.com, label => GeoDirectory ).
294 2
 *
295 2
 * @package Geodirectory
296
 * @since 1.5.7
297 2
 * @param string $url The website url.
298 2
 * @param bool $formatted True if returns formatted url. False if not. Default true.
299 2
 * @return array Parsed url and title.
300 2
 */
301
function geodir_parse_custom_field_url($url, $formatted = true) {
302 2
	if ($url == '' || !is_string($url)) {
303 2
		return NULL;
304 2
	}
305 2
	$original_url = $url;
0 ignored issues
show
Unused Code introduced by
$original_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
306
	
307 2
	$url = stripcslashes($url);
308
	$parts = explode('|', $url, 2);
309 2
	
310
	$url = trim($parts[0]);
311
	if ($formatted && $url != '') {
312
		$url = str_replace( ' ', '%20', $url );
313 2
		$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);
314 2
		
315 2
		if (0 !== stripos($url, 'mailto:')) {
316 2
			$strip = array('%0d', '%0a', '%0D', '%0A');
317
			$url = _deep_replace($strip, $url);
318 2
		}
319 2
		
320 2
		$url = str_replace(';//', '://', $url);
321
		
322
		if (strpos($url, ':') === false && ! in_array($url[0], array('/', '#', '?')) && !preg_match('/^[a-z0-9-]+?\.php/i', $url)) {
323
			$url = 'http://' . $url;
324 2
		}
325
		
326
		$url = wp_kses_normalize_entities($url);
327
		$url = str_replace('&amp;', '&#038;', $url);
328
		$url = str_replace("'", '&#039;', $url);
329
	}
330
	
331
	$return = array();
332
	$return['url'] = $url;
333
	if (!empty($parts[1]) && trim($parts[1]) != '') {
334
		$return['label'] = trim($parts[1]);
335
	}
336
337 6
	return $return;
338 1
}
339 1
340
/**
341 1
 * Set parent categories to fix categories tree structure.
342 1
 *
343
 * @since 1.5.7
344 1
 * @package GeoDirectory
345 1
 *
346 1
 * @param array $request_info Listing request info.
347 1
 * @return array Modified listing request info.
348 1
 */
349 1
function geodir_attach_parent_categories($request_info) {
350 1
	if (!empty($request_info['post_category']) && is_array($request_info['post_category'])) {
351 1
		foreach ($request_info['post_category'] as $taxomony => $term_ids) {			
352 1
			$attach_term_ids = array();
0 ignored issues
show
Unused Code introduced by
$attach_term_ids 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...
353
			
354 6
			if (!empty($term_ids) && is_array($term_ids) && taxonomy_exists($taxomony) && strpos($taxomony, 'category') !== false) {
355
				$attach_term_ids = geodir_add_parent_terms($term_ids, $taxomony);
356
				
357
				if (!empty($attach_term_ids)) {
358
					if (!isset($request_info['post_default_category'])) {
359
						$request_info['post_default_category'] = $attach_term_ids[0];
360
					}
361
					$request_info['post_category'][$taxomony] = $attach_term_ids;
362
				}
363
			}
364
		}
365
	}
366
	
367
	return $request_info;
368 1
}
369
370
/**
371
 * Add the parent terms in current terms.
372 1
 *
373
 * @since 1.5.7
374 1
 * @package GeoDirectory
375 1
 *
376 1
 * @param int|array $term_ids Term id or Terms array.
377
 * @param string $taxomony Category taxonomy of post type.
378 1
 * @return array Modified term ids.
379
 */
380
function geodir_add_parent_terms($term_ids, $taxomony) {	
381 1
	if (is_int($term_ids)) {
382
		$term_ids = array($term_ids);
383 1
	}
384
	
385
	$parent_terms = array();
386
	
387
	foreach ($term_ids as $term_id) {
388
		$parent_terms[] = $term_id;
389
		$term_parents = geodir_get_category_parents($term_id, $taxomony, $parent_terms);
390
		
391
		if (!empty($term_parents)) {
392
			$parent_terms = array_merge($parent_terms, $term_parents);
393
		}
394
	}
395
396
	return $parent_terms;
397
}
398
399 1
/**
400 1
 * Get the parent categories of current id.
401
 *
402
 * @since 1.5.7
403
 * @package GeoDirectory
404 1
 *
405
 * @param int $id Category id.
406
 * @param string $taxomony Category taxonomy of post type.
407
 * @param array $visited Array of category ids already included.
408
 * @param array $parents Array of category ids.
409
 * @return array Category ids.
410 1
 */
411
function geodir_get_category_parents($id, $taxomony, $visited = array(), $parents = array()) {
412
	$parent = get_term($id, $taxomony);
413
	if (is_wp_error($parent)) {
414
		return $parents;
415
	}
416
417
	if (isset($parent->parent) && $parent->parent && ($parent->parent != $parent->term_id) && !in_array($parent->parent, $visited)) {
418
		$visited[] = $parent->parent;
419
		$parents[] = $parent->parent;
420
		$parents = geodir_get_category_parents($parent->parent, $taxomony, $visited, $parents);
421
	}
422
423
	return $parents;
424
}
425
426
if (!function_exists('geodir_get_ip')) {
427
/**
428
 * Get the visitor's IP address.
429
 *
430
 * @since 1.5.7
431
 * @package GeoDirectory
432
 *
433
 * @return string The IP address.
434
 */
435
function geodir_get_ip() {
436
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
437
		//check ip from share internet
438
		$ip = $_SERVER['HTTP_CLIENT_IP'];
439
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
440
		//to check ip is pass from proxy
441
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
442
	} else {
443
		$ip = $_SERVER['REMOTE_ADDR'];
444
	}
445
	
446
	/**
447
	 * Filter the the visitor's IP address.
448
	 *
449
	 * @since 1.5.7
450
	 * @package GeoDirectory
451
	 *
452 15
	 * @param string $ip The IP address.
453 15
	 */
454
	return apply_filters('geodir_get_ip', $ip);
455
}
456
}
457
458
/**
459
 * Register die handler for gd_die()
460
 *
461
 * @since 1.5.9
462
 * @package GeoDirectory
463
 */
464
function _gd_die_handler() {
465
    if ( defined( 'GD_TESTING_MODE' ) ) {
466
        return '_gd_die_handler';
467
    } else {
468
        die();
469
    }
470
}
471 15
472 15
/**
473 15
 * Wrapper function for wp_die(). This function adds filters for wp_die() which
474 15
 * kills execution of the script using wp_die(). This allows us to then to work
475
 * with functions using gd_die() in the unit tests.
476
 *
477
 * @since 1.5.9
478
 * @package GeoDirectory
479
 * @param string $message Optional. Error message.
480
 * @param string $title   Optional. Error title.
481
 * @param int $status     Optional. Status code.
482
 */
483
function gd_die( $message = '', $title = '', $status = 400 ) {
484
    add_filter( 'wp_die_ajax_handler', '_gd_die_handler', 10, 3 );
485
    add_filter( 'wp_die_handler', '_gd_die_handler', 10, 3 );
486
    wp_die( $message, $title, array( 'response' => $status ));
487
}
488
489
/*
490
 * Matches each symbol of PHP date format standard with jQuery equivalent codeword
491
 *
492
 * @since 1.6.5
493
 * @param string $php_format The PHP date format.
494
 * @return string The jQuery format date string.
495
 */
496
function geodir_date_format_php_to_jqueryui( $php_format ) {
497
	$symbols = array(
498
		// Day
499
		'd' => 'dd',
500
		'D' => 'D',
501
		'j' => 'd',
502
		'l' => 'DD',
503
		'N' => '',
504
		'S' => '',
505
		'w' => '',
506
		'z' => 'o',
507
		// Week
508
		'W' => '',
509
		// Month
510
		'F' => 'MM',
511
		'm' => 'mm',
512
		'M' => 'M',
513
		'n' => 'm',
514
		't' => '',
515
		// Year
516
		'L' => '',
517
		'o' => '',
518
		'Y' => 'yy',
519
		'y' => 'y',
520
		// Time
521
		'a' => 'tt',
522
		'A' => 'TT',
523
		'B' => '',
524
		'g' => 'h',
525
		'G' => 'H',
526
		'h' => 'hh',
527
		'H' => 'HH',
528
		'i' => 'mm',
529
		's' => '',
530
		'u' => ''
531
	);
532
533
	$jqueryui_format = "";
534
	$escaping = false;
535
536
	for ( $i = 0; $i < strlen( $php_format ); $i++ ) {
537
		$char = $php_format[$i];
538
539
		// PHP date format escaping character
540
		if ( $char === '\\' ) {
541
			$i++;
542
543
			if ( $escaping ) {
544
				$jqueryui_format .= $php_format[$i];
545
			} else {
546
				$jqueryui_format .= '\'' . $php_format[$i];
547
			}
548
549
			$escaping = true;
550
		} else {
551
			if ( $escaping ) {
552
				$jqueryui_format .= "'";
553
				$escaping = false;
554
			}
555
556
			if ( isset( $symbols[$char] ) ) {
557
				$jqueryui_format .= $symbols[$char];
558
			} else {
559
				$jqueryui_format .= $char;
560
			}
561
		}
562
	}
563
564
	return $jqueryui_format;
565
}
566
567
/**
568
 * Maybe untranslate date string for saving to the database.
569
 *
570
 * @param string $date The date string.
571
 *
572
 * @return string The untranslated date string.
573
 * @since 1.6.5
574
 */
575
function geodir_maybe_untranslate_date($date){
576
	$english_long_months = array(
577
		'January',
578
		'February',
579
		'March',
580
		'April',
581
		'May',
582
		'June',
583
		'July',
584
		'August',
585
		'September',
586
		'October',
587
		'November',
588
		'December',
589
	);
590
591
	$non_english_long_months  = array(
592
		__('January'),
593
		__('February'),
594
		__('March'),
595
		__('April'),
596
		__('May'),
597
		__('June'),
598
		__('July'),
599
		__('August'),
600
		__('September'),
601
		__('October'),
602
		__('November'),
603
		__('December'),
604
	);
605
	$date = str_replace($non_english_long_months,$english_long_months,$date);
606
607
608
	$english_short_months = array(
609
		' Jan ',
610
		' Feb ',
611
		' Mar ',
612
		' Apr ',
613
		' May ',
614
		' Jun ',
615
		' Jul ',
616
		' Aug ',
617
		' Sep ',
618
		' Oct ',
619
		' Nov ',
620
		' Dec ',
621
	);
622
623
	$non_english_short_months = array(
624
		' '._x( 'Jan', 'January abbreviation' ).' ',
625
		' '._x( 'Feb', 'February abbreviation' ).' ',
626
		' '._x( 'Mar', 'March abbreviation' ).' ',
627
		' '._x( 'Apr', 'April abbreviation' ).' ',
628
		' '._x( 'May', 'May abbreviation' ).' ',
629
		' '._x( 'Jun', 'June abbreviation' ).' ',
630
		' '._x( 'Jul', 'July abbreviation' ).' ',
631
		' '._x( 'Aug', 'August abbreviation' ).' ',
632
		' '._x( 'Sep', 'September abbreviation' ).' ',
633
		' '._x( 'Oct', 'October abbreviation' ).' ',
634
		' '._x( 'Nov', 'November abbreviation' ).' ',
635
		' '._x( 'Dec', 'December abbreviation' ).' ',
636
	);
637
638
	$date = str_replace($non_english_short_months,$english_short_months,$date);
639
640
641
	return $date;
642
}
643
644
/**
645
 * Convert date to given format.
646
 *
647
 * @since 1.6.7
648
 *
649
 * @param string $date_input The date string.
650
 * @param string $date_to The destination date format.
651
 * @param string $date_from The source date format.
652
 * @return string The formatted date.
653
 */
654
function geodir_date($date_input, $date_to, $date_from = '') {
655
    if (empty($date_input) || empty($date_to)) {
656
        return NULL;
657
    }
658
    
659
    $date = '';
660
    if (!empty($date_from)) {
661
        $datetime = date_create_from_format($date_from, $date_input);
662
        
663
        if (!empty($datetime)) {
664
            $date = $datetime->format($date_to);
665
        }
666
    }
667
    
668
    if (empty($date)) {
669
        $date = strpos($date_input, '/') !== false ? str_replace('/', '-', $date_input) : $date_input;
670
        $date = date_i18n($date_to, strtotime($date));
671
    }
672
    
673
    $date = geodir_maybe_untranslate_date($date);
674
    /**
675
     * Filter the the date format conversion.
676
     *
677
     * @since 1.6.7
678
     * @package GeoDirectory
679
     *
680
     * @param string $date The date string.
681
     * @param string $date_input The date input.
682
     * @param string $date_to The destination date format.
683
     * @param string $date_from The source date format.
684
     */
685
    return apply_filters('geodir_date', $date, $date_input, $date_to, $date_from);
686
}
687
688
/**
689
 * Truncates the text.
690
 *
691
 * Cuts a string to the length of $length and replaces the last characters
692
 * with the ellipsis if the text is longer than length.
693
 *
694
 * @since 1.6.16
695
 * @package GeoDirectory
696
 *
697
 * @param string $text String to truncate.
698
 * @param int    $length Length of returned string, including ellipsis.
699
 * @param array  $options {
700
 *     An array of HTML attributes and options.
701
 *
702
 *     @type string $ellipsis Will be used as ending and appended to the trimmed string. Ex: "...".
703
 *     @type bool   $exact If false, $text will not be cut mid-word.
704
 *     @type bool   $html If true, HTML tags would be handled correctly.
705
 *     @type bool   $trimWidth If true, $text will be truncated with the width.
706
 * }
707
 * @return string Trimmed string.
708
 */
709
function geodir_excerpt($text, $length = 100, $options = array()) {
710
    if (!(int)$length > 0) {
711
        return $text;
712
    }
713
    $default = array(
714
        'ellipsis' => '', 'exact' => true, 'html' => true, 'trimWidth' => false,
715
	);
716
    if (!empty($options['html']) && function_exists('mb_internal_encoding') && strtolower(mb_internal_encoding()) === 'utf-8') {
717
        $default['ellipsis'] = "";
718
    }
719
    $options += $default;
720
721
    $prefix = '';
722
    $suffix = $options['ellipsis'];
723
724
    if ($options['html']) {
725
        $ellipsisLength = geodir_strlen(strip_tags($options['ellipsis']), $options);
726
727
        $truncateLength = 0;
728
        $totalLength = 0;
729
        $openTags = array();
730
        $truncate = '';
731
732
        preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
733
        foreach ($tags as $tag) {
734
            $contentLength = geodir_strlen($tag[3], $options);
735
736
            if ($truncate === '') {
737
                if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/i', $tag[2])) {
738
                    if (preg_match('/<[\w]+[^>]*>/', $tag[0])) {
739
                        array_unshift($openTags, $tag[2]);
740
                    } elseif (preg_match('/<\/([\w]+)[^>]*>/', $tag[0], $closeTag)) {
741
                        $pos = array_search($closeTag[1], $openTags);
742
                        if ($pos !== false) {
743
                            array_splice($openTags, $pos, 1);
744
                        }
745
                    }
746
                }
747
748
                $prefix .= $tag[1];
749
750
                if ($totalLength + $contentLength + $ellipsisLength > $length) {
751
                    $truncate = $tag[3];
752
                    $truncateLength = $length - $totalLength;
753
                } else {
754
                    $prefix .= $tag[3];
755
                }
756
            }
757
758
            $totalLength += $contentLength;
759
            if ($totalLength > $length) {
760
                break;
761
            }
762
        }
763
764
        if ($totalLength <= $length) {
765
            return $text;
766
        }
767
768
        $text = $truncate;
769
        $length = $truncateLength;
770
771
        foreach ($openTags as $tag) {
772
            $suffix .= '</' . $tag . '>';
773
        }
774
    } else {
775
        if (geodir_strlen($text, $options) <= $length) {
776
            return $text;
777
        }
778
        $ellipsisLength = geodir_strlen($options['ellipsis'], $options);
779
    }
780
781
    $result = geodir_substr($text, 0, $length - $ellipsisLength, $options);
782
783
    if (!$options['exact']) {
784
        if (geodir_substr($text, $length - $ellipsisLength, 1, $options) !== ' ') {
785
            $result = geodir_remove_last_word($result);
786
        }
787
788
        // Do not need to count ellipsis in the cut, if result is empty.
789
        if (!strlen($result)) {
790
            $result = geodir_substr($text, 0, $length, $options);
791
        }
792
    }
793
794
    return $prefix . $result . $suffix;
795
}
796
797
/**
798
 * Get string length.
799
 *
800
 * ### Options:
801
 *
802
 * - `html` If true, HTML entities will be handled as decoded characters.
803
 * - `trimWidth` If true, the width will return.
804
 *
805
 * @since 1.6.16
806
 * @package GeoDirectory
807
 *
808
 * @param string $text The string being checked for length
809
 * @param array  $options {
810
 *     An array of options.
811
 *
812
 *     @type bool $html If true, HTML entities will be handled as decoded characters.
813
 *     @type bool $trimWidth If true, the width will return.
814
 * }
815
 * @return int
816
 */
817
function geodir_strlen($text, array $options) {
818
    if (empty($options['trimWidth'])) {
819
        $strlen = 'geodir_utf8_strlen';
820
    } else {
821
        $strlen = 'geodir_utf8_strwidth';
822
    }
823
824
    if (empty($options['html'])) {
825
        return $strlen($text);
826
    }
827
828
    $pattern = '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i';
829
    $replace = preg_replace_callback(
830
        $pattern,
831
        function ($match) use ($strlen) {
832
            $utf8 = html_entity_decode($match[0], ENT_HTML5 | ENT_QUOTES, 'UTF-8');
833
834
            return str_repeat(' ', $strlen($utf8, 'UTF-8'));
835
        },
836
        $text
837
    );
838
839
    return $strlen($replace);
840
}
841
842
/**
843
 * Return part of a string.
844
 *
845
 * @since 1.6.16
846
 * @package GeoDirectory
847
 *
848
 * @param string $text The input string.
849
 * @param int $start The position to begin extracting.
850
 * @param int $length The desired length.
851
 * @param array  $options {
852
 *     An array of options.
853
 *
854
 *     @type bool $html If true, HTML entities will be handled as decoded characters.
855
 *     @type bool $trimWidth If true, will be truncated with specified width.
856
 * }
857
 * @return string
858
 */
859
function geodir_substr($text, $start, $length, array $options) {
860
    if (empty($options['trimWidth'])) {
861
        $substr = 'geodir_utf8_substr';
862
    } else {
863
        $substr = 'geodir_utf8_strimwidth';
864
    }
865
866
    $maxPosition = geodir_strlen($text, array('trimWidth' => false) + $options);
867
    if ($start < 0) {
868
        $start += $maxPosition;
869
        if ($start < 0) {
870
            $start = 0;
871
        }
872
    }
873
    if ($start >= $maxPosition) {
874
        return '';
875
    }
876
877
    if ($length === null) {
878
        $length = geodir_strlen($text, $options);
879
    }
880
881
    if ($length < 0) {
882
        $text = geodir_substr($text, $start, null, $options);
883
        $start = 0;
884
        $length += geodir_strlen($text, $options);
885
    }
886
887
    if ($length <= 0) {
888
        return '';
889
    }
890
891
    if (empty($options['html'])) {
892
        return (string)$substr($text, $start, $length);
893
    }
894
895
    $totalOffset = 0;
896
    $totalLength = 0;
897
    $result = '';
898
899
    $pattern = '/(&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};)/i';
900
    $parts = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
901
    foreach ($parts as $part) {
902
        $offset = 0;
903
904
        if ($totalOffset < $start) {
905
            $len = geodir_strlen($part, array('trimWidth' => false) + $options);
906
            if ($totalOffset + $len <= $start) {
907
                $totalOffset += $len;
908
                continue;
909
            }
910
911
            $offset = $start - $totalOffset;
912
            $totalOffset = $start;
913
        }
914
915
        $len = geodir_strlen($part, $options);
916
        if ($offset !== 0 || $totalLength + $len > $length) {
917
            if (strpos($part, '&') === 0 && preg_match($pattern, $part) && $part !== html_entity_decode($part, ENT_HTML5 | ENT_QUOTES, 'UTF-8') ) {
918
                // Entities cannot be passed substr.
919
                continue;
920
            }
921
922
            $part = $substr($part, $offset, $length - $totalLength);
923
            $len = geodir_strlen($part, $options);
924
        }
925
926
        $result .= $part;
927
        $totalLength += $len;
928
        if ($totalLength >= $length) {
929
            break;
930
        }
931
    }
932
933
    return $result;
934
}
935
936
/**
937
 * Removes the last word from the text.
938
 *
939
 * @since 1.6.16
940
 * @package GeoDirectory
941
 *
942
 * @param string $text The input text.
943
 * @return string
944
 */
945
function geodir_remove_last_word($text) {
946
    $spacepos = geodir_utf8_strrpos($text, ' ');
947
948
    if ($spacepos !== false) {
949
        $lastWord = geodir_utf8_strrpos($text, $spacepos);
950
951
        // Some languages are written without word separation.
952
        // We recognize a string as a word if it does not contain any full-width characters.
953
        if (geodir_utf8_strwidth($lastWord) === geodir_utf8_strlen($lastWord)) {
954
            $text = geodir_utf8_substr($text, 0, $spacepos);
955
        }
956
957
        return $text;
958
    }
959
960
    return '';
961
}
962
963
function geodir_tool_restore_cpt_from_taxonomies(){
964
965
	$cpts = get_option('geodir_post_types');
966
967
	if(!empty($cpts)){return;}
968
969
	$taxonomies = get_option('geodir_taxonomies');
970
971
	if(empty($taxonomies)){return;}
972
973
	$cpts = array();
974
975
	foreach($taxonomies as $key => $val){
976
977
		if(strpos($val['listing_slug'], '/') === false) {
978
			$cpts[$val['object_type']] = array('cpt'=>$val['object_type'],'slug'=>$val['listing_slug']);
979
		}
980
981
	}
982
983
	if(empty($cpts)){return;}
984
985
986
	$cpts_restore = $cpts;
987
988
	foreach($cpts as $cpt){
989
990
991
		$is_custom = $cpt['cpt']=='gd_place' ? 0 : 1;
992
993
		$cpts_restore[$cpt['cpt']] = array (
994
				'labels' =>
995
					array (
996
						'name' => $cpt['slug'],
997
						'singular_name' => $cpt['slug'],
998
						'add_new' => 'Add New',
999
						'add_new_item' => 'Add New '.$cpt['slug'],
1000
						'edit_item' => 'Edit '.$cpt['slug'],
1001
						'new_item' => 'New '.$cpt['slug'],
1002
						'view_item' => 'View '.$cpt['slug'],
1003
						'search_items' => 'Search '.$cpt['slug'],
1004
						'not_found' => 'No '.$cpt['slug'].' Found',
1005
						'not_found_in_trash' => 'No '.$cpt['slug'].' Found In Trash',
1006
						'label_post_profile' => '',
1007
						'label_post_info' => '',
1008
						'label_post_images' => '',
1009
						'label_post_map' => '',
1010
						'label_reviews' => '',
1011
						'label_related_listing' => '',
1012
					),
1013
				'can_export' => true,
1014
				'capability_type' => 'post',
1015
				'description' => '',
1016
				'has_archive' => $cpt['slug'],
1017
				'hierarchical' => false,
1018
				'map_meta_cap' => true,
1019
				'menu_icon' => '',
1020
				'public' => true,
1021
				'query_var' => true,
1022
				'rewrite' =>
1023
					array (
1024
						'slug' => $cpt['slug'],
1025
						'with_front' => false,
1026
						'hierarchical' => true,
1027
						'feeds' => true,
1028
					),
1029
				'supports' =>
1030
					array (
1031
						0 => 'title',
1032
						1 => 'editor',
1033
						2 => 'author',
1034
						3 => 'thumbnail',
1035
						4 => 'excerpt',
1036
						5 => 'custom-fields',
1037
						6 => 'comments',
1038
					),
1039
				'taxonomies' =>
1040
					array (
1041
						0 => $cpt['cpt'].'category',
1042
						1 => $cpt['cpt'].'_tags',
1043
					),
1044
				'is_custom' => $is_custom,
1045
				'listing_order' => '1',
1046
				'seo' =>
1047
					array (
1048
						'meta_keyword' => '',
1049
						'meta_description' => '',
1050
					),
1051
				'show_in_nav_menus' => 1,
1052
				'link_business' => 0,
1053
				'linkable_to' => '',
1054
				'linkable_from' => '',
1055
			);
1056
	}
1057
1058
1059
	update_option('geodir_post_types',$cpts_restore);
1060
1061
}
1062
1063
/**
1064
 * Get truncated string with specified width.
1065
 *
1066
 * @since 1.6.18
1067
 * @package Geodirectory
1068
 *
1069
 * @param string $str The string being decoded.
1070
 * @param int $start The start position offset. Number of characters from the beginning of string.
1071
 *                      For negative value, number of characters from the end of the string.
1072
 * @param int $width The width of the desired trim. Negative widths count from the end of the string.
1073
 * @param string $trimmaker A string that is added to the end of string when string is truncated. Ex: "...".
1074
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1075
 * @return string
1076
 */
1077
function geodir_utf8_strimwidth( $str, $start, $width, $trimmaker = '', $encoding = 'UTF-8' ) {
1078
    if ( function_exists( 'mb_strimwidth' ) ) {
1079
        return mb_strimwidth( $str, $start, $width, $trimmaker, $encoding );
1080
    }
1081
    
1082
    return geodir_utf8_substr( $str, $start, $width, $encoding ) . $trimmaker;
1083
}
1084
1085
/**
1086
 * Get the string length.
1087
 *
1088
 * @since 1.6.18
1089
 * @package Geodirectory
1090
 *
1091
 * @param string $str The string being checked for length. 
1092
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1093
 * @return int Returns the number of characters in string.
1094
 */
1095
function geodir_utf8_strlen( $str, $encoding = 'UTF-8' ) {
1096
    if ( function_exists( 'mb_strlen' ) ) {
1097
        return mb_strlen( $str, $encoding );
1098
    }
1099
        
1100
    return strlen( $str );
1101
}
1102
1103
/**
1104
 * Find position of first occurrence of string in a string
1105
 *
1106
 * @since 1.6.18
1107
 * @package Geodirectory
1108
 *
1109
 * @param string $str The string being checked.
1110
 * @param string $find The string to find in input string.
1111
 * @param int $offset The search offset. Default "0". A negative offset counts from the end of the string.
1112
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1113
 * @return int Returns the position of the first occurrence of search in the string.
1114
 */
1115
function geodir_utf8_strpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
1116
    if ( function_exists( 'mb_strpos' ) ) {
1117
        return mb_strpos( $str, $find, $offset, $encoding );
1118
    }
1119
        
1120
    return strpos( $str, $find, $offset );
1121
}
1122
1123
/**
1124
 * Find position of last occurrence of a string in a string.
1125
 *
1126
 * @since 1.6.18
1127
 * @package Geodirectory
1128
 *
1129
 * @param string $str The string being checked, for the last occurrence of search.
1130
 * @param string $find The string to find in input string.
1131
 * @param int $offset Specifies begin searching an arbitrary number of characters into the string.
1132
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1133
 * @return int Returns the position of the last occurrence of search.
1134
 */
1135
function geodir_utf8_strrpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
1136
    if ( function_exists( 'mb_strrpos' ) ) {
1137
        return mb_strrpos( $str, $find, $offset, $encoding );
1138
    }
1139
        
1140
    return strrpos( $str, $find, $offset );
1141
}
1142
1143
/**
1144
 * Get the part of string.
1145
 *
1146
 * @since 1.6.18
1147
 * @package Geodirectory
1148
 *
1149
 * @param string $str The string to extract the substring from.
1150
 * @param int $start If start is non-negative, the returned string will start at the entered position in string, counting from zero.
1151
 *                      If start is negative, the returned string will start at the entered position from the end of string. 
1152
 * @param int|null $length Maximum number of characters to use from string.
1153
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1154
 * @return string
1155
 */
1156
function geodir_utf8_substr( $str, $start, $length = null, $encoding = 'UTF-8' ) {
1157
    if ( function_exists( 'mb_substr' ) ) {
1158
        if ( $length === null ) {
1159
            return mb_substr( $str, $start, geodir_utf8_strlen( $str, $encoding ), $encoding );
1160
        } else {
1161
            return mb_substr( $str, $start, $length, $encoding );
1162
        }
1163
    }
1164
        
1165
    return substr( $str, $start, $length );
1166
}
1167
1168
/**
1169
 * Get the width of string.
1170
 *
1171
 * @since 1.6.18
1172
 * @package Geodirectory
1173
 *
1174
 * @param string $str The string being decoded.
1175
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1176
 * @return string The width of string.
1177
 */
1178
function geodir_utf8_strwidth( $str, $encoding = 'UTF-8' ) {
1179
	if ( function_exists( 'mb_strwidth' ) ) {
1180
		return mb_strwidth( $str, $encoding );
1181
	}
1182
1183
	return geodir_utf8_strlen( $str, $encoding );
1184
}
1185
1186
/**
1187
 * Get a string with the first character of string capitalized.
1188
 *
1189
 * @since 1.6.18
1190
 * @package Geodirectory
1191
 *
1192
 * @param string $str The input string.
1193
 * @param bool $lower_str_end If true it returns string lowercased except first character.
1194
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1195
 * @return string The resulting string.
1196
 */
1197
function geodir_utf8_ucfirst( $str, $lower_str_end = false, $encoding = 'UTF-8' ) {
1198
    if ( function_exists( 'mb_strlen' ) ) {
1199
        $first_letter = geodir_strtoupper( geodir_utf8_substr( $str, 0, 1, $encoding ), $encoding );
1200
        $str_end = "";
0 ignored issues
show
Unused Code introduced by
$str_end 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...
1201
        
1202
        if ( $lower_str_end ) {
1203
            $str_end = geodir_strtolower( geodir_utf8_substr( $str, 1, geodir_utf8_strlen( $str, $encoding ), $encoding ), $encoding );
1204
        } else {
1205
            $str_end = geodir_utf8_substr( $str, 1, geodir_utf8_strlen( $str, $encoding ), $encoding );
1206
        }
1207
        
1208
        return $first_letter . $str_end;
1209
    }
1210
1211
    return ucfirst( $str );
1212
}
1213
1214
function geodir_total_listings_count($post_type = false)
1215
{
1216
	global $wpdb;
1217
1218
	$count = 0;
1219
	
1220
	if ($post_type) {
1221
		$count = $count + $wpdb->get_var("select count(post_id) from " . $wpdb->prefix . "geodir_" . $post_type . "_detail");
1222
	} else {
1223
		$all_postypes = geodir_get_posttypes();
1224
1225
		if (!empty($all_postypes)) {
1226
			foreach ($all_postypes as $key) {
0 ignored issues
show
Bug introduced by
The expression $all_postypes 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...
1227
				$count = $count + $wpdb->get_var("select count(post_id) from " . $wpdb->prefix . "geodir_" . $key . "_detail");
1228
			}
1229
		}	
1230
	}
1231
1232
	return $count;
1233
}
1234
1235
function geodir_get_diagnose_step_max_items() {
1236
	return 5;
1237
}