Completed
Push — trunk ( 7ce277...e61c15 )
by Justin
03:33
created

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