Completed
Push — trunk ( 4bf362...177664 )
by
unknown
493:49 queued 491:11
created

CMB2_Utils::get_file_ext()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 6
rs 10
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
	 *
18
	 * @var   string
19
	 * @since 2.2.3
20
	 */
21
	protected static $ABSPATH = ABSPATH;
22 1
23 1
	/**
24
	 * The url which is used to load local resources.
25 1
	 *
26
	 * @var   string
27 1
	 * @since 2.0.0
28 1
	 */
29 1
	protected static $url = '';
30 1
31
	/**
32
	 * Utility method that attempts to get an attachment's ID by it's url
33 1
	 *
34
	 * @since  1.0.0
35
	 * @param  string $img_url Attachment url
36 1
	 * @return int|false            Attachment ID or false
37 1
	 */
38
	public static function image_id_from_url( $img_url ) {
39
		$attachment_id = 0;
40
		$dir = wp_upload_dir();
41
42
		// Is URL in uploads directory?
43
		if ( false === strpos( $img_url, $dir['baseurl'] . '/' ) ) {
44
			return false;
45
		}
46
47
		$file = basename( $img_url );
48
49
		$query_args = array(
50 2
			'post_type'   => 'attachment',
51 2
			'post_status' => 'inherit',
52 1
			'fields'      => 'ids',
53 1
			'meta_query'  => array(
54 1
				array(
55
					'value'   => $file,
56
					'compare' => 'LIKE',
57
					'key'     => '_wp_attachment_metadata',
58
				),
59
			),
60
		);
61
62
		$query = new WP_Query( $query_args );
63 1
64
		if ( $query->have_posts() ) {
65
66
			foreach ( $query->posts as $post_id ) {
67
				$meta = wp_get_attachment_metadata( $post_id );
68
				$original_file       = basename( $meta['file'] );
69
				$cropped_image_files = isset( $meta['sizes'] ) ? wp_list_pluck( $meta['sizes'], 'file' ) : array();
70
				if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
71
					$attachment_id = $post_id;
72
					break;
73
				}
74
			}
75
		}
76
77 2
		return 0 === $attachment_id ? false : $attachment_id;
78 2
	}
79 2
80
	/**
81 2
	 * Utility method to get a combined list of default and custom registered image sizes
82 2
	 *
83 2
	 * @since  2.2.4
84 2
	 * @link   http://core.trac.wordpress.org/ticket/18947
85
	 * @global array $_wp_additional_image_sizes
86
	 * @return array The image sizes
87
	 */
88
	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...
89 2
		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...
90
91 2
		$default_image_sizes = array( 'thumbnail', 'medium', 'large' );
92
		foreach ( $default_image_sizes as $size ) {
93
			$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...
94
				'height' => intval( get_option( "{$size}_size_h" ) ),
95
				'width'  => intval( get_option( "{$size}_size_w" ) ),
96
				'crop'   => get_option( "{$size}_crop" ) ? get_option( "{$size}_crop" ) : false,
97
			);
98
		}
99
100 5
		if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) {
101 5
			$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...
102
		}
103
104
		return $image_sizes;
105 5
	}
106 5
107 5
	/**
108
	 * Utility method to return the closest named size from an array of values
109
	 *
110
	 * Based off of WordPress's image_get_intermediate_size()
111
	 * If the size matches an existing size then it will be used. If there is no
112
	 * direct match, then the nearest image size larger than the specified size
113
	 * will be used. If nothing is found, then the function will return false.
114
	 * Uses get_available_image_sizes() to get all available sizes.
115
	 *
116 5
	 * @since  2.2.4
117 5
	 * @param  array|string $size Image size. Accepts an array of width and height (in that order)
118 5
	 * @return false|string       Named image size e.g. 'thumbnail'
119 5
	 */
