forked from CMB2/CMB2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CMB2_Utils.php
451 lines (397 loc) · 13.2 KB
/
CMB2_Utils.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
<?php
/**
* CMB2 Utilities
*
* @since 1.1.0
*
* @category WordPress_Plugin
* @package CMB2
* @author WebDevStudios
* @license GPL-2.0+
* @link http://webdevstudios.com
*/
class CMB2_Utils {
/**
* The WordPress ABSPATH constant.
* @var string
* @since 2.2.3
*/
protected static $ABSPATH = ABSPATH;
/**
* The url which is used to load local resources.
* @var string
* @since 2.0.0
*/
protected static $url = '';
/**
* Utility method that attempts to get an attachment's ID by it's url
* @since 1.0.0
* @param string $img_url Attachment url
* @return int|false Attachment ID or false
*/
public static function image_id_from_url( $img_url ) {
$attachment_id = 0;
$dir = wp_upload_dir();
// Is URL in uploads directory?
if ( false === strpos( $img_url, $dir['baseurl'] . '/' ) ) {
return false;
}
$file = basename( $img_url );
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
'key' => '_wp_attachment_metadata',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) {
foreach ( $query->posts as $post_id ) {
$meta = wp_get_attachment_metadata( $post_id );
$original_file = basename( $meta['file'] );
$cropped_image_files = isset( $meta['sizes'] ) ? wp_list_pluck( $meta['sizes'], 'file' ) : array();
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
$attachment_id = $post_id;
break;
}
}
}
return 0 === $attachment_id ? false : $attachment_id;
}
/**
* Utility method that returns time string offset by timezone
* @since 1.0.0
* @param string $tzstring Time string
* @return string Offset time string
*/
public static function timezone_offset( $tzstring ) {
$tz_offset = 0;
if ( ! empty( $tzstring ) && is_string( $tzstring ) ) {
if ( 'UTC' === substr( $tzstring, 0, 3 ) ) {
$tzstring = str_replace( array( ':15', ':30', ':45' ), array( '.25', '.5', '.75' ), $tzstring );
return intval( floatval( substr( $tzstring, 3 ) ) * HOUR_IN_SECONDS );
}
try {
$date_time_zone_selected = new DateTimeZone( $tzstring );
$tz_offset = timezone_offset_get( $date_time_zone_selected, date_create() );
} catch ( Exception $e ) {
self::log_if_debug( __METHOD__, __LINE__, $e->getMessage() );
}
}
return $tz_offset;
}
/**
* Utility method that returns a timezone string representing the default timezone for the site.
*
* Roughly copied from WordPress, as get_option('timezone_string') will return
* an empty string if no value has been set on the options page.
* A timezone string is required by the wp_timezone_choice() used by the
* select_timezone field.
*
* @since 1.0.0
* @return string Timezone string
*/
public static function timezone_string() {
$current_offset = get_option( 'gmt_offset' );
$tzstring = get_option( 'timezone_string' );
// Remove old Etc mappings. Fallback to gmt_offset.
if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
$tzstring = '';
}
if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists
if ( 0 == $current_offset ) {
$tzstring = 'UTC+0';
} elseif ( $current_offset < 0 ) {
$tzstring = 'UTC' . $current_offset;
} else {
$tzstring = 'UTC+' . $current_offset;
}
}
return $tzstring;
}
/**
* Returns a timestamp, first checking if value already is a timestamp.
* @since 2.0.0
* @param string|int $string Possible timestamp string
* @return int Time stamp
*/
public static function make_valid_time_stamp( $string ) {
if ( ! $string ) {
return 0;
}
return self::is_valid_time_stamp( $string )
? (int) $string :
strtotime( (string) $string );
}
/**
* Determine if a value is a valid timestamp
* @since 2.0.0
* @param mixed $timestamp Value to check
* @return boolean Whether value is a valid timestamp
*/
public static function is_valid_time_stamp( $timestamp ) {
return (string) (int) $timestamp === (string) $timestamp
&& $timestamp <= PHP_INT_MAX
&& $timestamp >= ~PHP_INT_MAX;
}
/**
* Checks if a value is 'empty'. Still accepts 0.
* @since 2.0.0
* @param mixed $value Value to check
* @return bool True or false
*/
public static function isempty( $value ) {
return null === $value || '' === $value || false === $value;
}
/**
* Checks if a value is not 'empty'. 0 doesn't count as empty.
* @since 2.2.2
* @param mixed $value Value to check
* @return bool True or false
*/
public static function notempty( $value ){
return null !== $value && '' !== $value && false !== $value;
}
/**
* Filters out empty values (not including 0).
* @since 2.2.2
* @param mixed $value Value to check
* @return bool True or false
*/
public static function filter_empty( $value ) {
return array_filter( $value, array( __CLASS__, 'notempty' ) );
}
/**
* Insert a single array item inside another array at a set position
* @since 2.0.2
* @param array &$array Array to modify. Is passed by reference, and no return is needed.
* @param array $new New array to insert
* @param int $position Position in the main array to insert the new array
*/
public static function array_insert( &$array, $new, $position ) {
$before = array_slice( $array, 0, $position - 1 );
$after = array_diff_key( $array, $before );
$array = array_merge( $before, $new, $after );
}
/**
* Defines the url which is used to load local resources.
* This may need to be filtered for local Window installations.
* If resources do not load, please check the wiki for details.
* @since 1.0.1
* @return string URL to CMB2 resources
*/
public static function url( $path = '' ) {
if ( self::$url ) {
return self::$url . $path;
}
$cmb2_url = self::get_url_from_dir( cmb2_dir() );
/**
* Filter the CMB location url
*
* @param string $cmb2_url Currently registered url
*/
self::$url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) );
return self::$url . $path;
}
/**
* Converts a system path to a URL
* @since 2.2.2
* @param string $dir Directory path to convert.
* @return string Converted URL.
*/
public static function get_url_from_dir( $dir ) {
$dir = self::normalize_path( $dir );
// Let's test if We are in the plugins or mu-plugins dir.
$test_dir = trailingslashit( $dir ) . 'unneeded.php';
if (
0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) )
|| 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) )
) {
// Ok, then use plugins_url, as it is more reliable.
return trailingslashit( plugins_url( '', $test_dir ) );
}
// Ok, now let's test if we are in the theme dir.
$theme_root = self::normalize_path( get_theme_root() );
if ( 0 === strpos( $dir, $theme_root ) ) {
// Ok, then use get_theme_root_uri.
return set_url_scheme(
trailingslashit(
str_replace(
untrailingslashit( $theme_root ),
untrailingslashit( get_theme_root_uri() ),
$dir
)
)
);
}
// Check to see if it's anywhere in the root directory
$site_dir = self::normalize_path( self::$ABSPATH );
$site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() );
$url = str_replace(
array( $site_dir, WP_PLUGIN_DIR ),
array( $site_url, WP_PLUGIN_URL ),
$dir
);
return set_url_scheme( $url );
}
/**
* `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path.
*
* On windows systems, replaces backslashes with forward slashes
* and forces upper-case drive letters.
* Allows for two leading slashes for Windows network shares, but
* ensures that all other duplicate slashes are reduced to a single.
*
* @since 2.2.0
*
* @param string $path Path to normalize.
* @return string Normalized path.
*/
protected static function normalize_path( $path ) {
if ( function_exists( 'wp_normalize_path' ) ) {
return wp_normalize_path( $path );
}
// Replace newer WP's version of wp_normalize_path.
$path = str_replace( '\\', '/', $path );
$path = preg_replace( '|(?<=.)/+|', '/', $path );
if ( ':' === substr( $path, 1, 1 ) ) {
$path = ucfirst( $path );
}
return $path;
}
/**
* Get timestamp from text date
* @since 2.2.0
* @param string $value Date value
* @param string $date_format Expected date format
* @return mixed Unix timestamp representing the date.
*/
public static function get_timestamp_from_value( $value, $date_format ) {
$date_object = date_create_from_format( $date_format, $value );
return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value );
}
/**
* Takes a php date() format string and returns a string formatted to suit for the date/time pickers
* It will work with only with the following subset ot date() options:
*
* d, j, z, m, n, y, and Y.
*
* A slight effort is made to deal with escaped characters.
*
* Other options are ignored, because they would either bring compatibility problems between PHP and JS, or
* bring even more translation troubles.
*
* @since 2.2.0
* @param string $format php date format
* @return string reformatted string
*/
public static function php_to_js_dateformat( $format ) {
// order is relevant here, since the replacement will be done sequentially.
$supported_options = array(
'd' => 'dd', // Day, leading 0
'j' => 'd', // Day, no 0
'z' => 'o', // Day of the year, no leading zeroes,
// 'D' => 'D', // Day name short, not sure how it'll work with translations
// 'l' => 'DD', // Day name full, idem before
'm' => 'mm', // Month of the year, leading 0
'n' => 'm', // Month of the year, no leading 0
// 'M' => 'M', // Month, Short name
// 'F' => 'MM', // Month, full name,
'y' => 'y', // Year, two digit
'Y' => 'yy', // Year, full
'H' => 'HH', // Hour with leading 0 (24 hour)
'G' => 'H', // Hour with no leading 0 (24 hour)
'h' => 'hh', // Hour with leading 0 (12 hour)
'g' => 'h', // Hour with no leading 0 (12 hour),
'i' => 'mm', // Minute with leading 0,
's' => 'ss', // Second with leading 0,
'a' => 'tt', // am/pm
'A' => 'TT' // AM/PM
);
foreach ( $supported_options as $php => $js ) {
// replaces every instance of a supported option, but skips escaped characters
$format = preg_replace( "~(?<!\\\\)$php~", $js, $format );
}
$format = preg_replace_callback( '~(?:\\\.)+~', array( __CLASS__, 'wrap_escaped_chars' ), $format );
return $format;
}
/**
* Helper function for CMB_Utils->php_to_js_dateformat, because php 5.2 was retarded.
* @since 2.2.0
* @param $value Value to wrap/escape
* @return string Modified value
*/
public static function wrap_escaped_chars( $value ) {
return "'" . str_replace( '\\', '', $value[0] ) . "'";
}
/**
* Send to debug.log if WP_DEBUG is defined and true
*
* @since 2.2.0
*
* @param string $function Function name
* @param int $line Line number
* @param mixed $msg Message to output
* @param mixed $debug Variable to print_r
*/
public static function log_if_debug( $function, $line, $msg, $debug = null ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) );
}
}
/**
* Determine a file's extension
* @since 1.0.0
* @param string $file File url
* @return string|false File extension or false
*/
public static function get_file_ext( $file ) {
$parsed = @parse_url( $file, PHP_URL_PATH );
return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
}
/**
* Get the file name from a url
* @since 2.0.0
* @param string $value File url or path
* @return string File name
*/
public static function get_file_name_from_path( $value ) {
$parts = explode( '/', $value );
return is_array( $parts ) ? end( $parts ) : $value;
}
/**
* Check if WP version is at least $version.
* @since 2.2.2
* @param string $version WP version string to compare.
* @return bool Result of comparison check.
*/
public static function wp_at_least( $version ) {
return version_compare( get_bloginfo( 'version' ), $version, '>=' );
}
/**
* Combines attributes into a string for a form element.
* @since 1.1.0
* @param array $attrs Attributes to concatenate.
* @param array $attr_exclude Attributes that should NOT be concatenated.
* @return string String of attributes for form element.
*/
public static function concat_attrs( $attrs, $attr_exclude = array() ) {
$attr_exclude[] = 'rendered';
$attributes = '';
foreach ( $attrs as $attr => $val ) {
$excluded = in_array( $attr, (array) $attr_exclude, true );
$empty = false === $val && 'value' !== $attr;
if ( ! $excluded && ! $empty ) {
// if data attribute, use single quote wraps, else double
$quotes = false !== stripos( $attr, 'data-' ) ? "'" : '"';
$attributes .= sprintf( ' %1$s=%3$s%2$s%3$s', $attr, $val, $quotes );
}
}
return $attributes;
}
}