PluginProbe
WPGet API – Connect to any external REST API / 2.0.6
WPGet API – Connect to any external REST API v2.0.6
1.9.2 1.9.3 1.9.4 1.9.5 1.9.6 1.9.7 1.9.8 1.9.9 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.1.0 2.1.1 2.1.3 2.1.4 2.1.5 2.2.0 2.2.1 2.2.10 2.2.2 2.2.3 All 97 releases
wpgetapi / lib / cmb2 / includes / CMB2_Utils.php

CMB2_Utils.php in WPGet API – Connect to any external REST API 2.0.6, at lib/cmb2/includes/CMB2_Utils.php

704 lines 20.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * CMB2 Utilities
4 *
5 * @since 1.1.0
6 *
7 * @category WordPress_Plugin
8 * @package CMB2
9 * @author CMB2 team
10 * @license GPL-2.0+
11 * @link https://cmb2.io
12 */
13 class CMB2_Utils {
14
15 /**
16 * The WordPress ABSPATH constant.
17 *
18 * @var string
19 * @since 2.2.3
20 */
21 protected static $ABSPATH = ABSPATH;
22
23 /**
24 * The url which is used to load local resources.
25 *
26 * @var string
27 * @since 2.0.0
28 */
29 protected static $url = '';
30
31 /**
32 * Utility method that attempts to get an attachment's ID by it's url
33 *
34 * @since 1.0.0
35 * @param string $img_url Attachment url.
36 * @return int|false Attachment ID or false
37 */
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 'post_type' => 'attachment',
51 'post_status' => 'inherit',
52 'fields' => 'ids',
53 'meta_query' => array(
54 array(
55 'value' => $file,
56 'compare' => 'LIKE',
57 'key' => '_wp_attachment_metadata',
58 ),
59 ),
60 );
61
62 $query = new WP_Query( $query_args );
63
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 return 0 === $attachment_id ? false : $attachment_id;
78 }
79
80 /**
81 * Utility method to get a combined list of default and custom registered image sizes
82 *
83 * @since 2.2.4
84 * @link http://core.trac.wordpress.org/ticket/18947
85 * @global array $_wp_additional_image_sizes
86 * @return array The image sizes
87 */
88 public static function get_available_image_sizes() {
89 global $_wp_additional_image_sizes;
90
91 $default_image_sizes = array( 'thumbnail', 'medium', 'large' );
92 foreach ( $default_image_sizes as $size ) {
93 $image_sizes[ $size ] = array(
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 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) {
101 $image_sizes = array_merge( $image_sizes, $_wp_additional_image_sizes );
102 }
103
104 return $image_sizes;
105 }
106
107 /**
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 * @since 2.2.4
117 * @param array|string $size Image size. Accepts an array of width and height (in that order).
118 * @return false|string Named image size e.g. 'thumbnail'
119 */
120 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 // If there's an exact match to an existing image size, short circuit.
131 if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
132 $candidates[ $data['width'] * $data['height'] ] = array( $_size, $data );
133 break;
134 }
135
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 */
143 if ( $data['width'] > $size[0] ) {
144 $constrained_size = wp_constrain_dimensions( $data['width'], $data['height'], $size[0] );
145 $expected_size = array( $size[0], $size[1] );
146 } 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 if ( $matched ) {
155 $candidates[ $data['width'] * $data['height'] ] = array( $_size, $data );
156 }
157 }
158 }
159
160 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 ] ) ) {
178 $data = $size;
179 }// End if.
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 return $tz_offset;
214 }
215
216 /**
217 * Utility method that returns a timezone string representing the default timezone for the site.
218 *
219 * Roughly copied from WordPress, as get_option('timezone_string') will return
220 * an empty string if no value has been set on the options page.
221 * A timezone string is required by the wp_timezone_choice() used by the
222 * select_timezone field.
223 *
224 * @since 1.0.0
225 * @return string Timezone string
226 */
227 public static function timezone_string() {
228 $current_offset = get_option( 'gmt_offset' );
229 $tzstring = get_option( 'timezone_string' );
230
231 // Remove old Etc mappings. Fallback to gmt_offset.
232 if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
233 $tzstring = '';
234 }
235
236 if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists.
237 if ( 0 == $current_offset ) {
238 $tzstring = 'UTC+0';
239 } elseif ( $current_offset < 0 ) {
240 $tzstring = 'UTC' . $current_offset;
241 } else {
242 $tzstring = 'UTC+' . $current_offset;
243 }
244 }
245
246 return $tzstring;
247 }
248
249 /**
250 * Returns a unix timestamp, first checking if value already is a timestamp.
251 *
252 * @since 2.0.0
253 * @param string|int $string Possible timestamp string.
254 * @return int Time stamp.
255 */
256 public static function make_valid_time_stamp( $string ) {
257 if ( ! $string ) {
258 return 0;
259 }
260
261 $timestamp = @strtotime( (string) $string );
262 if ( ! empty( $timestamp ) ) {
263
264 // We got a timestamp, first try!
265 return $timestamp;
266 }
267
268 $valid = self::is_valid_time_stamp( $string );
269 if ( $valid ) {
270 $timestamp = (int) $string;
271 $length = strlen( (string) $timestamp );
272 $unixlength = strlen( (string) time() );
273 $diff = $length - $unixlength;
274
275 // If value is larger than a unix timestamp, we need to round to the
276 // nearest unix timestamp (in seconds).
277 if ( $diff > 0 ) {
278 $divider = (int) '1' . str_repeat( '0', $diff );
279 $timestamp = round( $timestamp / $divider );
280 }
281 }
282
283 return $timestamp;
284 }
285
286 /**
287 * Determine if a value is a valid date.
288 *
289 * @since 2.9.1
290 * @param mixed $date Value to check.
291 * @return boolean Whether value is a valid date
292 */
293 public static function is_valid_date( $date ) {
294 return ( is_string( $date ) && @strtotime( $date ) )
295 || self::is_valid_time_stamp( $date );
296 }
297
298 /**
299 * Determine if a value is a valid timestamp
300 *
301 * @since 2.0.0
302 * @param mixed $timestamp Value to check.
303 * @return boolean Whether value is a valid timestamp
304 */
305 public static function is_valid_time_stamp( $timestamp ) {
306 return (string) (int) $timestamp === (string) $timestamp
307 && $timestamp <= PHP_INT_MAX
308 && $timestamp >= ~PHP_INT_MAX;
309 }
310
311 /**
312 * Checks if a value is 'empty'. Still accepts 0.
313 *
314 * @since 2.0.0
315 * @param mixed $value Value to check.
316 * @return bool True or false
317 */
318 public static function isempty( $value ) {
319 return null === $value || '' === $value || false === $value || array() === $value;
320 }
321
322 /**
323 * Checks if a value is not 'empty'. 0 doesn't count as empty.
324 *
325 * @since 2.2.2
326 * @param mixed $value Value to check.
327 * @return bool True or false
328 */
329 public static function notempty( $value ) {
330 return null !== $value && '' !== $value && false !== $value && array() !== $value;
331 }
332
333 /**
334 * Filters out empty values (not including 0).
335 *
336 * @since 2.2.2
337 * @param mixed $value Value to check.
338 * @return array True or false.
339 */
340 public static function filter_empty( $value ) {
341 return array_filter( $value, array( __CLASS__, 'notempty' ) );
342 }
343
344 /**
345 * Insert a single array item inside another array at a set position
346 *
347 * @since 2.0.2
348 * @param array $array Array to modify. Is passed by reference, and no return is needed. Passed by reference.
349 * @param array $new New array to insert.
350 * @param int $position Position in the main array to insert the new array.
351 */
352 public static function array_insert( &$array, $new, $position ) {
353 $before = array_slice( $array, 0, $position - 1 );
354 $after = array_diff_key( $array, $before );
355 $array = array_merge( $before, $new, $after );
356 }
357
358 /**
359 * Defines the url which is used to load local resources.
360 * This may need to be filtered for local Window installations.
361 * If resources do not load, please check the wiki for details.
362 *
363 * @since 1.0.1
364 *
365 * @param string $path URL path.
366 * @return string URL to CMB2 resources
367 */
368 public static function url( $path = '' ) {
369 if ( self::$url ) {
370 return self::$url . $path;
371 }
372
373 $cmb2_url = self::get_url_from_dir( cmb2_dir() );
374
375 /**
376 * Filter the CMB location url.
377 *
378 * @param string $cmb2_url Currently registered url.
379 */
380 self::$url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) );
381
382 return self::$url . $path;
383 }
384
385 /**
386 * Converts a system path to a URL
387 *
388 * @since 2.2.2
389 * @param string $dir Directory path to convert.
390 * @return string Converted URL.
391 */
392 public static function get_url_from_dir( $dir ) {
393 $dir = self::normalize_path( $dir );
394
395 // Let's test if We are in the plugins or mu-plugins dir.
396 $test_dir = trailingslashit( $dir ) . 'unneeded.php';
397 if (
398 0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) )
399 || 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) )
400 ) {
401 // Ok, then use plugins_url, as it is more reliable.
402 return trailingslashit( plugins_url( '', $test_dir ) );
403 }
404
405 // Ok, now let's test if we are in the theme dir.
406 $theme_root = self::normalize_path( get_theme_root() );
407 if ( 0 === strpos( $dir, $theme_root ) ) {
408 // Ok, then use get_theme_root_uri.
409 return set_url_scheme(
410 trailingslashit(
411 str_replace(
412 untrailingslashit( $theme_root ),
413 untrailingslashit( get_theme_root_uri() ),
414 $dir
415 )
416 )
417 );
418 }
419
420 // Check to see if it's anywhere in the root directory.
421 $site_dir = self::get_normalized_abspath();
422 $site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() );
423
424 $url = str_replace(
425 array( $site_dir, WP_PLUGIN_DIR ),
426 array( $site_url, WP_PLUGIN_URL ),
427 $dir
428 );
429
430 return set_url_scheme( $url );
431 }
432
433 /**
434 * Get the normalized absolute path defined by WordPress.
435 *
436 * @since 2.2.6
437 *
438 * @return string Normalized absolute path.
439 */
440 protected static function get_normalized_abspath() {
441 return self::normalize_path( self::$ABSPATH );
442 }
443
444 /**
445 * `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path.
446 *
447 * On windows systems, replaces backslashes with forward slashes
448 * and forces upper-case drive letters.
449 * Allows for two leading slashes for Windows network shares, but
450 * ensures that all other duplicate slashes are reduced to a single.
451 *
452 * @since 2.2.0
453 *
454 * @param string $path Path to normalize.
455 * @return string Normalized path.
456 */
457 protected static function normalize_path( $path ) {
458 if ( function_exists( 'wp_normalize_path' ) ) {
459 return wp_normalize_path( $path );
460 }
461
462 // Replace newer WP's version of wp_normalize_path.
463 $path = str_replace( '\\', '/', $path );
464 $path = preg_replace( '|(?<=.)/+|', '/', $path );
465 if ( ':' === substr( $path, 1, 1 ) ) {
466 $path = ucfirst( $path );
467 }
468
469 return $path;
470 }
471
472 /**
473 * Get timestamp from text date
474 *
475 * @since 2.2.0
476 * @param string $value Date value.
477 * @param string $date_format Expected date format.
478 * @return mixed Unix timestamp representing the date.
479 */
480 public static function get_timestamp_from_value( $value, $date_format ) {
481 $date_object = date_create_from_format( $date_format, $value );
482 return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value );
483 }
484
485 /**
486 * Takes a php date() format string and returns a string formatted to suit for the date/time pickers
487 * It will work only with the following subset of date() options:
488 *
489 * Formats: d, l, j, z, m, F, n, y, and Y.
490 *
491 * A slight effort is made to deal with escaped characters.
492 *
493 * Other options are ignored, because they would either bring compatibility problems between PHP and JS, or
494 * bring even more translation troubles.
495 *
496 * @since 2.2.0
497 * @param string $format PHP date format.
498 * @return string reformatted string
499 */
500 public static function php_to_js_dateformat( $format ) {
501
502 // order is relevant here, since the replacement will be done sequentially.
503 $supported_options = array(
504 'd' => 'dd', // Day, leading 0.
505 'j' => 'd', // Day, no 0.
506 'z' => 'o', // Day of the year, no leading zeroes.
507 // 'D' => 'D', // Day name short, not sure how it'll work with translations.
508 'l ' => 'DD ', // Day name full, idem before.
509 'l, ' => 'DD, ', // Day name full, idem before.
510 'm' => 'mm', // Month of the year, leading 0.
511 'n' => 'm', // Month of the year, no leading 0.
512 // 'M' => 'M', // Month, Short name.
513 'F ' => 'MM ', // Month, full name.
514 'F, ' => 'MM, ', // Month, full name.
515 'y' => 'y', // Year, two digit.
516 'Y' => 'yy', // Year, full.
517 'H' => 'HH', // Hour with leading 0 (24 hour).
518 'G' => 'H', // Hour with no leading 0 (24 hour).
519 'h' => 'hh', // Hour with leading 0 (12 hour).
520 'g' => 'h', // Hour with no leading 0 (12 hour).
521 'i' => 'mm', // Minute with leading 0.
522 's' => 'ss', // Second with leading 0.
523 'a' => 'tt', // am/pm.
524 'A' => 'TT', // AM/PM.
525 );
526
527 foreach ( $supported_options as $php => $js ) {
528 // replaces every instance of a supported option, but skips escaped characters.
529 $format = preg_replace( "~(?<!\\\\)$php~", $js, $format );
530 }
531
532 $supported_options = array(
533 'l' => 'DD', // Day name full, idem before.
534 'F' => 'MM', // Month, full name.
535 );
536
537 if ( isset( $supported_options[ $format ] ) ) {
538 $format = $supported_options[ $format ];
539 }
540
541 $format = preg_replace_callback( '~(?:\\\.)+~', array( __CLASS__, 'wrap_escaped_chars' ), $format );
542
543 return $format;
544 }
545
546 /**
547 * Helper function for CMB_Utils::php_to_js_dateformat().
548 *
549 * @since 2.2.0
550 * @param string $value Value to wrap/escape.
551 * @return string Modified value
552 */
553 public static function wrap_escaped_chars( $value ) {
554 return '&#39;' . str_replace( '\\', '', $value[0] ) . '&#39;';
555 }
556
557 /**
558 * Send to debug.log if WP_DEBUG is defined and true
559 *
560 * @since 2.2.0
561 *
562 * @param string $function Function name.
563 * @param int $line Line number.
564 * @param mixed $msg Message to output.
565 * @param mixed $debug Variable to print_r.
566 */
567 public static function log_if_debug( $function, $line, $msg, $debug = null ) {
568 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
569 error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) );
570 }
571 }
572
573 /**
574 * Determine a file's extension
575 *
576 * @since 1.0.0
577 * @param string $file File url.
578 * @return string|false File extension or false
579 */
580 public static function get_file_ext( $file ) {
581 $parsed = parse_url( $file, PHP_URL_PATH );
582 return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
583 }
584
585 /**
586 * Get the file name from a url
587 *
588 * @since 2.0.0
589 * @param string $value File url or path.
590 * @return string File name
591 */
592 public static function get_file_name_from_path( $value ) {
593 $parts = explode( '/', $value );
594 return is_array( $parts ) ? end( $parts ) : $value;
595 }
596
597 /**
598 * Check if WP version is at least $version.
599 *
600 * @since 2.2.2
601 * @param string $version WP version string to compare.
602 * @return bool Result of comparison check.
603 */
604 public static function wp_at_least( $version ) {
605 return version_compare( get_bloginfo( 'version' ), $version, '>=' );
606 }
607
608 /**
609 * Combines attributes into a string for a form element.
610 *
611 * @since 1.1.0
612 * @param array $attrs Attributes to concatenate.
613 * @param array $attr_exclude Attributes that should NOT be concatenated.
614 * @return string String of attributes for form element.
615 */
616 public static function concat_attrs( $attrs, $attr_exclude = array() ) {
617 $attr_exclude[] = 'rendered';
618 $attr_exclude[] = 'js_dependencies';
619
620 $attributes = '';
621 foreach ( $attrs as $attr => $val ) {
622 $excluded = in_array( $attr, (array) $attr_exclude, true );
623 $empty = false === $val && 'value' !== $attr;
624 if ( ! $excluded && ! $empty ) {
625 $val = is_array( $val ) ? implode( ',', $val ) : $val;
626
627 // if data attribute, use single quote wraps, else double.
628 $quotes = self::is_data_attribute( $attr ) ? "'" : '"';
629 $attributes .= sprintf( ' %1$s=%3$s%2$s%3$s', $attr, $val, $quotes );
630 }
631 }
632 return $attributes;
633 }
634
635 /**
636 * Check if given attribute is a data attribute.
637 *
638 * @since 2.2.5
639 *
640 * @param string $att HTML attribute.
641 * @return boolean
642 */
643 public static function is_data_attribute( $att ) {
644 return 0 === stripos( $att, 'data-' );
645 }
646
647 /**
648 * Ensures value is an array.
649 *
650 * @since 2.2.3
651 *
652 * @param mixed $value Value to ensure is array.
653 * @param array $default Default array. Defaults to empty array.
654 *
655 * @return array The array.
656 */
657 public static function ensure_array( $value, $default = array() ) {
658 if ( empty( $value ) ) {
659 return $default;
660 }
661
662 if ( is_array( $value ) || is_object( $value ) ) {
663 return (array) $value;
664 }
665
666 // Not sure anything would be non-scalar that is not an array or object?
667 if ( ! is_scalar( $value ) ) {
668 return $default;
669 }
670
671 return (array) $value;
672 }
673
674 /**
675 * If number is numeric, normalize it with floatval or intval, depending on if decimal is found.
676 *
677 * @since 2.2.6
678 *
679 * @param mixed $value Value to normalize (if numeric).
680 * @return mixed Possibly normalized value.
681 */
682 public static function normalize_if_numeric( $value ) {
683 if ( is_numeric( $value ) ) {
684 $value = false !== strpos( $value, '.' ) ? floatval( $value ) : intval( $value );
685 }
686
687 return $value;
688 }
689
690 /**
691 * Generates a 12 character unique hash from a string.
692 *
693 * @since 2.4.0
694 *
695 * @param string $string String to create a hash from.
696 *
697 * @return string
698 */
699 public static function generate_hash( $string ) {
700 return substr( base_convert( md5( $string ), 16, 32 ), 0, 12 );
701 }
702
703 }
704