Test Failed
Pull Request — master (#421)
by Kiran
17:15
created

helper_functions.php ➔ geodir_date()   D

Complexity

Conditions 9
Paths 19

Size

Total Lines 40
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 16
nc 19
nop 4
dl 0
loc 40
ccs 0
cts 0
cp 0
crap 90
rs 4.909
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 (geodir_is_wpml()) {
20
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
37
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
54
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
71
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
88
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
105
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
122
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
140
        $gd_page_id =  geodir_wpml_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 (geodir_is_wpml()) {
196
        $gd_page_id =  geodir_wpml_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
 * @since 1.6.22 Genitive month added.
575
 */
576
function geodir_maybe_untranslate_date($date) {
577
	global $wp_locale;
578
    
579
	$english_long_months = array(
580
		'January',
581
		'February',
582
		'March',
583
		'April',
584
		'May',
585
		'June',
586
		'July',
587
		'August',
588
		'September',
589
		'October',
590
		'November',
591
		'December',
592
	);
593
594
	$non_english_long_months  = array(
595
		__('January'),
596
		__('February'),
597
		__('March'),
598
		__('April'),
599
		__('May'),
600
		__('June'),
601
		__('July'),
602
		__('August'),
603
		__('September'),
604
		__('October'),
605
		__('November'),
606
		__('December'),
607
	);
608
	$date = str_replace($non_english_long_months,$english_long_months,$date);
609
    
610
	if ( !empty( $wp_locale ) ) {
611
		$date = str_replace( array_values( $wp_locale->month_genitive ), $english_long_months, $date );
612
	}
613
614
	$english_short_months = array(
615
		' Jan ',
616
		' Feb ',
617
		' Mar ',
618
		' Apr ',
619
		' May ',
620
		' Jun ',
621
		' Jul ',
622
		' Aug ',
623
		' Sep ',
624
		' Oct ',
625
		' Nov ',
626
		' Dec ',
627
	);
628
629
	$non_english_short_months = array(
630
		' '._x( 'Jan', 'January abbreviation' ).' ',
631
		' '._x( 'Feb', 'February abbreviation' ).' ',
632
		' '._x( 'Mar', 'March abbreviation' ).' ',
633
		' '._x( 'Apr', 'April abbreviation' ).' ',
634
		' '._x( 'May', 'May abbreviation' ).' ',
635
		' '._x( 'Jun', 'June abbreviation' ).' ',
636
		' '._x( 'Jul', 'July abbreviation' ).' ',
637
		' '._x( 'Aug', 'August abbreviation' ).' ',
638
		' '._x( 'Sep', 'September abbreviation' ).' ',
639
		' '._x( 'Oct', 'October abbreviation' ).' ',
640
		' '._x( 'Nov', 'November abbreviation' ).' ',
641
		' '._x( 'Dec', 'December abbreviation' ).' ',
642
	);
643
644
	$date = str_replace($non_english_short_months,$english_short_months,$date);
645
646
647
	return $date;
648
}
649
650
/**
651
 * Convert date to given format.
652
 *
653
 * @since 1.6.7
654
 * @since 1.6.22 $locale parameter added to fix already translated dates.
655
 *
656
 * @param string $date_input The date string.
657
 * @param string $date_to The destination date format.
658
 * @param string $date_from The source date format.
659
 * @param bool $locale True to retrieve the date in localized format. Default false.
660
 * @return string The formatted date.
661
 */
662
function geodir_date( $date_input, $date_to, $date_from = '', $locale = false ) {
663
    if ( empty( $date_input ) || empty( $date_to ) ) {
664
        return NULL;
665
    }
666
    
667
    $date_input = geodir_maybe_untranslate_date( $date_input );
668
    
669
    $timestamp = 0;
670
    if (!empty( $date_from ) && function_exists( 'date_create_from_format' ) ) {
671
        $datetime = date_create_from_format( $date_from, $date_input );
672
        if ( !empty( $datetime ) ) {
673
            $timestamp = $datetime->getTimestamp();
674
        }
675
    }
676
    
677
    if ( empty( $timestamp ) ) {
678
        $date = strpos( $date_input, '/' ) !== false ? str_replace( '/', '-', $date_input ) : $date_input;
679
        $timestamp = strtotime( $date );
680
    }
681
    
682
    $date = date_i18n( $date_to, $timestamp );
683
    
684
    if ( !$locale ) {
685
        $date = geodir_maybe_untranslate_date( $date );
686
    }
687
    
688
    /**
689
     * Filter the the date format conversion.
690
     *
691
     * @since 1.6.7
692
     * @package GeoDirectory
693
     *
694
     * @param string $date The date string.
695
     * @param string $date_input The date input.
696
     * @param string $date_to The destination date format.
697
     * @param string $date_from The source date format.
698
     * @param bool $locale True to retrieve the date in localized format.
699
     */
700
    return apply_filters( 'geodir_date', $date, $date_input, $date_to, $date_from, $locale );
701
}
702
703
/**
704
 * Truncates the text.
705
 *
706
 * Cuts a string to the length of $length and replaces the last characters
707
 * with the ellipsis if the text is longer than length.
708
 *
709
 * @since 1.6.16
710
 * @package GeoDirectory
711
 *
712
 * @param string $text String to truncate.
713
 * @param int    $length Length of returned string, including ellipsis.
714
 * @param array  $options {
715
 *     An array of HTML attributes and options.
716
 *
717
 *     @type string $ellipsis Will be used as ending and appended to the trimmed string. Ex: "...".
718
 *     @type bool   $exact If false, $text will not be cut mid-word.
719
 *     @type bool   $html If true, HTML tags would be handled correctly.
720
 *     @type bool   $trimWidth If true, $text will be truncated with the width.
721
 * }
722
 * @return string Trimmed string.
723
 */
724
function geodir_excerpt($text, $length = 100, $options = array()) {
725
    if (!(int)$length > 0) {
726
        return $text;
727
    }
728
    $default = array(
729
        'ellipsis' => '', 'exact' => true, 'html' => true, 'trimWidth' => false,
730
	);
731
    if (!empty($options['html']) && function_exists('mb_internal_encoding') && strtolower(mb_internal_encoding()) === 'utf-8') {
732
        $default['ellipsis'] = "";
733
    }
734
    $options += $default;
735
736
    $prefix = '';
737
    $suffix = $options['ellipsis'];
738
739
    if ($options['html']) {
740
        $ellipsisLength = geodir_strlen(strip_tags($options['ellipsis']), $options);
741
742
        $truncateLength = 0;
743
        $totalLength = 0;
744
        $openTags = array();
745
        $truncate = '';
746
747
        preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
748
        foreach ($tags as $tag) {
749
            $contentLength = geodir_strlen($tag[3], $options);
750
751
            if ($truncate === '') {
752
                if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/i', $tag[2])) {
753
                    if (preg_match('/<[\w]+[^>]*>/', $tag[0])) {
754
                        array_unshift($openTags, $tag[2]);
755
                    } elseif (preg_match('/<\/([\w]+)[^>]*>/', $tag[0], $closeTag)) {
756
                        $pos = array_search($closeTag[1], $openTags);
757
                        if ($pos !== false) {
758
                            array_splice($openTags, $pos, 1);
759
                        }
760
                    }
761
                }
762
763
                $prefix .= $tag[1];
764
765
                if ($totalLength + $contentLength + $ellipsisLength > $length) {
766
                    $truncate = $tag[3];
767
                    $truncateLength = $length - $totalLength;
768
                } else {
769
                    $prefix .= $tag[3];
770
                }
771
            }
772
773
            $totalLength += $contentLength;
774
            if ($totalLength > $length) {
775
                break;
776
            }
777
        }
778
779
        if ($totalLength <= $length) {
780
            return $text;
781
        }
782
783
        $text = $truncate;
784
        $length = $truncateLength;
785
786
        foreach ($openTags as $tag) {
787
            $suffix .= '</' . $tag . '>';
788
        }
789
    } else {
790
        if (geodir_strlen($text, $options) <= $length) {
791
            return $text;
792
        }
793
        $ellipsisLength = geodir_strlen($options['ellipsis'], $options);
794
    }
795
796
    $result = geodir_substr($text, 0, $length - $ellipsisLength, $options);
797
798
    if (!$options['exact']) {
799
        if (geodir_substr($text, $length - $ellipsisLength, 1, $options) !== ' ') {
800
            $result = geodir_remove_last_word($result);
801
        }
802
803
        // Do not need to count ellipsis in the cut, if result is empty.
804
        if (!strlen($result)) {
805
            $result = geodir_substr($text, 0, $length, $options);
806
        }
807
    }
808
809
    return $prefix . $result . $suffix;
810
}
811
812
/**
813
 * Get string length.
814
 *
815
 * ### Options:
816
 *
817
 * - `html` If true, HTML entities will be handled as decoded characters.
818
 * - `trimWidth` If true, the width will return.
819
 *
820
 * @since 1.6.16
821
 * @package GeoDirectory
822
 *
823
 * @param string $text The string being checked for length
824
 * @param array  $options {
825
 *     An array of options.
826
 *
827
 *     @type bool $html If true, HTML entities will be handled as decoded characters.
828
 *     @type bool $trimWidth If true, the width will return.
829
 * }
830
 * @return int
831
 */
832
function geodir_strlen($text, array $options) {
833
    if (empty($options['trimWidth'])) {
834
        $strlen = 'geodir_utf8_strlen';
835
    } else {
836
        $strlen = 'geodir_utf8_strwidth';
837
    }
838
839
    if (empty($options['html'])) {
840
        return $strlen($text);
841
    }
842
843
    $pattern = '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i';
844
    $replace = preg_replace_callback(
845
        $pattern,
846
        function ($match) use ($strlen) {
847
            $utf8 = html_entity_decode($match[0], ENT_HTML5 | ENT_QUOTES, 'UTF-8');
848
849
            return str_repeat(' ', $strlen($utf8, 'UTF-8'));
850
        },
851
        $text
852
    );
853
854
    return $strlen($replace);
855
}
856
857
/**
858
 * Return part of a string.
859
 *
860
 * @since 1.6.16
861
 * @package GeoDirectory
862
 *
863
 * @param string $text The input string.
864
 * @param int $start The position to begin extracting.
865
 * @param int $length The desired length.
866
 * @param array  $options {
867
 *     An array of options.
868
 *
869
 *     @type bool $html If true, HTML entities will be handled as decoded characters.
870
 *     @type bool $trimWidth If true, will be truncated with specified width.
871
 * }
872
 * @return string
873
 */
874
function geodir_substr($text, $start, $length, array $options) {
875
    if (empty($options['trimWidth'])) {
876
        $substr = 'geodir_utf8_substr';
877
    } else {
878
        $substr = 'geodir_utf8_strimwidth';
879
    }
880
881
    $maxPosition = geodir_strlen($text, array('trimWidth' => false) + $options);
882
    if ($start < 0) {
883
        $start += $maxPosition;
884
        if ($start < 0) {
885
            $start = 0;
886
        }
887
    }
888
    if ($start >= $maxPosition) {
889
        return '';
890
    }
891
892
    if ($length === null) {
893
        $length = geodir_strlen($text, $options);
894
    }
895
896
    if ($length < 0) {
897
        $text = geodir_substr($text, $start, null, $options);
898
        $start = 0;
899
        $length += geodir_strlen($text, $options);
900
    }
901
902
    if ($length <= 0) {
903
        return '';
904
    }
905
906
    if (empty($options['html'])) {
907
        return (string)$substr($text, $start, $length);
908
    }
909
910
    $totalOffset = 0;
911
    $totalLength = 0;
912
    $result = '';
913
914
    $pattern = '/(&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};)/i';
915
    $parts = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
916
    foreach ($parts as $part) {
917
        $offset = 0;
918
919
        if ($totalOffset < $start) {
920
            $len = geodir_strlen($part, array('trimWidth' => false) + $options);
921
            if ($totalOffset + $len <= $start) {
922
                $totalOffset += $len;
923
                continue;
924
            }
925
926
            $offset = $start - $totalOffset;
927
            $totalOffset = $start;
928
        }
929
930
        $len = geodir_strlen($part, $options);
931
        if ($offset !== 0 || $totalLength + $len > $length) {
932
            if (strpos($part, '&') === 0 && preg_match($pattern, $part) && $part !== html_entity_decode($part, ENT_HTML5 | ENT_QUOTES, 'UTF-8') ) {
933
                // Entities cannot be passed substr.
934
                continue;
935
            }
936
937
            $part = $substr($part, $offset, $length - $totalLength);
938
            $len = geodir_strlen($part, $options);
939
        }
940
941
        $result .= $part;
942
        $totalLength += $len;
943
        if ($totalLength >= $length) {
944
            break;
945
        }
946
    }
947
948
    return $result;
949
}
950
951
/**
952
 * Removes the last word from the text.
953
 *
954
 * @since 1.6.16
955
 * @package GeoDirectory
956
 *
957
 * @param string $text The input text.
958
 * @return string
959
 */
960
function geodir_remove_last_word($text) {
961
    $spacepos = geodir_utf8_strrpos($text, ' ');
962
963
    if ($spacepos !== false) {
964
        $lastWord = geodir_utf8_strrpos($text, $spacepos);
965
966
        // Some languages are written without word separation.
967
        // We recognize a string as a word if it does not contain any full-width characters.
968
        if (geodir_utf8_strwidth($lastWord) === geodir_utf8_strlen($lastWord)) {
969
            $text = geodir_utf8_substr($text, 0, $spacepos);
970
        }
971
972
        return $text;
973
    }
974
975
    return '';
976
}
977
978
function geodir_tool_restore_cpt_from_taxonomies(){
979
980
	$cpts = get_option('geodir_post_types');
981
982
	if(!empty($cpts)){return;}
983
984
	$taxonomies = get_option('geodir_taxonomies');
985
986
	if(empty($taxonomies)){return;}
987
988
	$cpts = array();
989
990
	foreach($taxonomies as $key => $val){
991
992
		if(strpos($val['listing_slug'], '/') === false) {
993
			$cpts[$val['object_type']] = array('cpt'=>$val['object_type'],'slug'=>$val['listing_slug']);
994
		}
995
996
	}
997
998
	if(empty($cpts)){return;}
999
1000
1001
	$cpts_restore = $cpts;
1002
1003
	foreach($cpts as $cpt){
1004
1005
1006
		$is_custom = $cpt['cpt']=='gd_place' ? 0 : 1;
1007
1008
		$cpts_restore[$cpt['cpt']] = array (
1009
				'labels' =>
1010
					array (
1011
						'name' => $cpt['slug'],
1012
						'singular_name' => $cpt['slug'],
1013
						'add_new' => 'Add New',
1014
						'add_new_item' => 'Add New '.$cpt['slug'],
1015
						'edit_item' => 'Edit '.$cpt['slug'],
1016
						'new_item' => 'New '.$cpt['slug'],
1017
						'view_item' => 'View '.$cpt['slug'],
1018
						'search_items' => 'Search '.$cpt['slug'],
1019
						'not_found' => 'No '.$cpt['slug'].' Found',
1020
						'not_found_in_trash' => 'No '.$cpt['slug'].' Found In Trash',
1021
						'label_post_profile' => '',
1022
						'label_post_info' => '',
1023
						'label_post_images' => '',
1024
						'label_post_map' => '',
1025
						'label_reviews' => '',
1026
						'label_related_listing' => '',
1027
					),
1028
				'can_export' => true,
1029
				'capability_type' => 'post',
1030
				'description' => '',
1031
				'has_archive' => $cpt['slug'],
1032
				'hierarchical' => false,
1033
				'map_meta_cap' => true,
1034
				'menu_icon' => '',
1035
				'public' => true,
1036
				'query_var' => true,
1037
				'rewrite' =>
1038
					array (
1039
						'slug' => $cpt['slug'],
1040
						'with_front' => false,
1041
						'hierarchical' => true,
1042
						'feeds' => true,
1043
					),
1044
				'supports' =>
1045
					array (
1046
						0 => 'title',
1047
						1 => 'editor',
1048
						2 => 'author',
1049
						3 => 'thumbnail',
1050
						4 => 'excerpt',
1051
						5 => 'custom-fields',
1052
						6 => 'comments',
1053
					),
1054
				'taxonomies' =>
1055
					array (
1056
						0 => $cpt['cpt'].'category',
1057
						1 => $cpt['cpt'].'_tags',
1058
					),
1059
				'is_custom' => $is_custom,
1060
				'listing_order' => '1',
1061
				'seo' =>
1062
					array (
1063
						'meta_keyword' => '',
1064
						'meta_description' => '',
1065
					),
1066
				'show_in_nav_menus' => 1,
1067
				'link_business' => 0,
1068
				'linkable_to' => '',
1069
				'linkable_from' => '',
1070
			);
1071
	}
1072
1073
1074
	update_option('geodir_post_types',$cpts_restore);
1075
1076
}
1077
1078
/**
1079
 * Get truncated string with specified width.
1080
 *
1081
 * @since 1.6.18
1082
 * @package Geodirectory
1083
 *
1084
 * @param string $str The string being decoded.
1085
 * @param int $start The start position offset. Number of characters from the beginning of string.
1086
 *                      For negative value, number of characters from the end of the string.
1087
 * @param int $width The width of the desired trim. Negative widths count from the end of the string.
1088
 * @param string $trimmaker A string that is added to the end of string when string is truncated. Ex: "...".
1089
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1090
 * @return string
1091
 */
1092
function geodir_utf8_strimwidth( $str, $start, $width, $trimmaker = '', $encoding = 'UTF-8' ) {
1093
    if ( function_exists( 'mb_strimwidth' ) ) {
1094
        return mb_strimwidth( $str, $start, $width, $trimmaker, $encoding );
1095
    }
1096
    
1097
    return geodir_utf8_substr( $str, $start, $width, $encoding ) . $trimmaker;
1098
}
1099
1100
/**
1101
 * Get the string length.
1102
 *
1103
 * @since 1.6.18
1104
 * @package Geodirectory
1105
 *
1106
 * @param string $str The string being checked for length. 
1107
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1108
 * @return int Returns the number of characters in string.
1109
 */
1110
function geodir_utf8_strlen( $str, $encoding = 'UTF-8' ) {
1111
    if ( function_exists( 'mb_strlen' ) ) {
1112
        return mb_strlen( $str, $encoding );
1113
    }
1114
        
1115
    return strlen( $str );
1116
}
1117
1118
/**
1119
 * Find position of first occurrence of string in a string
1120
 *
1121
 * @since 1.6.18
1122
 * @package Geodirectory
1123
 *
1124
 * @param string $str The string being checked.
1125
 * @param string $find The string to find in input string.
1126
 * @param int $offset The search offset. Default "0". A negative offset counts from the end of the string.
1127
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1128
 * @return int Returns the position of the first occurrence of search in the string.
1129
 */
1130
function geodir_utf8_strpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
1131
    if ( function_exists( 'mb_strpos' ) ) {
1132
        return mb_strpos( $str, $find, $offset, $encoding );
1133
    }
1134
        
1135
    return strpos( $str, $find, $offset );
1136
}
1137
1138
/**
1139
 * Find position of last occurrence of a string in a string.
1140
 *
1141
 * @since 1.6.18
1142
 * @package Geodirectory
1143
 *
1144
 * @param string $str The string being checked, for the last occurrence of search.
1145
 * @param string $find The string to find in input string.
1146
 * @param int $offset Specifies begin searching an arbitrary number of characters into the string.
1147
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1148
 * @return int Returns the position of the last occurrence of search.
1149
 */
1150
function geodir_utf8_strrpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
1151
    if ( function_exists( 'mb_strrpos' ) ) {
1152
        return mb_strrpos( $str, $find, $offset, $encoding );
1153
    }
1154
        
1155
    return strrpos( $str, $find, $offset );
1156
}
1157
1158
/**
1159
 * Get the part of string.
1160
 *
1161
 * @since 1.6.18
1162
 * @package Geodirectory
1163
 *
1164
 * @param string $str The string to extract the substring from.
1165
 * @param int $start If start is non-negative, the returned string will start at the entered position in string, counting from zero.
1166
 *                      If start is negative, the returned string will start at the entered position from the end of string. 
1167
 * @param int|null $length Maximum number of characters to use from string.
1168
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1169
 * @return string
1170
 */
