Completed
Pull Request — trunk (#848)
by
unknown
06:06
created

CMB2_Utils::url()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 16
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * CMB2 Utilities
4
 *
5
 * @since  1.1.0
6
 *
7
 * @category  WordPress_Plugin
8
 * @package   CMB2
9
 * @author    WebDevStudios
10
 * @license   GPL-2.0+
11
 * @link      http://webdevstudios.com
12
 */
13
class CMB2_Utils {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
14
15
	/**
16
	 * The WordPress ABSPATH constant.
17
	 * @var   string
18
	 * @since 2.2.3
19
	 */
20
	protected static $ABSPATH = ABSPATH;
21
22
	/**
23
	 * The url which is used to load local resources.
24
	 * @var   string
25
	 * @since 2.0.0
26
	 */
27
	protected static $url = '';
28
29
	/**
30
	 * Utility method that attempts to get an attachment's ID by it's url
31
	 * @since  1.0.0
32
	 * @param  string  $img_url Attachment url
33
	 * @return int|false            Attachment ID or false
34
	 */
35 1
	public static function image_id_from_url( $img_url ) {
36 1
		$attachment_id = 0;
37 1
		$dir = wp_upload_dir();
38
39
		// Is URL in uploads directory?
40 1
		if ( false === strpos( $img_url, $dir['baseurl'] . '/' ) ) {
41
			return false;
42
		}
43
44 1
		$file = basename( $img_url );
45
46
		$query_args = array(
47 1
			'post_type'   => 'attachment',
48 1
			'post_status' => 'inherit',
49 1
			'fields'      => 'ids',
50
			'meta_query'  => array(
51
				array(
52 1
					'value'   => $file,
53 1
					'compare' => 'LIKE',
54 1
					'key'     => '_wp_attachment_metadata',
55 1
				),
56
			)
57 1
		);
58
59 1
		$query = new WP_Query( $query_args );
60
61 1
		if ( $query->have_posts() ) {
62
63 1
			foreach ( $query->posts as $post_id ) {
64 1
				$meta = wp_get_attachment_metadata( $post_id );
65 1
				$original_file       = basename( $meta['file'] );
66 1
				$cropped_image_files = isset( $meta['sizes'] ) ? wp_list_pluck( $meta['sizes'], 'file' ) : array();
67 1
				if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
68 1
					$attachment_id = $post_id;
69 1
					break;
70
				}
71 1
			}
72
73 1
		}
74
75 1
		return 0 === $attachment_id ? false : $attachment_id;
76
	}
77
78
	/**
79
	 * Utility method to get a combined list of default and custom registered image sizes
80
	 * @since  2.x.x.x
81
	 * @link   http://core.trac.wordpress.org/ticket/18947
82
	 * @global array $_wp_additional_image_sizes
83
	 * @return array $image_sizes The image sizes
84
	 */
85 6
	static function get_available_image_sizes() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
86 6
		global $_wp_additional_image_sizes;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
87
88 6
		$default_image_sizes = array( 'thumbnail', 'medium', 'large' );
89 6
		foreach ( $default_image_sizes as $size ) {
90 6
			$image_sizes[ $size ] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$image_sizes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $image_sizes = 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...
91 6
				'height' => intval( get_option( "{$size}_size_h" ) ),
92 6
				'width'  => intval( get_option( "{$size}_size_w" ) ),
93 6
				'crop'   => get_option( "{$size}_crop" ) ? get_option( "{$size}_crop" ) : false,
94
			);
95 6
		}
96
97 6
		if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) {
98 6
			$image_sizes = array_merge( $image_sizes, $_wp_additional_image_sizes );
0 ignored issues
show
Bug introduced by
The variable $image_sizes 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...
99 6
		}
100
101 6
		return $image_sizes;
102
	}
103
104
	/**
105
	 * Utility method to return the closest named size from an array of values
106
	 *
107
	 * Based off of WordPress's image_get_intermediate_size()
108
	 * If the size matches an existing size then it will be used. If there is no
109
	 * direct match, then the nearest image size larger than the specified size
110
	 * will be used. If nothing is found, then the function will return false.
111
	 * Uses get_available_image_sizes() to get all available sizes.
112
	 *
113
	 * @since  2.x.x.x
114
	 * @param  array|string $size Image size. Accepts an array of width and height (in that order)
115
	 * @return false|string $data Named image size e.g. 'thumbnail'
116
	 */
