PluginProbe
Media Cloud Sync / 1.0.1
Media Cloud Sync v1.0.1
1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 All 34 releases
media-cloud-sync / includes / config / utils.php

utils.php in Media Cloud Sync 1.0.1, at includes/config/utils.php

548 lines 17.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Dudlewebs\WPMCS;
4
5 defined('ABSPATH') || exit;
6
7 class Utils {
8 /**
9 * Check a variable is empty
10 * @since 1.0.0
11 * @param string|integer|array|float
12 * @return boolean
13 */
14 public static function is_empty($var){
15 if (is_array($var)) {
16 return empty($var);
17 } else {
18 return ($var === null || $var === false || $var === '');
19 }
20 }
21
22 /**
23 * Function To get Plugin Specific Wordpress Option
24 * @since 1.0.0
25 * @return array|boolean|string|integer|float|double
26 */
27 public static function get_option($key, $default = false, $meta_name = false, $expire = false){
28 $data = Cache::get_object_cache( $key, false, $meta_name, $expire );
29 return $data == false ? $default : $data;
30 }
31
32 /**
33 * Function To update Plugin Specific Wordpress Option
34 * @since 1.0.0
35 * @return boolean
36 */
37 public static function update_option($key, $options, $meta_name = false, $expire = false){
38 return Cache::set_object_cache( $key, $options, false, $meta_name, $expire );
39 }
40
41 /**
42 * Function To delete Plugin Specific Wordpress Option
43 * @since 1.0.0
44 * @return boolean
45 */
46 public static function delete_option($key, $meta_name = false){
47 return Cache::delete_object_cache( $key, false, $meta_name );
48 }
49
50 /**
51 * Function To get Plugin Specific Wordpress post meta
52 * @since 1.0.0
53 * @return array|boolean|string|integer|float|double
54 */
55 public static function get_meta($post_id, $key, $default = false, $meta_name = false, $expire = false){
56 $data = Cache::get_object_cache( $key, $post_id, $meta_name, $expire );
57 return $data == false ? $default : $data;
58 }
59
60 /**
61 * Function To update Plugin Specific Wordpress post meta
62 * @since 1.0.0
63 * @return boolean
64 */
65 public static function update_meta($post_id, $key, $options, $meta_name = false, $expire = false){
66 return Cache::set_object_cache( $key, $options, $post_id, $meta_name, $expire );
67 }
68
69 /**
70 * Function To delete Plugin Specific Wordpress post meta
71 * @since 1.0.0
72 * @return boolean
73 */
74 public static function delete_meta($post_id, $key, $meta_name = false){
75 return Cache::delete_object_cache( $key, $post_id, $meta_name );
76 }
77
78 /**
79 * Function To get Current credentials
80 * @since 1.0.0
81 * @return array|boolean|string|integer|float|double
82 */
83 public static function get_credentials($option='', $default=false){
84 $current_setttings = self::get_option('credentials',[], Schema::getConstant('GLOBAL_SETTINGS_KEY'));
85 if(isset($current_setttings) && !empty($current_setttings)){
86 if(isset($option) && !empty($option)){
87 if(isset($current_setttings[$option])) {
88 return $current_setttings[$option];
89 } else {
90 return $default;
91 }
92 } else {
93 return $current_setttings;
94 }
95 } else {
96 return $default;
97 }
98 }
99
100 /**
101 * Function To get Current settings
102 * @since 1.0.0
103 * @return array|boolean|string|integer|float|double
104 */
105 public static function get_settings($option='', $default=false){
106 $current_setttings = self::get_option('settings',[], Schema::getConstant('GLOBAL_SETTINGS_KEY'));
107 if(isset($current_setttings) && !empty($current_setttings)){
108 if(isset($option) && !empty($option)){
109 if(isset($current_setttings[$option])) {
110 return $current_setttings[$option];
111 } else {
112 return $default;
113 }
114 } else {
115 return $current_setttings;
116 }
117 } else {
118 return $default;
119 }
120 }
121
122 /**
123 * Function To get Current Service
124 * @since 1.0.0
125 * @return array|boolean|string|integer|float|double
126 */
127 public static function get_service(){
128 $current_service = self::get_credentials('service', '');
129 if(isset($current_service) && !empty($current_service)){
130 return $current_service;
131 } else {
132 return false;
133 }
134 }
135
136 /**
137 * Function To get Current config
138 * @since 1.0.0
139 * @return array|boolean|string|integer|float|double
140 */
141 public static function get_config($option='', $default=false){
142 $current_setttings = self::get_credentials('config',[]);
143 if(isset($current_setttings) && !empty($current_setttings)){
144 if(isset($option) && !empty($option)){
145 if(isset($current_setttings[$option])) {
146 return $current_setttings[$option];
147 } else {
148 return $default;
149 }
150 } else {
151 return $current_setttings;
152 }
153 } else {
154 return $default;
155 }
156 }
157
158 /**
159 * Function to check serving media environment is ok
160 * @since 1.0.0
161 * @return boolean
162 */
163 public static function is_ok_to_serve($attachment_id = false, $check_id = true){
164 return (
165 self::get_service() &&
166 self::get_settings('rewrite_url') &&
167 ( $check_id ? isset($attachment_id) && !empty($attachment_id) : true )
168 );
169 }
170
171 /**
172 * Function to check uploading media environment is ok
173 * @since 1.0.0
174 * @return boolean
175 */
176 public static function is_ok_to_upload($attachment_id = false){
177 return (
178 self::get_service() &&
179 self::get_settings('copy_to_bucket') &&
180 isset($attachment_id) && !empty($attachment_id)
181 );
182 }
183
184 /**
185 * Function To check service is enabled
186 * @since 1.0.0
187 * @return array|boolean|string|integer|float|double
188 */
189 public static function is_service_enabled(){
190 return !!self::get_service();
191 }
192
193 /**
194 * Check whether a file exist in a list of files
195 * @since 1.0.1
196 * @return boolean
197 */
198 public static function check_existing_file_names( $filename, $files ) {
199 $fname = pathinfo( $filename, PATHINFO_FILENAME );
200 $ext = pathinfo( $filename, PATHINFO_EXTENSION );
201
202 // Edge case, file names like `.ext`.
203 if ( empty( $fname ) ) {
204 return false;
205 }
206
207 if ( $ext ) {
208 $ext = ".$ext";
209 }
210
211 $regex = '/^' . preg_quote( $fname ) . '-(?:\d+x\d+|scaled|rotated)' . preg_quote( $ext ) . '$/i';
212
213 foreach ( $files as $file ) {
214 if (
215 preg_match( $regex, wp_basename($file) ) ||
216 $filename == $file
217 ) {
218 return true;
219 }
220 }
221
222 return false;
223 }
224
225 /**
226 * Get Post Meta Data By Query
227 * @since 1.0.0
228 * @return boolean
229 */
230 public static function get_post_meta($post_id, $key, $single=false, $db_query=false){
231 global $wpdb;
232 if(!(!empty($key) || $post_id)) return false;
233
234 if($db_query) {
235 $meta_data = $wpdb->get_row( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id=$post_id AND meta_key='$key'" );
236 if ($wpdb->last_error || null === $meta_data || !isset($meta_data)) {
237 return false;
238 }
239 return $meta_data->meta_value;
240 } else {
241 return get_post_meta( $post_id, $key, $single );
242 }
243 }
244
245 /**
246 * Get Image URL and path from URL
247 * Return Relative URL and Path of an attachment.
248 * @since 1.0.0
249 *
250 */
251 public static function get_attachment_source_path($file) {
252 if ( isset($file) && !empty($file) ) {
253 $uploads = wp_get_upload_dir();
254 $file_path = '';
255 $site_url = site_url('/');
256 $server_base_path = self::get_settings('base_path');
257 if ( $uploads && false === $uploads['error'] ) {
258
259 $uploadDir = substr( $uploads['baseurl'], strpos( $uploads['baseurl'], $site_url ) + strlen($site_url));
260
261 // Get URL and PATH
262 if ( 0 === strpos( $file, $uploads['basedir'] ) || 0 === strpos( $file, $uploads['baseurl'] ) ) { // If URL is full link
263 $file_path = str_replace( $uploads['basedir'], '', $file );
264 $file_path = str_replace( $uploads['baseurl'], '', $file_path ); // Replace if has URl
265 } else if (
266 0 === strpos( $file, str_replace('/','\\', $uploads['basedir'] )) ||
267 0 === strpos( $file, str_replace('\\','/', $uploads['baseurl'] ))
268 ) { // If URL is full link and the url is slash unified (Like: str_replace('/','\\', $dir))
269 $file_path = str_replace( str_replace('/','\\', $uploads['basedir'] ), '', $file );
270 $file_path = str_replace( str_replace('\\','/', $uploads['baseurl'] ), '', $file_path ); // Replace if has URl
271 $file_path = str_replace('\\','/', $file_path );
272 } else if ( false !== strpos( $file, $uploadDir ) ) { //If URL has sub Directory That matches end of base URL(eg: wp-content/uploads)
273 $fileDir = dirname( $file );
274 $start_pos = strpos( $fileDir, $uploadDir ) + strlen($uploadDir);
275 $subDir = substr( $fileDir, $start_pos, strlen($fileDir)); // Find Sub Directory
276 $file_name = wp_basename( $file );
277
278 $file_path = trailingslashit($subDir) . $file_name;
279 } else if($server_base_path && false !== strpos( $file, trailingslashit($server_base_path))) {
280 $fileDir = dirname( $file );
281 $start_pos = strpos( $fileDir, $server_base_path) + strlen($server_base_path);
282 $subDir = substr( $fileDir, $start_pos, strlen($fileDir)); // Find Sub Directory
283 $file_name = wp_basename( $file );
284
285 $file_path = trailingslashit($subDir) . $file_name;
286 } else if(filter_var($file, FILTER_VALIDATE_URL)) {
287 $parsed = parse_url($file);
288 $path = isset($parsed["path"]) ? $parsed["path"] : '';
289 $query = isset($parsed["query"]) ? '?'.$parsed["query"] : '';
290 $file_path = $path. $query;
291 } else {
292 $file_path = $file;
293 }
294
295 return apply_filters( 'wpmcs_get_relative_file_path_from_upload_directory', untrailingslashit(ltrim( $file_path, '/\\' )), $file );
296 }
297 }
298 return false;
299 }
300
301 /**
302 * Check extension is compatible
303 * @since 1.0.0
304 * @return boolean
305 */
306 public static function is_extension_available($path){
307 $settings = self::get_settings();
308 $path_parts = pathinfo($path);
309
310 if(!isset($path_parts['basename']) || !isset($path_parts['extension'])) return false;
311
312 $alowed = isset($settings['extensions_include']) ? $settings['extensions_include'] : [];
313 $not_allowed = isset($settings['extensions_exclude']) ? $settings['extensions_exclude'] : [];
314
315 if(
316 (in_array($path_parts['extension'], $not_allowed)) ||
317 (!empty($alowed) && !in_array($path_parts['extension'], $alowed))
318 ) {
319 return false;
320 }
321
322 $type_and_ext = wp_check_filetype_and_ext($path, $path_parts['basename']);
323 $ext = empty( $type_and_ext['ext'] ) ? '' : $type_and_ext['ext'];
324 $type = empty( $type_and_ext['type'] ) ? '' : $type_and_ext['type'];
325
326 if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
327 return false;
328 }
329
330 return true;
331 }
332
333 /**
334 * Generate prefix for object versioning
335 * @since 1.0.0
336 * @return string
337 */
338 public static function generate_object_versioning_prefix(){
339 $year_month = self::get_settings('year_month');
340 $date_format = $year_month ? 'dHis' : 'YmdHis';
341
342 // Use current time so that object version is unique
343 $time = current_time('timestamp');
344
345 $object_version = date($date_format, $time) . '/';
346 $object_version = apply_filters('wpmcs_object_version_prefix', $object_version);
347
348 return $object_version;
349 }
350
351 /**
352 * Generate Key for Objects
353 * @since 1.0.0
354 */
355 public static function generate_object_key($file_name, $prefix) {
356 $upload_path = '';
357 $base_path = self::get_settings('base_path');
358 $year_month = self::get_settings('year_month');
359
360 if(isset($base_path) && !empty($base_path)) {
361 $upload_path.= preg_replace('~/+~', '/',
362 str_replace('\\', '/',
363 trim($base_path," \n\r\t\v\x00\/ ")
364 )
365 );
366 }
367 if(isset($year_month) && $year_month) {
368 $upload_path.= '/'.date("Y/m");
369 }
370
371 return ltrim($upload_path.'/'.$prefix.$file_name, '/');
372 }
373
374 /**
375 * Maybe convert size to string
376 *
377 * @param int $attachment_id
378 * @param mixed $size
379 *
380 * @return null|string
381 */
382 public static function maybe_convert_size_to_string( $attachment_id, $size ) {
383 if ( is_array( $size ) ) {
384 $width = ( isset( $size[0] ) && $size[0] > 0 ) ? $size[0] : 1;
385 $height = ( isset( $size[1] ) && $size[1] > 0 ) ? $size[1] : 1;
386 $original_aspect_ratio = $width / $height;
387 $meta = wp_get_attachment_metadata( $attachment_id );
388
389 if ( ! isset( $meta['sizes'] ) || empty( $meta['sizes'] ) ) {
390 return false;
391 }
392
393 $sizes = $meta['sizes'];
394 uasort( $sizes, function ( $a, $b ) {
395 // Order by image area
396 return ( $a['width'] * $a['height'] ) - ( $b['width'] * $b['height'] );
397 } );
398
399 $near_matches = array();
400
401 foreach ( $sizes as $size => $value ) {
402 if ( $width > $value['width'] || $height > $value['height'] ) {
403 continue;
404 }
405 $aspect_ratio = $value['width'] / $value['height'];
406 if ( $aspect_ratio === $original_aspect_ratio ) {
407 return $size;
408 }
409 $near_matches[] = $size;
410 }
411 // Return nearest match
412 if ( ! empty( $near_matches ) ) {
413 return $near_matches[0];
414 }
415 }
416
417 return $size;
418 }
419
420 /**
421 * Reduce the given URL down to the simplest version of itself.
422 *
423 * Useful for matching against the full version of the URL in a full-text search
424 * or saving as a key for dictionary type lookup.
425 *
426 * @param string $url
427 *
428 * @return string
429 */
430 public static function reduce_url( $url ) {
431 $parts = static::parse_url( $url );
432 $host = isset( $parts['host'] ) ? $parts['host'] : '';
433 $port = isset( $parts['port'] ) ? ":{$parts['port']}" : '';
434 $path = isset( $parts['path'] ) ? $parts['path'] : '';
435
436 return '//' . $host . $port . $path;
437 }
438
439 /**
440 * Remove scheme from URL.
441 *
442 * @param string $url
443 * @return string
444 */
445 public static function remove_scheme( $url ) {
446 return preg_replace( '/^(?:http|https):/', '', $url );
447 }
448
449 /**
450 * Remove size from filename (image[-100x100].jpeg).
451 *
452 * @param string $url
453 * @param bool $remove_extension
454 *
455 * @return string
456 */
457 public static function remove_size_from_filename( $url, $remove_extension = false ) {
458 $url = preg_replace( '/^(\S+)-[0-9]{1,4}x[0-9]{1,4}(\.[a-zA-Z0-9\.]{2,})?/', '$1$2', $url );
459
460 $url = apply_filters( 'wpmcs_remove_size_from_filename', $url );
461
462 if ( $remove_extension ) {
463 $ext = pathinfo( $url, PATHINFO_EXTENSION );
464 $url = str_replace( ".$ext", '', $url );
465 }
466
467 return $url;
468 }
469
470 /**
471 * Is the string a URL?
472 *
473 * @param mixed $string
474 *
475 * @return bool
476 */
477 public static function is_url( $string ): bool {
478 if ( empty( $string ) || ! is_string( $string ) ) {
479 return false;
480 }
481
482 if ( preg_match( '@^(?:https?:)?//[a-zA-Z0-9\-]+@', $string ) ) {
483 return true;
484 }
485
486 return false;
487 }
488
489 /**
490 * Parses a URL into its components. Compatible with PHP < 5.4.7.
491 *
492 * @param string $url The URL to parse.
493 *
494 * @param int $component PHP_URL_ constant for URL component to return.
495 *
496 * @return mixed An array of the parsed components, mixed for a requested component, or false on error.
497 */
498 public static function parse_url( $url, $component = -1 ) {
499 $url = trim( $url );
500 $no_scheme = 0 === strpos( $url, '//' );
501
502 if ( $no_scheme ) {
503 $url = 'http:' . $url;
504 }
505
506 $parts = parse_url( $url, $component );
507
508 if ( 0 < $component ) {
509 return $parts;
510 }
511
512 if ( $no_scheme && is_array( $parts ) ) {
513 unset( $parts['scheme'] );
514 }
515
516 return $parts;
517 }
518
519 /**
520 * Is the given string a usable URL?
521 *
522 * We need URLs that include at least a domain and filename with extension
523 * for URL rewriting in either direction.
524 *
525 * @param mixed $url
526 *
527 * @return bool
528 */
529 public static function is_file_url( $url ): bool {
530 if ( ! static::is_url( $url ) ) {
531 return false;
532 }
533
534 $parts = static::parse_url( $url );
535
536 if (
537 empty( $parts['host'] ) ||
538 empty( $parts['path'] ) ||
539 ! pathinfo( $parts['path'], PATHINFO_EXTENSION )
540 ) {
541 return false;
542 }
543
544 return true;
545 }
546
547 }
548