1171
function geodir_utf8_substr( $str, $start, $length = null, $encoding = 'UTF-8' ) {
1172
    if ( function_exists( 'mb_substr' ) ) {
1173
        if ( $length === null ) {
1174
            return mb_substr( $str, $start, geodir_utf8_strlen( $str, $encoding ), $encoding );
1175
        } else {
1176
            return mb_substr( $str, $start, $length, $encoding );
1177
        }
1178
    }
1179
        
1180
    return substr( $str, $start, $length );
1181
}
1182
1183
/**
1184
 * Get the width of string.
1185
 *
1186
 * @since 1.6.18
1187
 * @package Geodirectory
1188
 *
1189
 * @param string $str The string being decoded.
1190
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1191
 * @return string The width of string.
1192
 */
1193
function geodir_utf8_strwidth( $str, $encoding = 'UTF-8' ) {
1194
	if ( function_exists( 'mb_strwidth' ) ) {
1195
		return mb_strwidth( $str, $encoding );
1196
	}
1197
1198
	return geodir_utf8_strlen( $str, $encoding );
1199
}
1200
1201
/**
1202
 * Get a string with the first character of string capitalized.
1203
 *
1204
 * @since 1.6.18
1205
 * @package Geodirectory
1206
 *
1207
 * @param string $str The input string.
1208
 * @param bool $lower_str_end If true it returns string lowercased except first character.
1209
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
1210
 * @return string The resulting string.
1211
 */
