PluginProbe
Media Cloud Sync / 1.2.6
Media Cloud Sync v1.2.6
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.2.6, at includes/config/utils.php

632 lines 20.7 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 statuses
124 * @since 1.0.0
125 * @return array|boolean|string|integer|float|double
126 */
127 public static function get_status($option='', $default=false){
128 $current_setttings = self::get_option('status',[], Schema::getConstant('STATUS_KEY'));
129 if(isset($current_setttings) && !empty($current_setttings)){
130 if(isset($option) && !empty($option)){
131 if(isset($current_setttings[$option])) {
132 return $current_setttings[$option];
133 } else {
134 return $default;
135 }
136 } else {
137 return $current_setttings;
138 }
139 } else {
140 return $default;
141 }
142 }
143
144 /**
145 * Function To set statuses
146 * @since 1.0.0
147 *
148 */
149 public static function set_status($option='', $data=[]){
150 $current_setttings = self::get_option('status',[], Schema::getConstant('STATUS_KEY'));
151 if(isset($option) && !empty($option)){
152 $current_setttings[$option] = $data;
153 return self::update_option('status', $current_setttings, Schema::getConstant('STATUS_KEY'));
154 } else {
155 return false;
156 }
157 }
158
159 /**
160 * Function To get Current Service
161 * @since 1.0.0
162 * @return array|boolean|string|integer|float|double
163 */
164 public static function get_service(){
165 $current_service = self::get_credentials('service', '');
166 if(isset($current_service) && !empty($current_service)){
167 return $current_service;
168 } else {
169 return false;
170 }
171 }
172
173 /**
174 * Function To get Current config
175 * @since 1.0.0
176 * @return array|boolean|string|integer|float|double
177 */
178 public static function get_config($option='', $default=false){
179 $current_setttings = self::get_credentials('config',[]);
180 if(isset($current_setttings) && !empty($current_setttings)){
181 if(isset($option) && !empty($option)){
182 if(isset($current_setttings[$option])) {
183 return $current_setttings[$option];
184 } else {
185 return $default;
186 }
187 } else {
188 return $current_setttings;
189 }
190 } else {
191 return $default;
192 }
193 }
194
195 /**
196 * Function to check serving media environment is ok
197 * @since 1.0.0
198 * @return boolean
199 */
200 public static function is_ok_to_serve($attachment_id = false, $check_id = true){
201 return (
202 self::get_service() &&
203 self::get_settings('rewrite_url') &&
204 ( $check_id ? isset($attachment_id) && !empty($attachment_id) : true )
205 );
206 }
207
208 /**
209 * Function to check uploading media environment is ok
210 * @since 1.0.0
211 * @return boolean
212 */
213 public static function is_ok_to_upload($attachment_id = false){
214 return (
215 self::get_service() &&
216 self::get_settings('copy_to_bucket') &&
217 isset($attachment_id) && !empty($attachment_id)
218 );
219 }
220
221 /**
222 * Function To check service is enabled
223 * @since 1.0.0
224 * @return array|boolean|string|integer|float|double
225 */
226 public static function is_service_enabled(){
227 return !!self::get_service();
228 }
229
230 /**
231 * Check whether a file exist in a list of files
232 * @since 1.0.1
233 * @return boolean
234 */
235 public static function check_existing_file_names( $filename, $files ) {
236 $fname = pathinfo( $filename, PATHINFO_FILENAME );
237 $ext = pathinfo( $filename, PATHINFO_EXTENSION );
238
239 // Edge case, file names like `.ext`.
240 if ( empty( $fname ) ) {
241 return false;
242 }
243
244 if ( $ext ) {
245 $ext = ".$ext";
246 }
247
248 $regex = '/^' . preg_quote( $fname ) . '-(?:\d+x\d+|scaled|rotated)' . preg_quote( $ext ) . '$/i';
249
250 foreach ( $files as $file ) {
251 if (
252 preg_match( $regex, wp_basename($file) ) ||
253 $filename == $file
254 ) {
255 return true;
256 }
257 }
258
259 return false;
260 }
261
262 /**
263 * Get Post Meta Data By Query
264 * @since 1.0.0
265 * @return boolean
266 */
267 public static function get_post_meta($post_id, $key, $single=false, $db_query=false){
268 global $wpdb;
269 if(!(!empty($key) || $post_id)) return false;
270
271 if($db_query) {
272 $meta_data = $wpdb->get_row( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id=$post_id AND meta_key='$key'" );
273 if ($wpdb->last_error || null === $meta_data || !isset($meta_data)) {
274 return false;
275 }
276 return $meta_data->meta_value;
277 } else {
278 return get_post_meta( $post_id, $key, $single );
279 }
280 }
281
282 /**
283 * Get Image URL and path from URL
284 * Return Relative URL and Path of an attachment.
285 * @since 1.0.0
286 *
287 */
288 public static function get_attachment_source_path($file) {
289 if ( isset($file) && !empty($file) ) {
290 $uploads = wp_get_upload_dir();
291 $file_path = '';
292 $site_url = site_url('/');
293 $enable_base_path = self::get_settings('enable_base_path', true);
294 $server_base_path = self::get_settings('base_path', 'wp-content/uploads');
295 if ( $uploads && false === $uploads['error'] ) {
296
297 $uploadDir = substr( $uploads['baseurl'], strpos( $uploads['baseurl'], $site_url ) + strlen($site_url));
298
299 // Get URL and PATH
300 if ( 0 === strpos( $file, $uploads['basedir'] ) || 0 === strpos( $file, $uploads['baseurl'] ) ) { // If URL is full link
301 $file_path = str_replace( $uploads['basedir'], '', $file );
302 $file_path = str_replace( $uploads['baseurl'], '', $file_path ); // Replace if has URl
303 } else if (
304 0 === strpos( $file, str_replace('/','\\', $uploads['basedir'] )) ||
305 0 === strpos( $file, str_replace('\\','/', $uploads['baseurl'] ))
306 ) { // If URL is full link and the url is slash unified (Like: str_replace('/','\\', $dir))
307 $file_path = str_replace( str_replace('/','\\', $uploads['basedir'] ), '', $file );
308 $file_path = str_replace( str_replace('\\','/', $uploads['baseurl'] ), '', $file_path ); // Replace if has URl
309 $file_path = str_replace('\\','/', $file_path );
310 } else if ( false !== strpos( $file, $uploadDir ) ) { //If URL has sub Directory That matches end of base URL(eg: wp-content/uploads)
311 $fileDir = dirname( $file );
312 $start_pos = strpos( $fileDir, $uploadDir ) + strlen($uploadDir);
313 $subDir = substr( $fileDir, $start_pos, strlen($fileDir)); // Find Sub Directory
314 $file_name = wp_basename( $file );
315
316 $file_path = trailingslashit($subDir) . $file_name;
317 } else if($enable_base_path && $server_base_path && false !== strpos( $file, trailingslashit($server_base_path))) {
318 $fileDir = dirname( $file );
319 $start_pos = strpos( $fileDir, $server_base_path) + strlen($server_base_path);
320 $subDir = substr( $fileDir, $start_pos, strlen($fileDir)); // Find Sub Directory
321 $file_name = wp_basename( $file );
322
323 $file_path = trailingslashit($subDir) . $file_name;
324 } else if(filter_var($file, FILTER_VALIDATE_URL)) {
325 $parsed = parse_url($file);
326 $path = isset($parsed["path"]) ? $parsed["path"] : '';
327 $query = isset($parsed["query"]) ? '?'.$parsed["query"] : '';
328 $file_path = $path. $query;
329 } else {
330 $file_path = $file;
331 }
332
333 return apply_filters( 'wpmcs_get_relative_file_path_from_upload_directory', untrailingslashit(ltrim( $file_path, '/\\' )), $file );
334 }
335 }
336 return false;
337 }
338
339 /**
340 * Check extension is compatible
341 * @since 1.0.0
342 * @return boolean
343 */
344 public static function is_extension_available($path){
345 $settings = self::get_settings();
346 $path_parts = pathinfo($path);
347
348 if(!isset($path_parts['basename']) || !isset($path_parts['extension'])) return false;
349
350 $alowed = isset($settings['extensions_include']) ? $settings['extensions_include'] : [];
351 $not_allowed = isset($settings['extensions_exclude']) ? $settings['extensions_exclude'] : [];
352
353 if(
354 (in_array($path_parts['extension'], $not_allowed)) ||
355 (!empty($alowed) && !in_array($path_parts['extension'], $alowed))
356 ) {
357 return false;
358 }
359
360 $type_and_ext = wp_check_filetype_and_ext($path, $path_parts['basename']);
361 $ext = empty( $type_and_ext['ext'] ) ? '' : $type_and_ext['ext'];
362 $type = empty( $type_and_ext['type'] ) ? '' : $type_and_ext['type'];
363
364 if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
365 return false;
366 }
367
368 return true;
369 }
370
371 /**
372 * Generate prefix for object versioning
373 * @since 1.0.0
374 * @return string
375 */
376 public static function generate_object_versioning_prefix(){
377 $year_month = self::get_settings('year_month');
378 $date_format = $year_month ? 'dHis' : 'YmdHis';
379
380 // Use current time so that object version is unique
381 $time = current_time('timestamp');
382
383 $object_version = date($date_format, $time) . '/';
384 $object_version = apply_filters('wpmcs_object_version_prefix', $object_version);
385
386 return $object_version;
387 }
388
389 /**
390 * Generate Key for Objects
391 * @since 1.0.0
392 */
393 /**
394 * Generate Key for Objects
395 * @since 1.0.0
396 */
397 public static function generate_object_key($media_path, $prefix) {
398 $upload_path = '';
399 $enable_base_path = self::get_settings('enable_base_path', true);
400 $base_path = self::get_settings('base_path', 'wp-content/uploads');
401 $year_month = self::get_settings('year_month', true);
402 $media_path = ltrim( $media_path, '/' );
403 $file_name = wp_basename( $media_path );
404
405 if(!$enable_base_path) { // If base path is not enabled
406 $base_path = '';
407 }
408
409 $keep_original_folder_structure = apply_filters( 'wpmcs_keep_original_folder_structure', false );
410
411 if(isset($base_path) && !empty($base_path)) {
412 $upload_path.= preg_replace('~/+~', '/',
413 str_replace('\\', '/',
414 trim($base_path," \n\r\t\v\x00\/ ")
415 )
416 );
417 }
418
419 if($keep_original_folder_structure) {
420 $object_key = ltrim($upload_path . '/' . dirname( $media_path ) . '/' . $prefix . $file_name, '/');
421 } else {
422 if(isset($year_month) && $year_month) {
423 $year_month_prefix = self::get_year_month_from_file_path($media_path);
424 if($year_month_prefix) {
425 $upload_path.= '/'.$year_month_prefix;
426 } else {
427 $upload_path.= '/'.date("Y/m");
428 }
429 }
430
431 $object_key = ltrim($upload_path.'/'.$prefix.$file_name, '/');
432 }
433
434 return apply_filters( 'wpmcs_object_key', $object_key, $media_path, $prefix );
435 }
436
437
438 /**
439 * Check if a file path or URL follows the year/month structure and return the year/month as a string.
440 *
441 * @param string $path_or_url The relative path, absolute path, or URL to check.
442 * @return string|false The year/month string if valid, false otherwise.
443 */
444 public static function get_year_month_from_file_path( $path_or_url ) {
445 // Regex pattern to match paths and URLs containing 'YYYY/MM/' at any depth, allowing subdirectories afterward
446 $pattern = '#(?:^|/)(\d{4})/(0[1-9]|1[0-2])/[^/]+(?:/[^/]+)*$#';
447
448 // Check if the input matches the pattern
449 if ( preg_match( $pattern, $path_or_url, $matches ) ) {
450 // Return the year/month as a string in the format 'YYYY/MM'
451 return $matches[1] . '/' . $matches[2];
452 }
453
454 return false; // Invalid format
455 }
456
457
458 /**
459 * Maybe convert size to string
460 *
461 * @param int $attachment_id
462 * @param mixed $size
463 *
464 * @return null|string
465 */
466 public static function maybe_convert_size_to_string( $attachment_id, $size ) {
467 if ( is_array( $size ) ) {
468 $width = ( isset( $size[0] ) && $size[0] > 0 ) ? $size[0] : 1;
469 $height = ( isset( $size[1] ) && $size[1] > 0 ) ? $size[1] : 1;
470 $original_aspect_ratio = $width / $height;
471 $meta = wp_get_attachment_metadata( $attachment_id );
472
473 if ( ! isset( $meta['sizes'] ) || empty( $meta['sizes'] ) ) {
474 return false;
475 }
476
477 $sizes = $meta['sizes'];
478 uasort( $sizes, function ( $a, $b ) {
479 // Order by image area
480 return ( $a['width'] * $a['height'] ) - ( $b['width'] * $b['height'] );
481 } );
482
483 $near_matches = array();
484
485 foreach ( $sizes as $size => $value ) {
486 if ( $width > $value['width'] || $height > $value['height'] ) {
487 continue;
488 }
489 $aspect_ratio = $value['width'] / $value['height'];
490 if ( $aspect_ratio === $original_aspect_ratio ) {
491 return $size;
492 }
493 $near_matches[] = $size;
494 }
495 // Return nearest match
496 if ( ! empty( $near_matches ) ) {
497 return $near_matches[0];
498 }
499 }
500
501 return $size;
502 }
503
504 /**
505 * Reduce the given URL down to the simplest version of itself.
506 *
507 * Useful for matching against the full version of the URL in a full-text search
508 * or saving as a key for dictionary type lookup.
509 *
510 * @param string $url
511 *
512 * @return string
513 */
514 public static function reduce_url( $url ) {
515 $parts = static::parse_url( $url );
516 $host = isset( $parts['host'] ) ? $parts['host'] : '';
517 $port = isset( $parts['port'] ) ? ":{$parts['port']}" : '';
518 $path = isset( $parts['path'] ) ? $parts['path'] : '';
519
520 return '//' . $host . $port . $path;
521 }
522
523 /**
524 * Remove scheme from URL.
525 *
526 * @param string $url
527 * @return string
528 */
529 public static function remove_scheme( $url ) {
530 return preg_replace( '/^(?:http|https):/', '', $url );
531 }
532
533 /**
534 * Remove size from filename (image[-100x100].jpeg).
535 *
536 * @param string $url
537 * @param bool $remove_extension
538 *
539 * @return string
540 */
541 public static function remove_size_from_filename( $url, $remove_extension = false ) {
542 $url = preg_replace( '/^(\S+)-[0-9]{1,4}x[0-9]{1,4}(\.[a-zA-Z0-9\.]{2,})?/', '$1$2', $url );
543
544 $url = apply_filters( 'wpmcs_remove_size_from_filename', $url );
545
546 if ( $remove_extension ) {
547 $ext = pathinfo( $url, PATHINFO_EXTENSION );
548 $url = str_replace( ".$ext", '', $url );
549 }
550
551 return $url;
552 }
553
554 /**
555 * Is the string a URL?
556 *
557 * @param mixed $string
558 *
559 * @return bool
560 */
561 public static function is_url( $string ): bool {
562 if ( empty( $string ) || ! is_string( $string ) ) {
563 return false;
564 }
565
566 if ( preg_match( '@^(?:https?:)?//[a-zA-Z0-9\-]+@', $string ) ) {
567 return true;
568 }
569
570 return false;
571 }
572
573 /**
574 * Parses a URL into its components. Compatible with PHP < 5.4.7.
575 *
576 * @param string $url The URL to parse.
577 *
578 * @param int $component PHP_URL_ constant for URL component to return.
579 *
580 * @return mixed An array of the parsed components, mixed for a requested component, or false on error.
581 */
582 public static function parse_url( $url, $component = -1 ) {
583 $url = trim( $url );
584 $no_scheme = 0 === strpos( $url, '//' );
585
586 if ( $no_scheme ) {
587 $url = 'http:' . $url;
588 }
589
590 $parts = parse_url( $url, $component );
591
592 if ( 0 < $component ) {
593 return $parts;
594 }
595
596 if ( $no_scheme && is_array( $parts ) ) {
597 unset( $parts['scheme'] );
598 }
599
600 return $parts;
601 }
602
603 /**
604 * Is the given string a usable URL?
605 *
606 * We need URLs that include at least a domain and filename with extension
607 * for URL rewriting in either direction.
608 *
609 * @param mixed $url
610 *
611 * @return bool
612 */
613 public static function is_file_url( $url ): bool {
614 if ( ! static::is_url( $url ) ) {
615 return false;
616 }
617
618 $parts = static::parse_url( $url );
619
620 if (
621 empty( $parts['host'] ) ||
622 empty( $parts['path'] ) ||
623 ! pathinfo( $parts['path'], PATHINFO_EXTENSION )
624 ) {
625 return false;
626 }
627
628 return true;
629 }
630
631 }
632