120 5
	public static function get_named_size( $size ) {
121
		$data = array();
122
123
		// Find the best match when '$size' is an array.
124
		if ( is_array( $size ) ) {
125
			$image_sizes = self::get_available_image_sizes();
126
			$candidates = array();
127
128
			foreach ( $image_sizes as $_size => $data ) {
129
130 2
				// If there's an exact match to an existing image size, short circuit.
131 2
				if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
132 1
					$candidates[ $data['width'] * $data['height'] ] = array( $_size, $data );
133
					break;
134
				}
135 1
136
				// If it's not an exact match, consider larger sizes with the same aspect ratio.
137
				if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
138
139
					/*
140
					 * To test for varying crops, we constrain the dimensions of the larger image
141
					 * to the dimensions of the smaller image and see if they match.
142 1
					 */
143 1
					if ( $data['width'] > $size[0] ) {
144 1
						$constrained_size = wp_constrain_dimensions( $data['width'], $data['height'], $size[0] );
145 1
						$expected_size = array( $size[0], $size[1] );
146 1
					} else {
147
						$constrained_size = wp_constrain_dimensions( $size[0], $size[1], $data['width'] );
148
						$expected_size = array( $data['width'], $data['height'] );
149
					}
150
151
					// If the image dimensions are within 1px of the expected size, we consider it a match.
152
					$matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
153
154 1
					if ( $matched ) {
155
						$candidates[ $data['width'] * $data['height'] ] = array( $_size, $data );
156 1
					}
157
				}
158
			}
159
160 1
			if ( ! empty( $candidates ) ) {
161
				// Sort the array by size if we have more than one candidate.
162
				if ( 1 < count( $candidates ) ) {
163
					ksort( $candidates );
164
				}
165
166
				$data = array_shift( $candidates );
167
				$data = $data[0];
168
			} elseif ( ! empty( $image_sizes['thumbnail'] ) && $image_sizes['thumbnail']['width'] >= $size[0] && $image_sizes['thumbnail']['width'] >= $size[1] ) {
169
				/*
170
				 * When the size requested is smaller than the thumbnail dimensions, we
171
				 * fall back to the thumbnail size.
172
				 */
173
				$data = 'thumbnail';
174
			} else {
175
				return false;
176
			}
177
		} 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...
178
			$data = $size;
179
		}
180
181
		// If we still don't have a match at this point, return false.
182
		if ( empty( $data ) ) {
183
			return false;
184
		}
185
186
		return $data;
187
	}
188
189
	/**
190
	 * Utility method that returns time string offset by timezone
191
	 *
192
	 * @since  1.0.0
193
	 * @param  string $tzstring Time string
194
	 * @return string           Offset time string
195
	 */
196
	public static function timezone_offset( $tzstring ) {
197
		$tz_offset = 0;
198
199
		if ( ! empty( $tzstring ) && is_string( $tzstring ) ) {
200
			if ( 'UTC' === substr( $tzstring, 0, 3 ) ) {
201
				$tzstring = str_replace( array( ':15', ':30', ':45' ), array( '.25', '.5', '.75' ), $tzstring );
202
				return intval( floatval( substr( $tzstring, 3 ) ) * HOUR_IN_SECONDS );
203
			}
204
205
			try {
206
				$date_time_zone_selected = new DateTimeZone( $tzstring );
207
				$tz_offset = timezone_offset_get( $date_time_zone_selected, date_create() );
208
			} catch ( Exception $e ) {
209
				self::log_if_debug( __METHOD__, __LINE__, $e->getMessage() );
210
			}
211
212
		}
213
214
		return $tz_offset;
215
	}
216
217
	/**
218
	 * Utility method that returns a timezone string representing the default timezone for the site.
219
	 *
220
	 * Roughly copied from WordPress, as get_option('timezone_string') will return
221
	 * an empty string if no value has been set on the options page.
222
	 * A timezone string is required by the wp_timezone_choice() used by the
223
	 * select_timezone field.
224
	 *
225
	 * @since  1.0.0
226
	 * @return string Timezone string
227
	 */
228
	public static function timezone_string() {
229
		$current_offset = get_option( 'gmt_offset' );
230
		$tzstring       = get_option( 'timezone_string' );
231
232
		// Remove old Etc mappings. Fallback to gmt_offset.
233
		if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
234
			$tzstring = '';
235
		}
236
237
		if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists
238
			if ( 0 == $current_offset ) {
239
				$tzstring = 'UTC+0';
240
			} elseif ( $current_offset < 0 ) {
241
				$tzstring = 'UTC' . $current_offset;
242
			} else {
243
				$tzstring = 'UTC+' . $current_offset;
244
			}