1212
function geodir_utf8_ucfirst( $str, $lower_str_end = false, $encoding = 'UTF-8' ) {
1213
    if ( function_exists( 'mb_strlen' ) ) {
1214
        $first_letter = geodir_strtoupper( geodir_utf8_substr( $str, 0, 1, $encoding ), $encoding );
1215
        $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...
1216
        
1217
        if ( $lower_str_end ) {
1218
            $str_end = geodir_strtolower( geodir_utf8_substr( $str, 1, geodir_utf8_strlen( $str, $encoding ), $encoding ), $encoding );
1219
        } else {
1220
            $str_end = geodir_utf8_substr( $str, 1, geodir_utf8_strlen( $str, $encoding ), $encoding );
1221
        }
1222
        
1223
        return $first_letter . $str_end;
1224
    }
1225
1226
    return ucfirst( $str );
1227
}
1228
1229
function geodir_total_listings_count($post_type = false)
1230
{
1231
	global $wpdb;
1232
1233
	$count = 0;
1234
	
1235
	if ($post_type) {
1236
		$count = $count + $wpdb->get_var("select count(post_id) from " . $wpdb->prefix . "geodir_" . $post_type . "_detail");
1237
	} else {
1238
		$all_postypes = geodir_get_posttypes();
1239
1240
		if (!empty($all_postypes)) {
1241
			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...
1242
				$count = $count + $wpdb->get_var("select count(post_id) from " . $wpdb->prefix . "geodir_" . $key . "_detail");
1243
			}
1244
		}	
1245
	}
1246
1247
	return $count;
1248
}
1249
1250
function geodir_get_diagnose_step_max_items() {
1251
	return 5;
1252
}