117 6
	public static function get_named_size( $size ) {
118 6
		$data = array();
119
120
		// Find the best match when '$size' is an array.
121 6
		if ( is_array( $size ) ) {
122 6
			$image_sizes = self::get_available_image_sizes();
123 6
			$candidates = array();
124
125 6
			foreach ( $image_sizes as $_size => $data ) {
126
127
				// If there's an exact match to an existing image size, short circuit.
128 6
				if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
129
					$candidates[ $data['width'] * $data['height'] ] = array( $_size, $data );
130
					break;
131
				}
132
133
				// If it's not an exact match, consider larger sizes with the same aspect ratio.
134 6
				if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
135
					
136
					/*
137
					 * To test for varying crops, we constrain the dimensions of the larger image
138
					 * to the dimensions of the smaller image and see if they match.
139
					 */
140 6
					if ( $data['width'] > $size[0] ) {
141 6
						$constrained_size = wp_constrain_dimensions( $data['width'], $data['height'], $size[0] );
142 6
						$expected_size = array( $size[0], $size[1] );
143 6
					} else {
144
						$constrained_size = wp_constrain_dimensions( $size[0], $size[1], $data['width'] );
145
						$expected_size = array( $data['width'], $data['height'] );
146
					}
147
148
					// If the image dimensions are within 1px of the expected size, we consider it a match.
149 6
					$matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
150
151 6
					if ( $matched ) {
152 6
						$candidates[ $data['width'] * $data['height'] ] = array( $_size, $data );
153 6
					}
154 6
				}
155 6
			}
156
157 6
			if ( ! empty( $candidates ) ) {
158
				// Sort the array by size if we have more than one candidate.
159 6
				if ( 1 < count( $candidates ) ) {
160 4
					ksort( $candidates );
161 4
				}
162
163 6
				$data = array_shift( $candidates );
164 6
				$data = $data[0];
165
			/*
166
			 * When the size requested is smaller than the thumbnail dimensions, we
167
			 * fall back to the thumbnail size.
168
			 */
169 6
			} elseif ( ! empty( $image_sizes['thumbnail'] ) && $image_sizes['thumbnail']['width'] >= $size[0] && $image_sizes['thumbnail']['width'] >= $size[1] ) {
170
				$data = 'thumbnail';
171
			} else {
172
				return false;
173
			}
174
175 6
		} elseif ( ! empty( $image_sizes[ $size ] ) ) {
0 ignored issues
show
Bug introduced by
The variable $image_sizes seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
176
			$data = $size;
177
		}
178
179
		// If we still don't have a match at this point, return false.
180 6
		if ( empty( $data ) ) {
181
			return false;
182
		}
183
184 6
		return $data;
185
	}
186
187
	/**
188
	 * Utility method that returns time string offset by timezone
189
	 * @since  1.0.0
190
	 * @param  string $tzstring Time string
191
	 * @return string           Offset time string
192
	 */
193 2
	public static function timezone_offset( $tzstring ) {
194 2
		$tz_offset = 0;
195
196 2
		if ( ! empty( $tzstring ) && is_string( $tzstring ) ) {
197 2
			if ( 'UTC' === substr( $tzstring, 0, 3 ) ) {
198 1
				$tzstring = str_replace( array( ':15', ':30', ':45' ), array( '.25', '.5', '.75' ), $tzstring );
199 1
				return intval( floatval( substr( $tzstring, 3 ) ) * HOUR_IN_SECONDS );
200
			}
201
202
			try {
203 1
				$date_time_zone_selected = new DateTimeZone( $tzstring );
204 1
				$tz_offset = timezone_offset_get( $date_time_zone_selected, date_create() );
205 1
			} catch ( Exception $e ) {
206
				self::log_if_debug( __METHOD__, __LINE__, $e->getMessage() );
207
			}
208
209 1
		}
210
211 1
		return $tz_offset;
212
	}
213
214
	/**
215
	 * Utility method that returns a timezone string representing the default timezone for the site.
216
	 *
217
	 * Roughly copied from WordPress, as get_option('timezone_string') will return
218
	 * an empty string if no value has been set on the options page.
219
	 * A timezone string is required by the wp_timezone_choice() used by the
220
	 * select_timezone field.
221
	 *
222
	 * @since  1.0.0
223
	 * @return string Timezone string
224
	 */
225 1
	public static function timezone_string() {
226 1
		$current_offset = get_option( 'gmt_offset' );
227 1
		$tzstring       = get_option( 'timezone_string' );
228
229
		// Remove old Etc mappings. Fallback to gmt_offset.
230 1
		if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
231
			$tzstring = '';
232
		}
