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

595 lines 19.5 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 $enable_base_path = self::get_settings('enable_base_path', true);
257 $server_base_path = self::get_settings('base_path', 'wp-content/uploads');
258 if ( $uploads && false === $uploads['error'] ) {
259
260 $uploadDir = substr( $uploads['baseurl'], strpos( $uploads['baseurl'], $site_url ) + strlen($site_url));
261
262 // Get URL and PATH
263 if ( 0 === strpos( $file, $uploads['basedir'] ) || 0 === strpos( $file, $uploads['baseurl'] ) ) { // If URL is full link
264 $file_path = str_replace( $uploads['basedir'], '', $file );
265 $file_path = str_replace( $uploads['baseurl'], '', $file_path ); // Replace if has URl
266 } else if (
267 0 === strpos( $file, str_replace('/','\\', $uploads['basedir'] )) ||
268 0 === strpos( $file, str_replace('\\','/', $uploads['baseurl'] ))
269 ) { // If URL is full link and the url is slash unified (Like: str_replace('/','\\', $dir))
270 $file_path = str_replace( str_replace('/','\\', $uploads['basedir'] ), '', $file );
271 $file_path = str_replace( str_replace('\\','/', $uploads['baseurl'] ), '', $file_path ); // Replace if has URl
272 $file_path = str_replace('\\','/', $file_path );
273 } else if ( false !== strpos( $file, $uploadDir ) ) { //If URL has sub Directory That matches end of base URL(eg: wp-content/uploads)
274 $fileDir = dirname( $file );
275 $start_pos = strpos( $fileDir, $uploadDir ) + strlen($uploadDir);
276 $subDir = substr( $fileDir, $start_pos, strlen($fileDir)); // Find Sub Directory
277 $file_name = wp_basename( $file );
278
279 $file_path = trailingslashit($subDir) . $file_name;
280 } else if($enable_base_path && $server_base_path && false !== strpos( $file, trailingslashit($server_base_path))) {
281 $fileDir = dirname( $file );
282 $start_pos = strpos( $fileDir, $server_base_path) + strlen($server_base_path);
283 $subDir = substr( $fileDir, $start_pos, strlen($fileDir)); // Find Sub Directory
284 $file_name = wp_basename( $file );
285
286 $file_path = trailingslashit($subDir) . $file_name;
287 } else if(filter_var($file, FILTER_VALIDATE_URL)) {
288 $parsed = parse_url($file);
289 $path = isset($parsed["path"]) ? $parsed["path"] : '';
290 $query = isset($parsed["query"]) ? '?'.$parsed["query"] : '';
291 $file_path = $path. $query;
292 } else {
293 $file_path = $file;
294 }
295
296 return apply_filters( 'wpmcs_get_relative_file_path_from_upload_directory', untrailingslashit(ltrim( $file_path, '/\\' )), $file );
297 }
298 }
299 return false;
300 }
301
302 /**
303 * Check extension is compatible
304 * @since 1.0.0
305 * @return boolean
306 */
307 public static function is_extension_available($path){
308 $settings = self::get_settings();
309 $path_parts = pathinfo($path);
310
311 if(!isset($path_parts['basename']) || !isset($path_parts['extension'])) return false;
312
313 $alowed = isset($settings['extensions_include']) ? $settings['extensions_include'] : [];
314 $not_allowed = isset($settings['extensions_exclude']) ? $settings['extensions_exclude'] : [];
315
316 if(
317 (in_array($path_parts['extension'], $not_allowed)) ||
318 (!empty($alowed) && !in_array($path_parts['extension'], $alowed))
319 ) {
320 return false;
321 }
322
323 $type_and_ext = wp_check_filetype_and_ext($path, $path_parts['basename']);
324 $ext = empty( $type_and_ext['ext'] ) ? '' : $type_and_ext['ext'];
325 $type = empty( $type_and_ext['type'] ) ? '' : $type_and_ext['type'];
326
327 if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
328 return false;
329 }
330
331 return true;
332 }
333
334 /**
335 * Generate prefix for object versioning
336 * @since 1.0.0
337 * @return string
338 */
339 public static function generate_object_versioning_prefix(){
340 $year_month = self::get_settings('year_month');
341 $date_format = $year_month ? 'dHis' : 'YmdHis';
342
343 // Use current time so that object version is unique
344 $time = current_time('timestamp');
345
346 $object_version = date($date_format, $time) . '/';
347 $object_version = apply_filters('wpmcs_object_version_prefix', $object_version);
348
349 return $object_version;
350 }
351
352 /**
353 * Generate Key for Objects
354 * @since 1.0.0
355 */
356 /**
357 * Generate Key for Objects
358 * @since 1.0.0
359 */
360 public static function generate_object_key($media_path, $prefix) {
361 $upload_path = '';
362 $enable_base_path = self::get_settings('enable_base_path', true);
363 $base_path = self::get_settings('base_path', 'wp-content/uploads');
364 $year_month = self::get_settings('year_month', true);
365 $media_path = ltrim( $media_path, '/' );
366 $file_name = wp_basename( $media_path );
367
368 if(!$enable_base_path) { // If base path is not enabled
369 $base_path = '';
370 }
371
372 $keep_original_folder_structure = apply_filters( 'wpmcs_keep_original_folder_structure', false );
373
374 if(isset($base_path) && !empty($base_path)) {
375 $upload_path.= preg_replace('~/+~', '/',
376 str_replace('\\', '/',
377 trim($base_path," \n\r\t\v\x00\/ ")
378 )
379 );
380 }
381
382 if($keep_original_folder_structure) {
383 $object_key = ltrim($upload_path . '/' . dirname( $media_path ) . '/' . $prefix . $file_name, '/');
384 } else {
385 if(isset($year_month) && $year_month) {
386 $year_month_prefix = self::get_year_month_from_file_path($media_path);
387 if($year_month_prefix) {
388 $upload_path.= '/'.$year_month_prefix;
389 } else {
390 $upload_path.= '/'.date("Y/m");
391 }
392 }
393
394 $object_key = ltrim($upload_path.'/'.$prefix.$file_name, '/');
395 }
396
397 return apply_filters( 'wpmcs_object_key', $object_key, $media_path, $prefix );
398 }
399
400
401 /**
402 * Check if a file path or URL follows the year/month structure and return the year/month as a string.
403 *
404 * @param string $path_or_url The relative path, absolute path, or URL to check.
405 * @return string|false The year/month string if valid, false otherwise.
406 */
407 public static function get_year_month_from_file_path( $path_or_url ) {
408 // Regex pattern to match paths and URLs containing 'YYYY/MM/' at any depth, allowing subdirectories afterward
409 $pattern = '#(?:^|/)(\d{4})/(0[1-9]|1[0-2])/[^/]+(?:/[^/]+)*$#';
410
411 // Check if the input matches the pattern
412 if ( preg_match( $pattern, $path_or_url, $matches ) ) {
413 // Return the year/month as a string in the format 'YYYY/MM'
414 return $matches[1] . '/' . $matches[2];
415 }
416
417 return false; // Invalid format
418 }
419
420
421 /**
422 * Maybe convert size to string
423 *
424 * @param int $attachment_id
425 * @param mixed $size
426 *
427 * @return null|string
428 */
429 public static function maybe_convert_size_to_string( $attachment_id, $size ) {
430 if ( is_array( $size ) ) {
431 $width = ( isset( $size[0] ) && $size[0] > 0 ) ? $size[0] : 1;
432 $height = ( isset( $size[1] ) && $size[1] > 0 ) ? $size[1] : 1;
433 $original_aspect_ratio = $width / $height;
434 $meta = wp_get_attachment_metadata( $attachment_id );
435
436 if ( ! isset( $meta['sizes'] ) || empty( $meta['sizes'] ) ) {
437 return false;
438 }
439
440 $sizes = $meta['sizes'];
441 uasort( $sizes, function ( $a, $b ) {
442 // Order by image area
443 return ( $a['width'] * $a['height'] ) - ( $b['width'] * $b['height'] );
444 } );
445
446 $near_matches = array();
447
448 foreach ( $sizes as $size => $value ) {
449 if ( $width > $value['width'] || $height > $value['height'] ) {
450 continue;
451 }
452 $aspect_ratio = $value['width'] / $value['height'];
453 if ( $aspect_ratio === $original_aspect_ratio ) {
454 return $size;
455 }
456 $near_matches[] = $size;
457 }
458 // Return nearest match
459 if ( ! empty( $near_matches ) ) {
460 return $near_matches[0];
461 }
462 }
463
464 return $size;
465 }
466
467 /**
468 * Reduce the given URL down to the simplest version of itself.
469 *
470 * Useful for matching against the full version of the URL in a full-text search
471 * or saving as a key for dictionary type lookup.
472 *
473 * @param string $url
474 *
475 * @return string
476 */
477 public static function reduce_url( $url ) {
478 $parts = static::parse_url( $url );
479 $host = isset( $parts['host'] ) ? $parts['host'] : '';
480 $port = isset( $parts['port'] ) ? ":{$parts['port']}" : '';
481 $path = isset( $parts['path'] ) ? $parts['path'] : '';
482
483 return '//' . $host . $port . $path;
484 }
485
486 /**
487 * Remove scheme from URL.
488 *
489 * @param string $url
490 * @return string
491 */
492 public static function remove_scheme( $url ) {
493 return preg_replace( '/^(?:http|https):/', '', $url );
494 }
495
496 /**
497 * Remove size from filename (image[-100x100].jpeg).
498 *
499 * @param string $url
500 * @param bool $remove_extension
501 *
502 * @return string
503 */
504 public static function remove_size_from_filename( $url, $remove_extension = false ) {
505 $url = preg_replace( '/^(\S+)-[0-9]{1,4}x[0-9]{1,4}(\.[a-zA-Z0-9\.]{2,})?/', '$1$2', $url );
506
507 $url = apply_filters( 'wpmcs_remove_size_from_filename', $url );
508
509 if ( $remove_extension ) {
510 $ext = pathinfo( $url, PATHINFO_EXTENSION );
511 $url = str_replace( ".$ext", '', $url );
512 }
513
514 return $url;
515 }
516
517 /**
518 * Is the string a URL?
519 *
520 * @param mixed $string
521 *
522 * @return bool
523 */
524 public static function is_url( $string ): bool {
525 if ( empty( $string ) || ! is_string( $string ) ) {
526 return false;
527 }
528
529 if ( preg_match( '@^(?:https?:)?//[a-zA-Z0-9\-]+@', $string ) ) {
530 return true;
531 }
532
533 return false;
534 }
535
536 /**
537 * Parses a URL into its components. Compatible with PHP < 5.4.7.
538 *
539 * @param string $url The URL to parse.
540 *
541 * @param int $component PHP_URL_ constant for URL component to return.
542 *
543 * @return mixed An array of the parsed components, mixed for a requested component, or false on error.
544 */
545 public static function parse_url( $url, $component = -1 ) {
546 $url = trim( $url );
547 $no_scheme = 0 === strpos( $url, '//' );
548
549 if ( $no_scheme ) {
550 $url = 'http:' . $url;
551 }
552
553 $parts = parse_url( $url, $component );
554
555 if ( 0 < $component ) {
556 return $parts;
557 }
558
559 if ( $no_scheme && is_array( $parts ) ) {
560 unset( $parts['scheme'] );
561 }
562
563 return $parts;
564 }
565
566 /**
567 * Is the given string a usable URL?
568 *
569 * We need URLs that include at least a domain and filename with extension
570 * for URL rewriting in either direction.
571 *
572 * @param mixed $url
573 *
574 * @return bool
575 */
576 public static function is_file_url( $url ): bool {
577 if ( ! static::is_url( $url ) ) {
578 return false;
579 }
580
581 $parts = static::parse_url( $url );
582
583 if (
584 empty( $parts['host'] ) ||
585 empty( $parts['path'] ) ||
586 ! pathinfo( $parts['path'], PATHINFO_EXTENSION )
587 ) {
588 return false;
589 }
590
591 return true;
592 }
593
594 }
595