245
		}
246
247
		return $tzstring;
248
	}
249
250
	/**
251
	 * Returns a timestamp, first checking if value already is a timestamp.
252
	 *
253
	 * @since  2.0.0
254
	 * @param  string|int $string Possible timestamp string
255
	 * @return int   	            Time stamp
256
	 */
257
	public static function make_valid_time_stamp( $string ) {
258
		if ( ! $string ) {
259
			return 0;
260
		}
261
262
		return self::is_valid_time_stamp( $string )
263
			? (int) $string :
264
			strtotime( (string) $string );
265
	}
266
267
	/**
268
	 * Determine if a value is a valid timestamp
269
	 *
270
	 * @since  2.0.0
271
	 * @param  mixed $timestamp Value to check
272
	 * @return boolean           Whether value is a valid timestamp
273
	 */
274
	public static function is_valid_time_stamp( $timestamp ) {
275
		return (string) (int) $timestamp === (string) $timestamp
276
			&& $timestamp <= PHP_INT_MAX
277
			&& $timestamp >= ~PHP_INT_MAX;
278
	}
279
280
	/**
281
	 * Checks if a value is 'empty'. Still accepts 0.
282
	 *
283
	 * @since  2.0.0
284
	 * @param  mixed $value Value to check
285
	 * @return bool         True or false
286
	 */
287
	public static function isempty( $value ) {
288
		return null === $value || '' === $value || false === $value || array() === $value;
289
	}
290
291
	/**
292
	 * Checks if a value is not 'empty'. 0 doesn't count as empty.
293
	 *
294
	 * @since  2.2.2
295
	 * @param  mixed $value Value to check
296
	 * @return bool         True or false
297
	 */
298
	public static function notempty( $value ) {
299
		return null !== $value && '' !== $value && false !== $value && array() !== $value;
300
	}
301
302
	/**
303
	 * Filters out empty values (not including 0).
304
	 *
305
	 * @since  2.2.2
306
	 * @param  mixed $value Value to check
307
	 * @return bool         True or false
308
	 */
309
	public static function filter_empty( $value ) {
310
		return array_filter( $value, array( __CLASS__, 'notempty' ) );
311
	}
312
313
	/**
314
	 * Insert a single array item inside another array at a set position
315
	 *
316
	 * @since  2.0.2
317
	 * @param  array &$array   Array to modify. Is passed by reference, and no return is needed.
318
	 * @param  array $new      New array to insert
319
	 * @param  int   $position Position in the main array to insert the new array
320
	 */
321
	public static function array_insert( &$array, $new, $position ) {
322
		$before = array_slice( $array, 0, $position - 1 );
323
		$after  = array_diff_key( $array, $before );
324
		$array  = array_merge( $before, $new, $after );
325
	}
326
327
	/**
328
	 * Defines the url which is used to load local resources.
329
	 * This may need to be filtered for local Window installations.
330
	 * If resources do not load, please check the wiki for details.
331
	 *
332
	 * @since  1.0.1
333
	 * @return string URL to CMB2 resources
334
	 */
335
	public static function url( $path = '' ) {
336
		if ( self::$url ) {
337
			return self::$url . $path;
338
		}
339
340
		$cmb2_url = self::get_url_from_dir( cmb2_dir() );
341
342
		/**
343
		 * Filter the CMB location url
344
		 *
345
		 * @param string $cmb2_url Currently registered url
346
		 */
347
		self::$url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) );
348
349
		return self::$url . $path;
350
	}
351
352
	/**
353
	 * Converts a system path to a URL
354
	 *
355
	 * @since  2.2.2
356
	 * @param  string $dir Directory path to convert.
357
	 * @return string      Converted URL.
358
	 */
359
	public static function get_url_from_dir( $dir ) {
360
		$dir = self::normalize_path( $dir );
361
362
		// Let's test if We are in the plugins or mu-plugins dir.
363
		$test_dir = trailingslashit( $dir ) . 'unneeded.php';
364
		if (
365
			0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) )
366
			|| 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) )
367
		) {
368
			// Ok, then use plugins_url, as it is more reliable.
369
			return trailingslashit( plugins_url( '', $test_dir ) );
370
		}