233
234 1
		if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists
235 1
			if ( 0 == $current_offset ) {
236 1
				$tzstring = 'UTC+0';
237 1
			} elseif ( $current_offset < 0 ) {
238
				$tzstring = 'UTC' . $current_offset;
239
			} else {
240
				$tzstring = 'UTC+' . $current_offset;
241
			}
242 1
		}
243
244 1
		return $tzstring;
245
	}
246
247
	/**
248
	 * Returns a timestamp, first checking if value already is a timestamp.
249
	 * @since  2.0.0
250
	 * @param  string|int $string Possible timestamp string
251
	 * @return int   	            Time stamp
252
	 */
253 10
	public static function make_valid_time_stamp( $string ) {
254 10
		if ( ! $string ) {
255
			return 0;
256
		}
257
258 10
		return self::is_valid_time_stamp( $string )
259 10
			? (int) $string :
260 10
			strtotime( (string) $string );
261
	}
262
263
	/**
264
	 * Determine if a value is a valid timestamp
265
	 * @since  2.0.0
266
	 * @param  mixed  $timestamp Value to check
267
	 * @return boolean           Whether value is a valid timestamp
268
	 */
269 10
	public static function is_valid_time_stamp( $timestamp ) {
270 10
		return (string) (int) $timestamp === (string) $timestamp
271 10
			&& $timestamp <= PHP_INT_MAX
272 10
			&& $timestamp >= ~PHP_INT_MAX;
273
	}
274
275
	/**
276
	 * Checks if a value is 'empty'. Still accepts 0.
277
	 * @since  2.0.0
278
	 * @param  mixed $value Value to check
279
	 * @return bool         True or false
280
	 */
281 61
	public static function isempty( $value ) {
282 61
		return null === $value || '' === $value || false === $value || array() === $value;
283
	}
284
285
	/**
286
	 * Checks if a value is not 'empty'. 0 doesn't count as empty.
287
	 * @since  2.2.2
288
	 * @param  mixed $value Value to check
289
	 * @return bool         True or false
290
	 */
291 4
	public static function notempty( $value ){
292 4
		return null !== $value && '' !== $value && false !== $value && array() !== $value;
293
	}
294
295
	/**
296
	 * Filters out empty values (not including 0).
297
	 * @since  2.2.2
298
	 * @param  mixed $value Value to check
299
	 * @return bool         True or false
300
	 */
301 3
	public static function filter_empty( $value ) {
302 3
		return array_filter( $value, array( __CLASS__, 'notempty' ) );
303
	}
304
305
	/**
306
	 * Insert a single array item inside another array at a set position
307
	 * @since  2.0.2
308
	 * @param  array &$array   Array to modify. Is passed by reference, and no return is needed.
309
	 * @param  array $new      New array to insert
310
	 * @param  int   $position Position in the main array to insert the new array
311
	 */
312 2
	public static function array_insert( &$array, $new, $position ) {
313 2
		$before = array_slice( $array, 0, $position - 1 );
314 2
		$after  = array_diff_key( $array, $before );
315 2
		$array  = array_merge( $before, $new, $after );
316 2
	}
317
318
	/**
319
	 * Defines the url which is used to load local resources.
320
	 * This may need to be filtered for local Window installations.
321
	 * If resources do not load, please check the wiki for details.
322
	 * @since  1.0.1
323
	 * @return string URL to CMB2 resources
324
	 */
325 2
	public static function url( $path = '' ) {
326 2
		if ( self::$url ) {
327 1
			return self::$url . $path;
328
		}
329
330 1
		$cmb2_url = self::get_url_from_dir( cmb2_dir() );
331
332
		/**
333
		 * Filter the CMB location url
334
		 *
335
		 * @param string $cmb2_url Currently registered url
336
		 */
337 1
		self::$url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) );
338
339 1
		return self::$url . $path;
340
	}
341
342
	/**
343
	 * Converts a system path to a URL
344
	 * @since  2.2.2
345
	 * @param  string $dir Directory path to convert.
346
	 * @return string      Converted URL.
347
	 */
348 2
	public static function get_url_from_dir( $dir ) {
349 2
		$dir = self::normalize_path( $dir );
350
351
		// Let's test if We are in the plugins or mu-plugins dir.
352 2
		$test_dir = trailingslashit( $dir ) . 'unneeded.php';
353
		if (
354 2
			0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) )
355 2
			|| 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) )
