-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathclass-utils.php
More file actions
1591 lines (1425 loc) · 45.5 KB
/
class-utils.php
File metadata and controls
1591 lines (1425 loc) · 45.5 KB
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Utilities for Cloudinary.
*
* @package Cloudinary
*/
namespace Cloudinary;
use Cloudinary\Misc\Image_Sizes_No_Textdomain;
use Cloudinary\Settings\Setting;
use Google\Web_Stories\Story_Post_Type;
use WP_Post;
/**
* Class that includes utility methods.
*
* @package Cloudinary
*/
class Utils {
/**
* Holds a list of temp files to be purged.
*
* @var array
*/
public static $file_fragments = array();
const METADATA = array(
'actions' => array(
'add_{object}_metadata',
'update_{object}_metadata',
),
'objects' => array(
'post',
'term',
'user',
),
);
/**
* Filter an array recursively
*
* @param array $input The array to filter.
* @param callable|null $callback The callback to run for filtering.
*
* @return array
*/
public static function array_filter_recursive( array $input, $callback = null ) {
// PHP array_filter does this, so we'll do it too.
if ( null === $callback ) {
$callback = static function ( $item ) {
return ! empty( $item );
};
}
foreach ( $input as &$value ) {
if ( is_array( $value ) ) {
$value = self::array_filter_recursive( $value, $callback );
}
}
return array_filter( $input, $callback );
}
/**
* Gets the active child setting.
*
* @return Setting
*/
public static function get_active_setting() {
$settings = get_plugin_instance()->settings;
$active = null;
if ( $settings->has_param( 'active_setting' ) ) {
$active = $settings->get_setting( $settings->get_param( 'active_setting' ) );
}
return $active;
}
/**
* Detects array keys with dot notation and expands them to form a new multi-dimensional array.
*
* @param array $input The array that will be processed.
* @param string $separator Separator string.
*
* @return array
*/
public static function expand_dot_notation( array $input, $separator = '.' ) {
$result = array();
foreach ( $input as $key => $value ) {
if ( is_array( $value ) ) {
$value = self::expand_dot_notation( $value );
}
foreach ( array_reverse( explode( $separator, $key ) ) as $inner_key ) {
$value = array( $inner_key => $value );
}
// phpcs:ignore
/** @noinspection SlowArrayOperationsInLoopInspection */
$result = array_merge_recursive( $result, $value );
}
return $result;
}
/**
* Check whether the inputted HTML string is powered by AMP, or if the request is an amp page.
* Reference on how to detect an AMP page: https://amp.dev/documentation/guides-and-tutorials/learn/spec/amphtml/?format=websites#ampd.
*
* @param string|null $html_string Optional: The specific HTML string to check.
*
* @return bool
*/
public static function is_amp( $html_string = null ) {
if ( ! empty( $html_string ) ) {
return preg_match( '/<html.+(amp|⚡)+[^>]/', substr( $html_string, 0, 200 ), $found );
}
$is_amp = false;
if ( function_exists( 'amp_is_request' ) ) {
$is_amp = amp_is_request();
}
return $is_amp;
}
/**
* Check whether the inputted post type is a webstory.
*
* @param string $post_type The post type to compare to.
*
* @return bool
*/
public static function is_webstory_post_type( $post_type ) {
return class_exists( Story_Post_Type::class ) && Story_Post_Type::POST_TYPE_SLUG === $post_type;
}
/**
* Get all the attributes from an HTML tag.
*
* @param string $tag HTML tag to get attributes from.
*
* @return array
*/
public static function get_tag_attributes( $tag ) {
$tag = strstr( $tag, ' ', false );
$tag = trim( $tag, '> ' );
$args = shortcode_parse_atts( $tag );
$return = array();
foreach ( $args as $key => $value ) {
if ( is_int( $key ) ) {
$return[ $value ] = 'true';
continue;
}
$return[ $key ] = $value;
}
return $return;
}
/**
* Get the depth of an array.
*
* @param array $data The array to check.
*
* @return int
*/
public static function array_depth( array $data ) {
$depth = 0;
foreach ( $data as $value ) {
if ( is_array( $value ) ) {
$level = self::array_depth( $value ) + 1;
if ( $level > $depth ) {
$depth = $level;
}
}
}
return $depth;
}
/**
* Check if the current user can perform a task.
*
* @param string $task The task to check.
* @param string $capability The default capability.
* @param string $context The context for the task.
* @param mixed ...$args Optional further parameters.
*
* @return bool
*/
public static function user_can( $task, $capability = 'manage_options', $context = '', ...$args ) {
// phpcs:disable WordPress.WhiteSpace.DisallowInlineTabs.NonIndentTabsUsed
/**
* Filter the capability required for a specific Cloudinary task.
*
* @hook cloudinary_task_capability_{task}
* @since 2.7.6. In 3.0.6 $context and $args added.
*
* @example
* <?php
*
* // Enforce `manage_options` to download an asset from Cloudinary.
* add_filter(
* 'cloudinary_task_capability_manage_assets',
* function( $task, $context ) {
* if ( 'download' === $context ) {
* $capability = 'manage_options';
* }
* return $capability;
* },
* 10,
* 2
* );
*
* @param $capability {string} The capability.
* @param $context {string} The context for the task.
* @param $args {mixed} The optional arguments.
*
* @default 'manage_options'
* @return {string}
*/
$capability = apply_filters( "cloudinary_task_capability_{$task}", $capability, $context, ...$args );
/**
* Filter the capability required for Cloudinary tasks.
*
* @hook cloudinary_task_capability
* @since 2.7.6. In 3.0.6 $context and $args added.
*
* @example
* <?php
*
* // Enforce `manage_options` to download an asset from Cloudinary.
* add_filter(
* 'cloudinary_task_capability',
* function( $capability, $task, $context ) {
* if ( 'manage_assets' === $task && 'download' === $context ) {
* $capability = 'manage_options';
* }
* return $capability;
* },
* 10,
* 3
* );
*
* @param $capability {string} The current capability for the task.
* @param $task {string} The task.
* @param $context {string} The context for the task.
* @param $args {mixed} The optional arguments.
*
* @return {string}
*/
$capability = apply_filters( 'cloudinary_task_capability', $capability, $task, $context, ...$args );
// phpcs:enable WordPress.WhiteSpace.DisallowInlineTabs.NonIndentTabsUsed
return current_user_can( $capability, ...$args ); // phpcs:ignore WordPress.WP.Capabilities.Undetermined
}
/**
* Get the Cloudinary relationships table name.
*
* @return string
*/
public static function get_relationship_table() {
global $wpdb;
return $wpdb->prefix . 'cloudinary_relationships';
}
/**
* Get the table create SQL.
*
* @return string
*/
public static function get_table_sql() {
global $wpdb;
$table_name = self::get_relationship_table();
$charset_collate = $wpdb->get_charset_collate();
// Setup the sql.
$sql = "CREATE TABLE $table_name (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
post_id bigint(20) DEFAULT NULL,
public_id varchar(1000) DEFAULT NULL,
parent_path varchar(1000) DEFAULT NULL,
sized_url varchar(1000) DEFAULT NULL,
media_context varchar(12) DEFAULT 'default',
width int(11) DEFAULT NULL,
height int(11) DEFAULT NULL,
format varchar(12) DEFAULT NULL,
sync_type varchar(45) DEFAULT NULL,
post_state varchar(12) DEFAULT NULL,
transformations text DEFAULT NULL,
text_overlay text DEFAULT NULL,
image_overlay text DEFAULT NULL,
signature varchar(45) DEFAULT NULL,
public_hash varchar(45) DEFAULT NULL,
url_hash varchar(45) DEFAULT NULL,
parent_hash varchar(45) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY media (url_hash, media_context),
KEY post_id (post_id),
KEY parent_hash (parent_hash),
KEY public_hash (public_hash),
KEY sync_type (sync_type)
) ENGINE=InnoDB $charset_collate";
return $sql;
}
/**
* Check if table exists.
*
* @return bool
*/
protected static function table_installed() {
global $wpdb;
$exists = false;
$table_name = self::get_relationship_table();
$name = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
if ( $table_name === $name ) {
$exists = true;
}
return $exists;
}
/**
* Install our custom table.
*/
public static function install() {
// Ensure that the plugin bootstrap is loaded.
get_plugin_instance()->init();
$sql = self::get_table_sql();
if ( false === self::table_installed() ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.dbDelta_dbdelta
update_option( Sync::META_KEYS['db_version'], get_plugin_instance()->version );
} else {
self::upgrade_install();
}
}
/**
* Upgrade the installation.
*/
protected static function upgrade_install() {
$sequence = self::get_upgrade_sequence();
foreach ( $sequence as $callable ) {
if ( is_callable( $callable ) ) {
call_user_func( $callable );
}
}
}
/**
* Get the DB upgrade sequence.
*
* @return array
*/
protected static function get_upgrade_sequence() {
$upgrade_sequence = array();
$sequences = array(
'3.0.0' => array(
'range' => array( '3.0.0' ),
'method' => array( 'Cloudinary\Utils', 'upgrade_3_0_1' ),
),
'3.1.9' => array(
'range' => array( '3.0.1', '3.1.9' ),
'method' => array( 'Cloudinary\Utils', 'upgrade_3_1_9' ),
),
'3.3.0' => array(
'range' => array( '3.1.9', '3.3.0' ),
'method' => array( 'Cloudinary\Utils', 'upgrade_3_3_0' ),
),
);
$previous_version = get_option( Sync::META_KEYS['db_version'], '3.0.0' );
$current_version = get_plugin_instance()->version;
foreach ( $sequences as $sequence ) {
if (
version_compare( $current_version, $previous_version, '>' )
&& version_compare( $previous_version, reset( $sequence['range'] ), '>=' )
&& version_compare( $previous_version, end( $sequence['range'] ), '<' )
) {
$upgrade_sequence[] = $sequence['method'];
}
}
/**
* Filter the upgrade sequence.
*
* @hook cloudinary_upgrade_sequence
* @since 3.0.1
*
* @param $upgrade_sequence {array} The default sequence.
*
* @return {array}
*/
return apply_filters( 'cloudinary_upgrade_sequence', $upgrade_sequence );
}
/**
* Upgrade DB from v3.0.0 to v3.0.1.
*/
public static function upgrade_3_0_1() {
global $wpdb;
$tablename = self::get_relationship_table();
// Drop old indexes.
$wpdb->query( "ALTER TABLE {$tablename} DROP INDEX sized_url" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} DROP INDEX parent_path" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} DROP INDEX public_id" ); // phpcs:ignore WordPress.DB
// Add new columns.
$wpdb->query( "ALTER TABLE {$tablename} ADD `public_hash` VARCHAR(45) NULL DEFAULT NULL" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} ADD `url_hash` VARCHAR(45) NULL DEFAULT NULL" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} ADD `parent_hash` VARCHAR(45) NULL DEFAULT NULL" ); // phpcs:ignore WordPress.DB
// Add new indexes.
$wpdb->query( "ALTER TABLE {$tablename} ADD UNIQUE INDEX url_hash (url_hash)" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} ADD INDEX public_hash (public_hash)" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} ADD INDEX parent_hash (parent_hash)" ); // phpcs:ignore WordPress.DB
// Alter sizes.
$wpdb->query( "ALTER TABLE {$tablename} CHANGE public_id public_id varchar(1000) DEFAULT NULL" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} CHANGE parent_path parent_path varchar(1000) DEFAULT NULL" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} CHANGE sized_url sized_url varchar(1000) DEFAULT NULL" ); // phpcs:ignore WordPress.DB
// Alter engine.
$wpdb->query( "ALTER TABLE {$tablename} ENGINE=InnoDB;" );// phpcs:ignore WordPress.DB
// Set DB Version.
update_option( Sync::META_KEYS['db_version'], get_plugin_instance()->version );
}
/**
* Upgrade DB from v3.0.1 to v3.1.9.
*/
public static function upgrade_3_1_9() {
global $wpdb;
$tablename = self::get_relationship_table();
// Add new columns.
$wpdb->query( "ALTER TABLE {$tablename} ADD COLUMN `media_context` VARCHAR(12) DEFAULT 'default' AFTER `sized_url`" ); // phpcs:ignore WordPress.DB
// Update indexes.
$wpdb->query( "ALTER TABLE {$tablename} DROP INDEX url_hash" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} ADD UNIQUE INDEX media (url_hash, media_context)" ); // phpcs:ignore WordPress.DB
// Set DB Version.
update_option( Sync::META_KEYS['db_version'], get_plugin_instance()->version );
}
/**
* Upgrade DB from v3.1.9 to v3.2.15.
* Adds columns for overlay data.
*/
public static function upgrade_3_3_0() {
global $wpdb;
$tablename = self::get_relationship_table();
// Add new columns for overlays.
$wpdb->query( "ALTER TABLE {$tablename} ADD COLUMN `text_overlay` TEXT DEFAULT NULL AFTER `transformations`" ); // phpcs:ignore WordPress.DB
$wpdb->query( "ALTER TABLE {$tablename} ADD COLUMN `image_overlay` TEXT DEFAULT NULL AFTER `text_overlay`" ); // phpcs:ignore WordPress.DB
// Update sample.jpg to leather_bag.jpg in media_display settings.
$media_display = get_option( 'cloudinary_media_display', array() );
if ( ! empty( $media_display ) && is_array( $media_display ) ) {
$updated = false;
$fields = array( 'image_preview', 'lazyload_preview', 'breakpoints_preview' );
foreach ( $fields as $field ) {
if ( isset( $media_display[ $field ] ) && is_string( $media_display[ $field ] ) ) {
if ( false !== strpos( $media_display[ $field ], 'sample.jpg' ) ) {
$media_display[ $field ] = str_replace( 'sample.jpg', 'leather_bag.jpg', $media_display[ $field ] );
$updated = true;
}
}
}
if ( $updated ) {
update_option( 'cloudinary_media_display', $media_display );
}
}
// Set DB Version.
update_option( Sync::META_KEYS['db_version'], get_plugin_instance()->version );
}
/**
* Gets the URL for opening a Support Request.
*
* @param array $args The arguments.
*
* @return string
*/
public static function get_support_link( $args = array() ) {
$user = wp_get_current_user();
$plugin = get_plugin_instance();
$url = 'https://support.cloudinary.com/hc/en-us/requests/new';
$default_args = array(
'tf_anonymous_requester_email' => $user->user_email,
'tf_22246877' => $user->display_name,
'tf_360007219560' => $plugin->components['connect']->get_cloud_name(),
'tf_360017815680' => 'other_help_needed',
'tf_subject' => esc_attr(
sprintf(
// translators: The plugin version.
__( 'I need help with Cloudinary WordPress plugin version %s', 'cloudinary' ),
$plugin->version
)
),
'tf_description' => esc_attr( __( 'Please, provide more details on your request, and if possible, attach a System Report', 'cloudinary' ) ),
);
$args = wp_parse_args(
$args,
$default_args
);
return add_query_arg( array_filter( $args ), $url );
}
/**
* Wrapper function to core wp_get_inline_script_tag.
*
* @param string $javascript Inline JavaScript code.
*/
public static function print_inline_tag( $javascript ) {
if ( function_exists( 'wp_print_inline_script_tag' ) ) {
wp_print_inline_script_tag( $javascript );
return;
}
$javascript = "\n" . trim( $javascript, "\n\r " ) . "\n";
printf( "<script type='text/javascript'>%s</script>\n", $javascript ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Get a sanitized input text field.
*
* @param string $var_name The value to get.
* @param int $type The type to get.
*
* @return mixed
*/
public static function get_sanitized_text( $var_name, $type = INPUT_GET ) {
return filter_input( $type, $var_name, FILTER_CALLBACK, array( 'options' => 'sanitize_text_field' ) );
}
/**
* Returns information about a file path by normalizing the locale.
*
* @param string $path The path to be parsed.
* @param int $flags Specifies a specific element to be returned.
* Defaults to 15 which stands for PATHINFO_ALL.
*
* @return array|string|string[]
*/
public static function pathinfo( $path, $flags = 15 ) {
/**
* Approach based on wp_basename.
*
* @see wp-includes/formatting.php
*/
$path = str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
$pathinfo = pathinfo( $path, $flags );
return is_array( $pathinfo ) ? array_map( 'urldecode', $pathinfo ) : urldecode( $pathinfo );
}
/**
* Check if a thing looks like a json string.
*
* @param mixed $thing The thing to check.
*
* @return bool
*/
public static function looks_like_json( $thing ) {
if ( ! is_string( $thing ) ) {
return false;
}
$thing = trim( $thing );
if ( empty( $thing ) ) {
return false;
}
if ( ! in_array( $thing[0], array( '{', '[' ), true ) ) {
return false;
}
return true;
}
/**
* Check if we're in a REST API request.
*
* @return bool
*/
public static function is_rest_api() {
$is = defined( 'REST_REQUEST' ) && REST_REQUEST;
if ( ! $is ) {
$is = ! empty( $GLOBALS['wp']->query_vars['rest_route'] );
}
if ( ! $is ) {
// Fallback if rest engine is not setup yet.
$rest_base = wp_parse_url( static::rest_url( '/' ), PHP_URL_PATH );
$request_uri = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL );
$is = is_string( $request_uri ) && strpos( $request_uri, $rest_base ) === 0;
}
return $is;
}
/**
* Check if we are in WordPress ajax.
*
* @return bool
*/
public static function is_frontend_ajax() {
$referer = wp_get_referer();
$admin_base = admin_url();
$is_admin = $referer ? 0 === strpos( $referer, $admin_base ) : false;
// Check if this is a frontend ajax request.
$is_frontend_ajax = ! $is_admin && defined( 'DOING_AJAX' ) && DOING_AJAX;
// If it's not an obvious WP ajax request, check if it's a custom frontend ajax request.
if ( ! $is_frontend_ajax && ! $is_admin ) {
// Catch the content type of the $_SERVER['CONTENT_TYPE'] variable.
$type = filter_input( INPUT_SERVER, 'CONTENT_TYPE', FILTER_CALLBACK, array( 'options' => 'sanitize_text_field' ) );
$is_frontend_ajax = $type && false !== strpos( $type, 'json' );
}
return $is_frontend_ajax;
}
/**
* Check if this is an admin request, but not an ajax one.
*
* @return bool
*/
public static function is_admin() {
return is_admin() && ! self::is_frontend_ajax();
}
/**
* Inspected on wp_extract_urls.
* However, there's a shortcoming on some transformations where the core extractor will fail to fully parse such URLs.
*
* @param string $content The content.
*
* @return array
*/
public static function extract_urls( $content ) {
// Remove inline SVG data URIs, as they can cause parsing issues when extracting URLs.
$content = self::strip_inline_svg_data_uris( $content );
preg_match_all(
"#([\"']?)("
. '(?:[\w-]+:)?//?'
. '[^\s()<>"\']+'
. '[.,]'
. '(?:'
. '\([\w\d]+\)|'
. '(?:'
. "[^`!()\[\]{};:'\".,<>«»“”‘’\s]|"
. '(?:[:]\w+)?/?'
. ')+'
. ')'
. ")\\1#",
$content,
$post_links
);
$post_links = array_unique( array_map( 'html_entity_decode', $post_links[2] ) );
return array_values( $post_links );
}
/**
* Strip inline SVG data URIs from content.
*
* @param string $content The content to process.
*
* @return string The content with SVG data URIs removed.
*/
public static function strip_inline_svg_data_uris( $content ) {
// Pattern to match the data URI structure: data:image/svg+xml;base64,<base64-encoded-data>.
$svg_data_uri_pattern = '/data:image\/svg\+xml;base64,[a-zA-Z0-9\/\+\=]+/i';
// Remove all occurrences of SVG data URIs from the content.
$cleaned_content = preg_replace( $svg_data_uri_pattern, '', $content );
// In case an error occurred, we return the original content to avoid data loss.
return is_null( $cleaned_content ) ? $content : $cleaned_content;
}
/**
* Is saving metadata.
*
* @return bool
*/
public static function is_saving_metadata() {
$saving = false;
$metadata = self::METADATA;
foreach ( $metadata['actions'] as $action ) {
foreach ( $metadata['objects'] as $object ) {
$inline_action = str_replace( array( '{object}', 'metadata' ), array( $object, 'meta' ), $action );
if ( did_action( $inline_action ) ) {
$saving = true;
break;
}
}
}
return $saving;
}
/**
* Encode SVG placeholder.
*
* @param string $width The SVG width.
* @param string $height The SVG height.
* @param string $color The SVG color.
*
* @return string
*/
public static function svg_encoded( $width = '600px', $height = '400px', $color = '-color-' ) {
$svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' . $width . '" height="' . $height . '"><rect width="100%" height="100%"><animate attributeName="fill" values="' . $color . '" dur="2s" repeatCount="indefinite" /></rect></svg>';
return 'data:image/svg+xml;base64,' . base64_encode( $svg );
}
/**
* Wrapper for get_post_parent.
*
* @param int|WP_Post|null $post The post.
*
* @return WP_Post|null
*/
public static function get_post_parent( $post = null ) {
if ( is_callable( 'get_post_parent' ) ) {
return get_post_parent( $post );
}
$wp_post = get_post( $post );
return ! empty( $wp_post->post_parent ) ? get_post( $wp_post->post_parent ) : null;
}
/**
* Download a fragment of a file URL to a temp file and return the file URI.
*
* @param string $url The URL to download.
* @param int $size The size of the fragment to download.
*
* @return string|false
*/
public static function download_fragment( $url, $size = 1048576 ) {
$temp_file = wp_tempnam( basename( $url ) );
$pointer = fopen( $temp_file, 'wb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
$file = false;
if ( $pointer ) {
// Prep to purge.
$index = count( self::$file_fragments );
if ( empty( $index ) ) {
add_action( 'shutdown', array( __CLASS__, 'purge_fragments' ) );
}
self::$file_fragments[ $index ] = array(
'pointer' => $pointer,
'file' => $temp_file,
);
// Get the metadata of the stream.
$data = stream_get_meta_data( $pointer );
// Stream the content to the temp file.
$response = wp_safe_remote_get(
$url,
array(
'timeout' => 300, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout
'stream' => true,
'filename' => $data['uri'],
'limit_response_size' => $size,
)
);
if ( ! is_wp_error( $response ) ) {
$file = $data['uri'];
} else {
// Clean up if there was an error.
self::purge_fragment( $index );
}
}
return $file;
}
/**
* Purge fragment temp files on shutdown.
*/
public static function purge_fragments() {
foreach ( array_keys( self::$file_fragments ) as $index ) {
self::purge_fragment( $index );
}
}
/**
* Purge a fragment temp file.
*
* @param int $index The index of the fragment to purge.
*/
public static function purge_fragment( $index ) {
if ( isset( self::$file_fragments[ $index ] ) ) {
fclose( self::$file_fragments[ $index ]['pointer'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
unlink( self::$file_fragments[ $index ]['file'] ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink
}
}
/**
* Log a debug message.
*
* @param string $message The message to log.
* @param string|null $key The key to log the message under.
*/
public static function log( $message, $key = null ) {
if ( get_plugin_instance()->get_component( 'report' )->enabled() ) {
$messages = get_option( Sync::META_KEYS['debug'], array() );
if ( $key ) {
$hash = md5( $message );
$messages[ $key ][ $hash ] = $message;
} else {
$messages[] = $message;
}
update_option( Sync::META_KEYS['debug'], $messages, false );
}
}
/**
* Get the debug messages.
*
* @return array
*/
public static function get_debug_messages() {
return get_option( Sync::META_KEYS['debug'], array( __( 'Debug log is empty', 'cloudinary' ) ) );
}
/**
* Check if the tag attributes contain possible third party manipulated data, and return found data.
*
* @param array $attributes The tag attributes.
* @param string $tag The tag.
*
* @return string|false
*/
public static function maybe_get_third_party_changes( $attributes, $tag ) {
static $filtered_keys, $filtered_classes;
$lazy_keys = array(
'src',
'lazyload',
'lazy',
'loading',
);
$lazy_classes = array(
'lazyload',
'lazy',
'loading',
);
if ( ! $filtered_keys ) {
/**
* Filter the keywords in data-* attributes on tags to be ignored from lazy-loading.
*
* @hook cloudinary_ignored_data_keywords
* @since 3.0.8
*
* @param $lazy_keys {array} The built-in ignore data-* keywords.
*
* @return {array}
*/
$filtered_keys = apply_filters( 'cloudinary_ignored_data_keywords', $lazy_keys );
/**
* Filter the keywords in classes on tags to be ignored from lazy-loading.
*
* @hook cloudinary_ignored_class_keywords
* @since 3.0.8
*
* @param $lazy_classes {array} The built-in ignore class keywords.
*
* @return {array}
*/
$filtered_classes = apply_filters( 'cloudinary_ignored_class_keywords', $lazy_classes );
}
$is = false;
// Source tag on Picture tags are not lazy-loaded.
if ( 'source' !== $tag ) {
if ( ! isset( $attributes['src'] ) ) {
$is = __( 'Missing SRC attribute.', 'cloudinary' );
} elseif ( false !== strpos( $attributes['src'], 'data:image' ) ) {
$is = $attributes['src'];
} elseif ( isset( $attributes['class'] ) ) {
$classes = explode( '-', str_replace( ' ', '-', $attributes['class'] ) );
if ( ! empty( array_intersect( $filtered_classes, $classes ) ) ) {
$is = $attributes['class'];
}
}
}
// If the above didn't find anything, check the data-* attributes.
if ( ! $is ) {
foreach ( $attributes as $key => $value ) {
if ( 'data-' !== substr( $key, 0, 5 ) ) {
continue;
}
$parts = explode( '-', $key );
if ( ! empty( array_intersect( $parts, $filtered_keys ) ) ) {
$is = $key;
break;
}
}
}
return $is;
}
/**
* Clean up meta after sync.
*
* @param int $attachment_id The attachment ID.
*
* @return void
*/
public static function clean_up_sync_meta( $attachment_id ) {
// translators: The attachment ID.
$action_message = sprintf( __( 'Clean up sync metadata for %d', 'cloudinary' ), $attachment_id );
do_action( '_cloudinary_queue_action', $action_message );
// remove pending.
delete_post_meta( $attachment_id, Sync::META_KEYS['pending'] );
// Remove processing flag.
delete_post_meta( $attachment_id, Sync::META_KEYS['syncing'] );
$sync_thread = get_post_meta( $attachment_id, Sync::META_KEYS['queued'], true );
if ( ! empty( $sync_thread ) ) {
delete_post_meta( $attachment_id, Sync::META_KEYS['queued'] );
delete_post_meta( $attachment_id, $sync_thread );
}
}
/**
* Get the registered image sizes, the labels and crop settings.
*
* @param null|int $attachment_id The attachment ID to get the sizes. Defaults to generic registered sizes.
*
* @return array
*/
public static function get_registered_sizes( $attachment_id = null ) {
$additional_sizes = wp_get_additional_image_sizes();
$all_sizes = array();
$labels = array();
$intermediate_sizes = array();
if ( is_null( $attachment_id ) ) {
$intermediate_sizes = get_intermediate_image_sizes(); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_intermediate_image_sizes_get_intermediate_image_sizes
} else {
$meta = wp_get_attachment_metadata( $attachment_id );
if ( ! empty( $meta['sizes'] ) ) {
$additional_sizes = wp_parse_args( $additional_sizes, $meta['sizes'] );
$intermediate_sizes = array_keys( $meta['sizes'] );
}
}
foreach ( $intermediate_sizes as $size ) {
$labels[ $size ] = ucwords( str_replace( array( '-', '_' ), ' ', $size ) );
}
/** This filter is documented in wp-admin/includes/media.php */
$image_sizes = apply_filters(
'image_size_names_choose',
Image_Sizes_No_Textdomain::get_image_sizes()
);
$labels = wp_parse_args( $labels, $image_sizes );
foreach ( $intermediate_sizes as $size ) {
if ( isset( $additional_sizes[ $size ] ) ) {
$all_sizes[ $size ] = array(