371
372
		// Ok, now let's test if we are in the theme dir.
373
		$theme_root = self::normalize_path( get_theme_root() );
374
		if ( 0 === strpos( $dir, $theme_root ) ) {
375
			// Ok, then use get_theme_root_uri.
376
			return set_url_scheme(
377
				trailingslashit(
378
					str_replace(
379
						untrailingslashit( $theme_root ),
380
						untrailingslashit( get_theme_root_uri() ),
381
						$dir
382
					)
383
				)
384
			);
385
		}
386
387
		// Check to see if it's anywhere in the root directory
388
		$site_dir = self::normalize_path( self::$ABSPATH );
389
		$site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() );
390
391
		$url = str_replace(
392
			array( $site_dir, WP_PLUGIN_DIR ),
393
			array( $site_url, WP_PLUGIN_URL ),
394
			$dir
395
		);
396
397
		return set_url_scheme( $url );
398
	}
399
400
	/**
401
	 * `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path.
402
	 *
403
	 * On windows systems, replaces backslashes with forward slashes
404
	 * and forces upper-case drive letters.
405
	 * Allows for two leading slashes for Windows network shares, but
406
	 * ensures that all other duplicate slashes are reduced to a single.
407
	 *
408
	 * @since 2.2.0
409
	 *
410
	 * @param string $path Path to normalize.
411
	 * @return string Normalized path.
412
	 */
413
	protected static function normalize_path( $path ) {
414
		if ( function_exists( 'wp_normalize_path' ) ) {
415
			return wp_normalize_path( $path );
416
		}
417
418
		// Replace newer WP's version of wp_normalize_path.
419
		$path = str_replace( '\\', '/', $path );
420
		$path = preg_replace( '|(?<=.)/+|', '/', $path );
421
		if ( ':' === substr( $path, 1, 1 ) ) {
422
			$path = ucfirst( $path );
423
		}
424
425
		return $path;
426
	}
427
428
	/**
429
	 * Get timestamp from text date
430
	 *
431
	 * @since  2.2.0
432
	 * @param  string $value       Date value
433
	 * @param  string $date_format Expected date format
434
	 * @return mixed               Unix timestamp representing the date.
435
	 */
436
	public static function get_timestamp_from_value( $value, $date_format ) {
437
		$date_object = date_create_from_format( $date_format, $value );
438
		return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value );
439
	}
440
441
	/**
442
	 * Takes a php date() format string and returns a string formatted to suit for the date/time pickers
443
	 * It will work with only with the following subset ot date() options:
444
	 *
445
	 *  d, j, z, m, n, y, and Y.
446
	 *
447
	 * A slight effort is made to deal with escaped characters.
448
	 *
449
	 * Other options are ignored, because they would either bring compatibility problems between PHP and JS, or
450
	 * bring even more translation troubles.
451
	 *
452
	 * @since 2.2.0
453
	 * @param string $format php date format
454
	 * @return string reformatted string
455
	 */
456
	public static function php_to_js_dateformat( $format ) {
457
458
		// order is relevant here, since the replacement will be done sequentially.
459
		$supported_options = array(
460
			'd' => 'dd',  // Day, leading 0
461
			'j' => 'd',   // Day, no 0
462
			'z' => 'o',   // Day of the year, no leading zeroes,
463
			// '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...
464
			// '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...
465
			'm' => 'mm',  // Month of the year, leading 0
466
			'n' => 'm',   // Month of the year, no leading 0
467
			// '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...
468
			// '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...
469
			'y' => 'y',   // Year, two digit
470
			'Y' => 'yy',  // Year, full
471
			'H' => 'HH',  // Hour with leading 0 (24 hour)
472
			'G' => 'H',   // Hour with no leading 0 (24 hour)
473
			'h' => 'hh',  // Hour with leading 0 (12 hour)
474
			'g' => 'h',   // Hour with no leading 0 (12 hour),
475
			'i' => 'mm',  // Minute with leading 0,
476
			's' => 'ss',  // Second with leading 0,
477
			'a' => 'tt',  // am/pm
478
			'A' => 'TT',// AM/PM
479
		);
480
481
		foreach ( $supported_options as $php => $js ) {
482
			// replaces every instance of a supported option, but skips escaped characters
483
			$format = preg_replace( "~(?<!\\\\)$php~", $js, $format );
484
		}
485
486
		$format = preg_replace_callback( '~(?:\\\.)+~', array( __CLASS__, 'wrap_escaped_chars' ), $format );
487
488
		return $format;
489
	}