356 2
		) {
357
			// Ok, then use plugins_url, as it is more reliable.
358 1
			return trailingslashit( plugins_url( '', $test_dir ) );
359
		}
360
361
		// Ok, now let's test if we are in the theme dir.
362 2
		$theme_root = self::normalize_path( get_theme_root() );
363 2
		if ( 0 === strpos( $dir, $theme_root ) ) {
364
			// Ok, then use get_theme_root_uri.
365 1
			return set_url_scheme(
366 1
				trailingslashit(
367 1
					str_replace(
368 1
						untrailingslashit( $theme_root ),
369 1
						untrailingslashit( get_theme_root_uri() ),
370
						$dir
371 1
					)
372 1
				)
373 1
			);
374
		}
375
376
		// Check to see if it's anywhere in the root directory
377
378 2
		$site_dir = self::normalize_path( self::$ABSPATH );
379 2
		$site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() );
380
381 2
		$url = str_replace(
382 2
			array( $site_dir, WP_PLUGIN_DIR ),
383 2
			array( $site_url, WP_PLUGIN_URL ),
384
			$dir
385 2
		);
386
387 2
		return set_url_scheme( $url );
388
	}
389
390
	/**
391
	 * `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path.
392
	 *
393
	 * On windows systems, replaces backslashes with forward slashes
394
	 * and forces upper-case drive letters.
395
	 * Allows for two leading slashes for Windows network shares, but
396
	 * ensures that all other duplicate slashes are reduced to a single.
397
	 *
398
	 * @since 2.2.0
399
	 *
400
	 * @param string $path Path to normalize.
401
	 * @return string Normalized path.
402
	 */
403 2
	protected static function normalize_path( $path ) {
404 2
		if ( function_exists( 'wp_normalize_path' ) ) {
405
			return wp_normalize_path( $path );
406
		}
407
408
		// Replace newer WP's version of wp_normalize_path.
409 2
		$path = str_replace( '\\', '/', $path );
410 2
		$path = preg_replace( '|(?<=.)/+|', '/', $path );
411 2
		if ( ':' === substr( $path, 1, 1 ) ) {
412 1
			$path = ucfirst( $path );
413 1
		}
414
415 2
		return $path;
416
	}
417
418
	/**
419
	 * Get timestamp from text date
420
	 * @since  2.2.0
421
	 * @param  string $value       Date value
422
	 * @param  string $date_format Expected date format
423
	 * @return mixed               Unix timestamp representing the date.
424
	 */
425
	public static function get_timestamp_from_value( $value, $date_format ) {
426
		$date_object = date_create_from_format( $date_format, $value );
427
		return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value );
428
	}
429
430
	/**
431
	 * Takes a php date() format string and returns a string formatted to suit for the date/time pickers
432
	 * It will work with only with the following subset ot date() options:
433
	 *
434
	 *  d, j, z, m, n, y, and Y.
435
	 *
436
	 * A slight effort is made to deal with escaped characters.
437
	 *
438
	 * Other options are ignored, because they would either bring compatibility problems between PHP and JS, or
439
	 * bring even more translation troubles.
440
	 *
441
	 * @since 2.2.0
442
	 * @param string $format php date format
443
	 * @return string reformatted string
444
	 */
445 5
	public static function php_to_js_dateformat( $format ) {
446
447
		// order is relevant here, since the replacement will be done sequentially.
448
		$supported_options = array(
449 5
			'd' => 'dd',  // Day, leading 0
450 5
			'j' => 'd',   // Day, no 0
451 5
			'z' => 'o',   // Day of the year, no leading zeroes,
452
			// 'D' => 'D',   // Day name short, not sure how it'll work with translations
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...
453
			// 'l' => 'DD',  // Day name full, idem before
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...
454 5
			'm' => 'mm',  // Month of the year, leading 0
455 5
			'n' => 'm',   // Month of the year, no leading 0
456
			// 'M' => 'M',   // Month, Short name
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...
457
			// 'F' => 'MM',  // Month, full name,
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...
458 5
			'y' => 'y',   // Year, two digit
459 5
			'Y' => 'yy',  // Year, full
460 5
			'H' => 'HH',  // Hour with leading 0 (24 hour)
461 5
			'G' => 'H',   // Hour with no leading 0 (24 hour)
462 5
			'h' => 'hh',  // Hour with leading 0 (12 hour)
463 5
			'g' => 'h',   // Hour with no leading 0 (12 hour),
464 5
			'i' => 'mm',  // Minute with leading 0,
465 5
			's' => 'ss',  // Second with leading 0,
466 5
			'a' => 'tt',  // am/pm
467
			'A' => 'TT'   // AM/PM
468 5
		);
469
470 5
		foreach ( $supported_options as $php => $js ) {
471
			// replaces every instance of a supported option, but skips escaped characters
472 5
			$format = preg_replace( "~(?<!\\\\)$php~", $js, $format );
473 5
		}
474
475 5
		$format = preg_replace_callback( '~(?:\\\.)+~', array( __CLASS__, 'wrap_escaped_chars' ), $format );
476
477 5
		return $format;
478
	}
