PluginProbe
GamiPress – Gamification plugin to reward points, badges & ranks in WordPress, now with AI / 7.9.8
GamiPress – Gamification plugin to reward points, badges & ranks in WordPress, now with AI v7.9.8
8.0.4 8.0.3 8.0.1 8.0.2 8.0.0 7.9.9.7 7.9.9.6 7.9.9.5 7.9.9.4 7.9.9.3 7.9.9.2 7.9.9.1 7.9.9 7.9.8 7.9.7 7.9.6 7.9.5 7.9.4 7.9.3 7.9.2 7.9.1 7.9.0 7.8.9 7.8.8 7.8.7 All 46 releases
gamipress / libraries / cmb2 / includes / CMB2_Utils.php

CMB2_Utils.php in GamiPress – Gamification plugin to reward points, badges & ranks in WordPress, now with AI 7.9.8, at libraries/cmb2/includes/CMB2_Utils.php

699 lines 20.8 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 $valid = self::is_valid_time_stamp( $string );
262 if ( $valid ) {
263 $timestamp = (int) $string;
264 $length = strlen( (string) $timestamp );
265 $unixlength = strlen( (string) time() );
266 $diff = $length - $unixlength;
267
268 // If value is larger than a unix timestamp, we need to round to the
269 // nearest unix timestamp (in seconds).
270 if ( $diff > 0 ) {
271 $divider = (int) '1' . str_repeat( '0', $diff );
272 $timestamp = round( $timestamp / $divider );
273 }
274 } else {
275 $timestamp = @strtotime( (string) $string );
276 }
277
278 return $timestamp;
279 }
280
281 /**
282 * Determine if a value is a valid date.
283 *
284 * @since 2.9.1
285 * @param mixed $date Value to check.
286 * @return boolean Whether value is a valid date
287 */
288 public static function is_valid_date( $date ) {
289 return ( is_string( $date ) && @strtotime( $date ) )
290 || self::is_valid_time_stamp( $date );
291 }
292
293 /**
294 * Determine if a value is a valid timestamp
295 *
296 * @since 2.0.0
297 * @param mixed $timestamp Value to check.
298 * @return boolean Whether value is a valid timestamp
299 */
300 public static function is_valid_time_stamp( $timestamp ) {
301 return (string) (int) $timestamp === (string) $timestamp
302 && $timestamp <= PHP_INT_MAX
303 && $timestamp >= ~PHP_INT_MAX;
304 }
305
306 /**
307 * Checks if a value is 'empty'. Still accepts 0.
308 *
309 * @since 2.0.0
310 * @param mixed $value Value to check.
311 * @return bool True or false
312 */
313 public static function isempty( $value ) {
314 return null === $value || '' === $value || false === $value || array() === $value;
315 }
316
317 /**
318 * Checks if a value is not 'empty'. 0 doesn't count as empty.
319 *
320 * @since 2.2.2
321 * @param mixed $value Value to check.
322 * @return bool True or false
323 */
324 public static function notempty( $value ) {
325 return null !== $value && '' !== $value && false !== $value && array() !== $value;
326 }
327
328 /**
329 * Filters out empty values (not including 0).
330 *
331 * @since 2.2.2
332 * @param mixed $value Value to check.
333 * @return array True or false.
334 */
335 public static function filter_empty( $value ) {
336 return array_filter( $value, array( __CLASS__, 'notempty' ) );
337 }
338
339 /**
340 * Insert a single array item inside another array at a set position
341 *
342 * @since 2.0.2
343 * @param array $array Array to modify. Is passed by reference, and no return is needed. Passed by reference.
344 * @param array $new New array to insert.
345 * @param int $position Position in the main array to insert the new array.
346 */
347 public static function array_insert( &$array, $new, $position ) {
348 $before = array_slice( $array, 0, $position - 1 );
349 $after = array_diff_key( $array, $before );
350 $array = array_merge( $before, $new, $after );
351 }
352
353 /**
354 * Defines the url which is used to load local resources.
355 * This may need to be filtered for local Window installations.
356 * If resources do not load, please check the wiki for details.
357 *
358 * @since 1.0.1
359 *
360 * @param string $path URL path.
361 * @return string URL to CMB2 resources
362 */
363 public static function url( $path = '' ) {
364 if ( self::$url ) {
365 return self::$url . $path;
366 }
367
368 $cmb2_url = self::get_url_from_dir( cmb2_dir() );
369
370 /**
371 * Filter the CMB location url.
372 *
373 * @param string $cmb2_url Currently registered url.
374 */
375 self::$url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) );
376
377 return self::$url . $path;
378 }
379
380 /**
381 * Converts a system path to a URL
382 *
383 * @since 2.2.2
384 * @param string $dir Directory path to convert.
385 * @return string Converted URL.
386 */
387 public static function get_url_from_dir( $dir ) {
388 $dir = self::normalize_path( $dir );
389
390 // Let's test if We are in the plugins or mu-plugins dir.
391 $test_dir = trailingslashit( $dir ) . 'unneeded.php';
392 if (
393 0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) )
394 || 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) )
395 ) {
396 // Ok, then use plugins_url, as it is more reliable.
397 return trailingslashit( plugins_url( '', $test_dir ) );
398 }
399
400 // Ok, now let's test if we are in the theme dir.
401 $theme_root = self::normalize_path( get_theme_root() );
402 if ( 0 === strpos( $dir, $theme_root ) ) {
403 // Ok, then use get_theme_root_uri.
404 return set_url_scheme(
405 trailingslashit(
406 str_replace(
407 untrailingslashit( $theme_root ),
408 untrailingslashit( get_theme_root_uri() ),
409 $dir
410 )
411 )
412 );
413 }
414
415 // Check to see if it's anywhere in the root directory.
416 $site_dir = self::get_normalized_abspath();
417 $site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() );
418
419 $url = str_replace(
420 array( $site_dir, WP_PLUGIN_DIR ),
421 array( $site_url, WP_PLUGIN_URL ),
422 $dir
423 );
424
425 return set_url_scheme( $url );
426 }
427
428 /**
429 * Get the normalized absolute path defined by WordPress.
430 *
431 * @since 2.2.6
432 *
433 * @return string Normalized absolute path.
434 */
435 protected static function get_normalized_abspath() {
436 return self::normalize_path( self::$ABSPATH );
437 }
438
439 /**
440 * `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path.
441 *
442 * On windows systems, replaces backslashes with forward slashes
443 * and forces upper-case drive letters.
444 * Allows for two leading slashes for Windows network shares, but
445 * ensures that all other duplicate slashes are reduced to a single.
446 *
447 * @since 2.2.0
448 *
449 * @param string $path Path to normalize.
450 * @return string Normalized path.
451 */
452 protected static function normalize_path( $path ) {
453 if ( function_exists( 'wp_normalize_path' ) ) {
454 return wp_normalize_path( $path );
455 }
456
457 // Replace newer WP's version of wp_normalize_path.
458 $path = str_replace( '\\', '/', $path );
459 $path = preg_replace( '|(?<=.)/+|', '/', $path );
460 if ( ':' === substr( $path, 1, 1 ) ) {
461 $path = ucfirst( $path );
462 }
463
464 return $path;
465 }
466
467 /**
468 * Get timestamp from text date
469 *
470 * @since 2.2.0
471 * @param string $value Date value.
472 * @param string $date_format Expected date format.
473 * @return mixed Unix timestamp representing the date.
474 */
475 public static function get_timestamp_from_value( $value, $date_format ) {
476 $date_object = date_create_from_format( $date_format, $value );
477 return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value );
478 }
479
480 /**
481 * Takes a php date() format string and returns a string formatted to suit for the date/time pickers
482 * It will work only with the following subset of date() options:
483 *
484 * Formats: d, l, j, z, m, F, n, y, and Y.
485 *
486 * A slight effort is made to deal with escaped characters.
487 *
488 * Other options are ignored, because they would either bring compatibility problems between PHP and JS, or
489 * bring even more translation troubles.
490 *
491 * @since 2.2.0
492 * @param string $format PHP date format.
493 * @return string reformatted string
494 */
495 public static function php_to_js_dateformat( $format ) {
496
497 // order is relevant here, since the replacement will be done sequentially.
498 $supported_options = array(
499 'd' => 'dd', // Day, leading 0.
500 'j' => 'd', // Day, no 0.
501 'z' => 'o', // Day of the year, no leading zeroes.
502 // 'D' => 'D', // Day name short, not sure how it'll work with translations.
503 'l ' => 'DD ', // Day name full, idem before.
504 'l, ' => 'DD, ', // Day name full, idem before.
505 'm' => 'mm', // Month of the year, leading 0.
506 'n' => 'm', // Month of the year, no leading 0.
507 // 'M' => 'M', // Month, Short name.
508 'F ' => 'MM ', // Month, full name.
509 'F, ' => 'MM, ', // Month, full name.
510 'y' => 'y', // Year, two digit.
511 'Y' => 'yy', // Year, full.
512 'H' => 'HH', // Hour with leading 0 (24 hour).
513 'G' => 'H', // Hour with no leading 0 (24 hour).
514 'h' => 'hh', // Hour with leading 0 (12 hour).
515 'g' => 'h', // Hour with no leading 0 (12 hour).
516 'i' => 'mm', // Minute with leading 0.
517 's' => 'ss', // Second with leading 0.
518 'a' => 'tt', // am/pm.
519 'A' => 'TT', // AM/PM.
520 );
521
522 foreach ( $supported_options as $php => $js ) {
523 // replaces every instance of a supported option, but skips escaped characters.
524 $format = preg_replace( "~(?<!\\\\)$php~", $js, $format );
525 }
526
527 $supported_options = array(
528 'l' => 'DD', // Day name full, idem before.
529 'F' => 'MM', // Month, full name.
530 );
531
532 if ( isset( $supported_options[ $format ] ) ) {
533 $format = $supported_options[ $format ];
534 }
535
536 $format = preg_replace_callback( '~(?:\\\.)+~', array( __CLASS__, 'wrap_escaped_chars' ), $format );
537
538 return $format;
539 }
540
541 /**
542 * Helper function for CMB_Utils::php_to_js_dateformat().
543 *
544 * @since 2.2.0
545 * @param string $value Value to wrap/escape.
546 * @return string Modified value
547 */
548 public static function wrap_escaped_chars( $value ) {
549 return '&#39;' . str_replace( '\\', '', $value[0] ) . '&#39;';
550 }
551
552 /**
553 * Send to debug.log if WP_DEBUG is defined and true
554 *
555 * @since 2.2.0
556 *
557 * @param string $function Function name.
558 * @param int $line Line number.
559 * @param mixed $msg Message to output.
560 * @param mixed $debug Variable to print_r.
561 */
562 public static function log_if_debug( $function, $line, $msg, $debug = null ) {
563 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
564 error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) );
565 }
566 }
567
568 /**
569 * Determine a file's extension
570 *
571 * @since 1.0.0
572 * @param string $file File url.
573 * @return string|false File extension or false
574 */
575 public static function get_file_ext( $file ) {
576 $parsed = parse_url( $file, PHP_URL_PATH );
577 return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
578 }
579
580 /**
581 * Get the file name from a url
582 *
583 * @since 2.0.0
584 * @param string $value File url or path.
585 * @return string File name
586 */
587 public static function get_file_name_from_path( $value ) {
588 $parts = explode( '/', $value );
589 return is_array( $parts ) ? end( $parts ) : $value;
590 }
591
592 /**
593 * Check if WP version is at least $version.
594 *
595 * @since 2.2.2
596 * @param string $version WP version string to compare.
597 * @return bool Result of comparison check.
598 */
599 public static function wp_at_least( $version ) {
600 return version_compare( get_bloginfo( 'version' ), $version, '>=' );
601 }
602
603 /**
604 * Combines attributes into a string for a form element.
605 *
606 * @since 1.1.0
607 * @param array $attrs Attributes to concatenate.
608 * @param array $attr_exclude Attributes that should NOT be concatenated.
609 * @return string String of attributes for form element.
610 */
611 public static function concat_attrs( $attrs, $attr_exclude = array() ) {
612 $attr_exclude[] = 'rendered';
613 $attr_exclude[] = 'js_dependencies';
614
615 $attributes = '';
616 foreach ( $attrs as $attr => $val ) {
617 $excluded = in_array( $attr, (array) $attr_exclude, true );
618 $empty = false === $val && 'value' !== $attr;
619 if ( ! $excluded && ! $empty ) {
620 $val = is_array( $val ) ? implode( ',', $val ) : $val;
621
622 // if data attribute, use single quote wraps, else double.
623 $quotes = self::is_data_attribute( $attr ) ? "'" : '"';
624 $attributes .= sprintf( ' %1$s=%3$s%2$s%3$s', $attr, $val, $quotes );
625 }
626 }
627 return $attributes;
628 }
629
630 /**
631 * Check if given attribute is a data attribute.
632 *
633 * @since 2.2.5
634 *
635 * @param string $att HTML attribute.
636 * @return boolean
637 */
638 public static function is_data_attribute( $att ) {
639 return 0 === stripos( $att, 'data-' );
640 }
641
642 /**
643 * Ensures value is an array.
644 *
645 * @since 2.2.3
646 *
647 * @param mixed $value Value to ensure is array.
648 * @param array $default Default array. Defaults to empty array.
649 *
650 * @return array The array.
651 */
652 public static function ensure_array( $value, $default = array() ) {
653 if ( empty( $value ) ) {
654 return $default;
655 }
656
657 if ( is_array( $value ) || is_object( $value ) ) {
658 return (array) $value;
659 }
660
661 // Not sure anything would be non-scalar that is not an array or object?
662 if ( ! is_scalar( $value ) ) {
663 return $default;
664 }
665
666 return (array) $value;
667 }
668
669 /**
670 * If number is numeric, normalize it with floatval or intval, depending on if decimal is found.
671 *
672 * @since 2.2.6
673 *
674 * @param mixed $value Value to normalize (if numeric).
675 * @return mixed Possibly normalized value.
676 */
677 public static function normalize_if_numeric( $value ) {
678 if ( is_numeric( $value ) ) {
679 $value = false !== strpos( $value, '.' ) ? floatval( $value ) : intval( $value );
680 }
681
682 return $value;
683 }
684
685 /**
686 * Generates a 12 character unique hash from a string.
687 *
688 * @since 2.4.0
689 *
690 * @param string $string String to create a hash from.
691 *
692 * @return string
693 */
694 public static function generate_hash( $string ) {
695 return substr( base_convert( md5( $string ), 16, 32 ), 0, 12 );
696 }
697
698 }
699