490
491
	/**
492
	 * Helper function for CMB_Utils->php_to_js_dateformat, because php 5.2 was retarded.
493
	 *
494
	 * @since  2.2.0
495
	 * @param  $value Value to wrap/escape
496
	 * @return string Modified value
497
	 */
498
	public static function wrap_escaped_chars( $value ) {
499
		return '&#39;' . str_replace( '\\', '', $value[0] ) . '&#39;';
500
	}
501
502
	/**
503
	 * Send to debug.log if WP_DEBUG is defined and true
504
	 *
505
	 * @since  2.2.0
506
	 *
507
	 * @param  string $function Function name
508
	 * @param  int    $line     Line number
509
	 * @param  mixed  $msg      Message to output
510
	 * @param  mixed  $debug    Variable to print_r
511
	 */
512
	public static function log_if_debug( $function, $line, $msg, $debug = null ) {
513
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
514
			error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) );
515
		}
516
	}
517
518
	/**
519
	 * Determine a file's extension
520
	 *
521
	 * @since  1.0.0
522
	 * @param  string $file File url
523
	 * @return string|false       File extension or false
524
	 */
525
	public static function get_file_ext( $file ) {
526
		$parsed = parse_url( $file, PHP_URL_PATH );
527
		return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
528
	}
529
530
	/**
531
	 * Get the file name from a url
532
	 *
533
	 * @since  2.0.0
534
	 * @param  string $value File url or path
535
	 * @return string        File name
536
	 */
537
	public static function get_file_name_from_path( $value ) {
538
		$parts = explode( '/', $value );
539
		return is_array( $parts ) ? end( $parts ) : $value;
540
	}
541
542
	/**
543
	 * Check if WP version is at least $version.
544
	 *
545
	 * @since  2.2.2
546
	 * @param  string $version WP version string to compare.
547
	 * @return bool             Result of comparison check.
548
	 */
549
	public static function wp_at_least( $version ) {
550
		return version_compare( get_bloginfo( 'version' ), $version, '>=' );
551
	}
552
553
	/**
554
	 * Combines attributes into a string for a form element.
555
	 *
556
	 * @since  1.1.0
557
	 * @param  array $attrs        Attributes to concatenate.
558
	 * @param  array $attr_exclude Attributes that should NOT be concatenated.
559
	 * @return string               String of attributes for form element.
560
	 */
561
	public static function concat_attrs( $attrs, $attr_exclude = array() ) {
562
		$attr_exclude[] = 'rendered';
563
		$attributes = '';
564
		foreach ( $attrs as $attr => $val ) {
565
			$excluded = in_array( $attr, (array) $attr_exclude, true );
566
			$empty    = false === $val && 'value' !== $attr;
567
			if ( ! $excluded && ! $empty ) {
568
				// if data attribute, use single quote wraps, else double
569
				$quotes = false !== stripos( $attr, 'data-' ) ? "'" : '"';
570
				$attributes .= sprintf( ' %1$s=%3$s%2$s%3$s', $attr, $val, $quotes );
571
			}
572
		}
573
		return $attributes;
574
	}
575
576
	/**
577
	 * Ensures value is an array.
578
	 *
579
	 * @since  2.2.3
580
	 *
581
	 * @param  mixed $value   Value to ensure is array.
582
	 * @param  array $default Default array. Defaults to empty array.
583
	 *
584
	 * @return array          The array.
585
	 */
586
	public static function ensure_array( $value, $default = array() ) {
587
		if ( empty( $value ) ) {
588
			return $default;
589
		}
590
591
		if ( is_array( $value ) || is_object( $value ) ) {
592
			return (array) $value;
593
		}
594
595
		// Not sure anything would be non-scalar that is not an array or object?
596
		if ( ! is_scalar( $value ) ) {
597
			return $default;
598
		}
599
600
		return (array) $value;
601
	}
602
603
}
604