479
480
	/**
481
	 * Helper function for CMB_Utils->php_to_js_dateformat, because php 5.2 was retarded.
482
	 * @since  2.2.0
483
	 * @param  $value Value to wrap/escape
484
	 * @return string Modified value
485
	 */
486 4
	public static function wrap_escaped_chars( $value ) {
487 4
		return "&#39;" . str_replace( '\\', '', $value[0] ) . "&#39;";
488
	}
489
490
	/**
491
	 * Send to debug.log if WP_DEBUG is defined and true
492
	 *
493
	 * @since  2.2.0
494
	 *
495
	 * @param  string  $function Function name
496
	 * @param  int     $line     Line number
497
	 * @param  mixed   $msg      Message to output
498
	 * @param  mixed   $debug    Variable to print_r
499
	 */
500
	public static function log_if_debug( $function, $line, $msg, $debug = null ) {
501
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
502
			error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) );
503
		}
504
	}
505
506
	/**
507
	 * Determine a file's extension
508
	 * @since  1.0.0
509
	 * @param  string       $file File url
510
	 * @return string|false       File extension or false
511
	 */
512 6
	public static function get_file_ext( $file ) {
513 6
		$parsed = parse_url( $file, PHP_URL_PATH );
514 6
		return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
515
	}
516
517
	/**
518
	 * Get the file name from a url
519
	 * @since  2.0.0
520
	 * @param  string $value File url or path
521
	 * @return string        File name
522
	 */
523 5
	public static function get_file_name_from_path( $value ) {
524 5
		$parts = explode( '/', $value );
525 5
		return is_array( $parts ) ? end( $parts ) : $value;
526
	}
527
528
	/**
529
	 * Check if WP version is at least $version.
530
	 * @since  2.2.2
531
	 * @param  string  $version WP version string to compare.
532
	 * @return bool             Result of comparison check.
533
	 */
534 6
	public static function wp_at_least( $version ) {
535 6
		return version_compare( get_bloginfo( 'version' ), $version, '>=' );
536
	}
537
538
	/**
539
	 * Combines attributes into a string for a form element.
540
	 * @since  1.1.0
541
	 * @param  array  $attrs        Attributes to concatenate.
542
	 * @param  array  $attr_exclude Attributes that should NOT be concatenated.
543
	 * @return string               String of attributes for form element.
544
	 */
545 46
	public static function concat_attrs( $attrs, $attr_exclude = array() ) {
546 46
		$attr_exclude[] = 'rendered';
547 46
		$attributes = '';
548 46
		foreach ( $attrs as $attr => $val ) {
549 46
			$excluded = in_array( $attr, (array) $attr_exclude, true );
550 46
			$empty    = false === $val && 'value' !== $attr;
551 46
			if ( ! $excluded && ! $empty ) {
552
				// if data attribute, use single quote wraps, else double
553 46
				$quotes = false !== stripos( $attr, 'data-' ) ? "'" : '"';
554 46
				$attributes .= sprintf( ' %1$s=%3$s%2$s%3$s', $attr, $val, $quotes );
555 46
			}
556 46
		}
557 46
		return $attributes;
558
	}
559
560
	/**
561
	 * Ensures value is an array.
562
	 *
563
	 * @since  2.2.3
564
	 *
565
	 * @param  mixed $value   Value to ensure is array.
566
	 * @param  array $default Default array. Defaults to empty array.
567
	 *
568
	 * @return array          The array.
569
	 */
570 48
	public static function ensure_array( $value, $default = array() ) {
571 48
		if ( empty( $value ) ) {
572 44
			return $default;
573
		}
574
575 6
		if ( is_array( $value ) || is_object( $value ) ) {
576 6
			return (array) $value;
577
		}
578
579
		// Not sure anything would be non-scalar that is not an array or object?
580 1
		if ( ! is_scalar( $value ) ) {
581
			return $default;
582
		}
583
584 1
		return (array) $value;
585
	}
586
587
}
588