-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathclass-delivery.php
More file actions
2124 lines (1862 loc) · 65 KB
/
class-delivery.php
File metadata and controls
2124 lines (1862 loc) · 65 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
/**
* Cloudinary Delivery for delivery of cloudinary assets.
*
* @package Cloudinary
*/
namespace Cloudinary;
use Cloudinary\Component\Setup;
use Cloudinary\Connect\Api;
use Cloudinary\Media\Filter;
use Cloudinary\Media\Global_Transformations;
use Cloudinary\UI\Component\HTML;
use Cloudinary\Delivery\Bypass;
use Cloudinary\Relate\Relationship;
/**
* Plugin Delivery class.
*/
class Delivery implements Setup {
/**
* Holds the core plugin.
*
* @var Plugin
*/
protected $plugin;
/**
* Holds the Media component.
*
* @var Media
*/
protected $media;
/**
* Holds the Media\Filter component.
*
* @var Filter
*/
protected $filter;
/**
* Holds the Sync component.
*
* @var Sync
*/
protected $sync;
/**
* Hold the Post ID.
*
* @var null|int
*/
protected $current_post_id = null;
/**
* Holds the Bypass instance.
*
* @var Bypass
*/
protected $bypass;
/**
* Holds a list of found and valid urls.
*
* @var array
*/
public $found_urls = array();
/**
* Holds a list of known urls.
*
* @var array
*/
public $known = array();
/**
* Holds the list of unknown URLS.
*
* @var array
*/
public $unknown = array();
/**
* Holds a list of known urls with public_ids.
*
* @var array
*/
public $usable = array();
/**
* Holds a list of known urls without public_ids.
*
* @var array
*/
public $unusable = array();
/**
* The meta data cache key to store URLS.
*
* @var string
*/
const META_CACHE_KEY = '_cld_replacements';
/**
* Holds the captured post contexts
*
* @var array
*/
protected $post_contexts = array();
/**
* Flag for doing metadata adds or updates.
*
* @var bool
*/
protected $doing_metadata = false;
/**
* Component constructor.
*
* @param Plugin $plugin Global instance of the main plugin.
*/
public function __construct( Plugin $plugin ) {
$this->plugin = $plugin;
add_action( 'cloudinary_connected', array( $this, 'init' ) );
}
/**
* Init the class when cloudinary is connected.
*/
public function init() {
$this->plugin->components['replace'] = new String_Replace( $this->plugin );
$this->media = $this->plugin->get_component( 'media' );
add_filter( 'cloudinary_filter_out_local', '__return_false' );
add_action( 'update_option_cloudinary_media_display', array( $this, 'clear_cache' ) );
add_action( 'cloudinary_flush_cache', array( $this, 'do_clear_cache' ) );
add_action( 'cloudinary_unsync_asset', array( $this, 'unsync_size_relationship' ) );
add_action( 'before_delete_post', array( $this, 'delete_size_relationship' ) );
add_action( 'delete_attachment', array( $this, 'delete_size_relationship' ) );
add_action( 'cloudinary_register_sync_types', array( $this, 'register_sync_type' ), 30 );
add_filter( 'rest_request_before_callbacks', array( $this, 'maybe_unset_attributes' ), 10, 3 );
add_action(
'the_post',
function ( $post ) {
$this->post_contexts[] = $post->ID;
}
);
// Add Bypass options.
$this->bypass = new Bypass( $this->plugin );
// Add relation checking on front.
if ( ! is_admin() ) {
add_filter( 'wp_get_attachment_url', array( $this, 'ensure_relation' ), 10, 2 );
}
}
/**
* Determine if attributes should be added to image tags.
*
* @param WP_REST_Response $response The response object.
* @param WP_REST_Server $handler The request handler.
* @param WP_REST_Request|null $request The request object, if available.
*
* @return WP_REST_Response
*/
public function maybe_unset_attributes( $response, $handler, $request ) {
$route = $request->get_route();
if (
(bool) $request->get_header( 'x-cld-fetch-from-editor' )
|| (
false !== strpos( $route, 'wp/v2/media' )
&& 'edit' === $request->get_param( 'context' )
)
) {
add_filter( 'cloudinary_skip_parse_element', '__return_true' );
}
return $response;
}
/**
* Maybe filter out Cloudinary URLs in post meta.
*
* @param null|bool $check Whether to allow adding metadata for the given type.
* @param int $object_id The ID of the object metadata is for.
* @param string $meta_key The Metadata key.
* @param mixed $meta_value Metadata value.
*
* @return null|bool
*/
public function maybe_filter_out_metadata( $check, $object_id, $meta_key, $meta_value ) {
$internal_keys = array_merge(
Sync::META_KEYS,
array(
self::META_CACHE_KEY,
)
);
// Don't filter out metadata if we're dealing with Cloudinary internals.
if ( in_array( $meta_key, $internal_keys, true ) ) {
return $check;
}
if ( $this->doing_metadata ) {
return $check;
}
$this->doing_metadata = true;
$current_filter = current_filter();
list( $action, $object ) = explode( '_', $current_filter );
$process_meta_value = $this->filter_out_cloudinary( $meta_value );
if ( $process_meta_value !== $meta_value ) {
$meta_value = $process_meta_value;
$check = call_user_func( "{$action}_{$object}_meta", $object_id, $meta_key, $meta_value );
}
$this->doing_metadata = false;
return $check;
}
/**
* Filter out Cloudinary URLS and replace with local.
*
* @param string $content The content to filter.
*
* @return string
*/
public function filter_out_cloudinary( $content ) {
static $globals;
if ( ! $globals ) {
$image = $this->media->apply_default_transformations( array(), 'image' );
$video = $this->media->apply_default_transformations( array(), 'video' );
$globals = array(
'image' => Api::generate_transformation_string( $image, 'image' ),
'video' => Api::generate_transformation_string( $video, 'video' ),
);
}
$unslashed = false;
$working_content = $content;
if ( is_string( $working_content ) && ! is_numeric( $working_content ) ) {
$maybe_encoded = json_decode( $working_content, false );
if ( ! is_null( $maybe_encoded ) ) {
$working_content = $maybe_encoded;
}
}
if ( String_Replace::is_iterable( $working_content ) ) {
$working_content = $this->plugin->components['replace']->flatten( $working_content );
} else {
$unslash_maybe = wp_unslash( $working_content );
$unslashed = $unslash_maybe !== $working_content;
if ( $unslashed ) {
$working_content = $unslash_maybe;
}
}
$base_urls = array_unique( Utils::extract_urls( $working_content ) );
$cloudinary_urls = array_filter( $base_urls, array( $this->media, 'is_cloudinary_url' ) ); // clean out empty urls.
$urls = array();
if ( empty( $cloudinary_urls ) ) {
return $content;
}
foreach ( $cloudinary_urls as $url ) {
$public_id = $this->media->get_public_id_from_url( $url );
if ( ! empty( $public_id ) ) {
$urls[ $public_id ] = $url;
}
}
$results = Utils::query_relations( array_keys( $urls ) );
String_Replace::reset();
foreach ( $results as $result ) {
if ( ! isset( $urls[ $result['public_id'] ] ) ) {
continue;
}
$original_url = $urls[ $result['public_id'] ];
// Get merged transformations including overlays.
$merged_transformations = Relate::get_transformations( $result['post_id'], true );
if ( ! empty( $merged_transformations ) ) {
$original_url = str_replace( $merged_transformations . '/', '/', $original_url );
}
$size = $this->media->get_size_from_url( $original_url );
$transformations = $this->media->get_transformations_from_string( $original_url );
if ( 'image' === $this->media->get_resource_type( $result['post_id'] ) && ! $this->media->is_preview_only( $result['post_id'] ) ) {
$attachment_url = wp_get_attachment_image_url( $result['post_id'], $size );
} else {
$attachment_url = wp_get_attachment_url( $result['post_id'] );
}
$query_args = array();
wp_parse_str( wp_parse_url( $original_url, PHP_URL_QUERY ), $query_args );
if ( ! empty( $query_args['cld_overwrite'] ) ) {
$attachment_url = add_query_arg( 'cld_overwrite', true, $attachment_url );
}
if ( ! empty( $transformations ) ) {
$transformations = array_filter(
$transformations,
static function ( $item ) {
return ! isset( $item['crop'] ) && ! isset( $item['width'] ) && ! isset( $item['height'] );
}
);
$transformations = Api::generate_transformation_string( $transformations );
if ( ! empty( $transformations ) && ! in_array( $transformations, $globals, true ) ) {
$attachment_url = add_query_arg( 'cld_params', $transformations, $attachment_url );
}
}
String_Replace::replace( $urls[ $result['public_id'] ], $attachment_url );
}
$content = String_Replace::do_replace( $content );
return $content;
}
/**
* Ensure that an asset has a relation on front end.
*
* @param string $url The URL of the asset.
* @param int $attachment_id The attachment ID.
*
* @return string
*/
public function ensure_relation( $url, $attachment_id ) {
static $urls = array();
if ( empty( $urls[ $attachment_id ] ) && ! $this->media->get_post_meta( $attachment_id, Sync::META_KEYS['relationship'], true ) ) {
$urls[ $attachment_id ] = true;
$this->sync->get_sync_type( $attachment_id );
}
return $url;
}
/**
* Generate the delivery signature.
*
* @param int $attachment_id The attachment ID.
*
* @return string
*/
public function generate_signature( $attachment_id ) {
static $sql;
if ( ! $sql ) {
$sql = Utils::get_table_sql();
}
$public_id = null;
$relationship = Relationship::get_relationship( $attachment_id );
if ( $relationship instanceof Relationship ) {
$public_id = $relationship->public_id;
}
$sizes = $this->get_sized( $attachment_id );
$settings_signature = self::get_settings_signature();
$relation_signature = $this->media->get_post_meta( $attachment_id, Sync::META_KEYS['relationship'], true );
return wp_json_encode( $sizes ) . $public_id . $sql . $settings_signature . $relation_signature . Utils::get_media_context( $attachment_id );
}
/**
* Is attachment deliverable in the FE.
*
* @param int $attachment_id The attachment ID.
*
* @return bool
*/
public function is_deliverable( $attachment_id ) {
$is = false;
if ( wp_attachment_is_image( $attachment_id ) && 'on' === $this->plugin->settings->get_value( 'image_delivery' ) ) {
$is = true;
}
if ( ! $is && wp_attachment_is( 'video', $attachment_id ) && 'on' === $this->plugin->settings->get_value( 'video_delivery' ) ) {
$is = true;
}
// Ensure that the attachment has dimensions to be delivered.
if ( $is ) {
$meta = wp_get_attachment_metadata( $attachment_id, true );
$is = ! empty( $meta['width'] ) && ! empty( $meta['height'] );
// Webm audio files don't have width and height.
if ( ! $is && ! empty( $meta['mime_type'] ) && 'audio/webm' === $meta['mime_type'] ) {
$is = true;
}
}
if ( ! $is ) {
$is = ! wp_attachment_is_image( $attachment_id ) && ! wp_attachment_is( 'video', $attachment_id );
}
$svg = $this->plugin->get_component( 'svg' );
if ( ! $is && $svg->is_active() && $svg::is_svg( $attachment_id ) && 'on' === $this->plugin->settings->get_value( 'image_delivery' ) ) {
$is = true;
}
/**
* Filter deliverable attachments.
*
* @hook cloudinary_is_deliverable
*
* @param $is {bool} The default value.
* @param $attachment_id {int} The attachment ID.
*
* @return {bool}
*/
return apply_filters( 'cloudinary_is_deliverable', $is, $attachment_id );
}
/**
* Create delivery entries.
*
* @param int $attachment_id The attachment ID.
*/
public function create_delivery( $attachment_id ) {
$relationship = Relationship::get_relationship( $attachment_id );
$transformations = null;
// Preserve pre-existing transformations.
if ( $relationship instanceof Relationship ) {
$transformations = Relate::get_transformations( $attachment_id, true );
if ( empty( $transformations ) ) {
$transformations = null;
}
}
$this->delete_size_relationship( $attachment_id );
$size = $this->get_sized( $attachment_id );
$public_id = $this->media->has_public_id( $attachment_id ) ? $this->media->get_public_id( $attachment_id ) : null;
$base = $this->get_content_path();
$sized_url = '';
$wh = '0x0'; // phpcs:ignore PHPCompatibility.Numbers.RemovedHexadecimalNumericStrings.Found, PHPCompatibility.Miscellaneous.ValidIntegers.HexNumericStringFound
// Some attachments do not have Sizes.
if ( ! empty( $size ) ) {
$sized_url = $size['sized_url'];
$wh = $size['size'];
}
if ( empty( $sized_url ) ) {
$sized_url = Utils::get_path_from_url( wp_get_attachment_url( $attachment_id ), true );
}
self::create_size_relation( $attachment_id, $sized_url, $wh, $base );
// Update public ID and type.
self::update_size_relations_public_id( $attachment_id, $public_id );
self::update_size_relations_state( $attachment_id, 'inherit' );
self::update_size_relations_transformations( $attachment_id, $transformations );
$this->sync->set_signature_item( $attachment_id, 'delivery' );
}
/**
* Sync method for the relation type.
*
* @param int $attachment_id The attachment ID.
*/
public function update_relation( $attachment_id ) {
$public_id = $this->media->has_public_id( $attachment_id ) ? $this->media->get_public_id( $attachment_id ) : null;
// Update public ID and type.
self::update_size_relations_public_id( $attachment_id, $public_id );
$this->sync->set_signature_item( $attachment_id, 'relation' );
}
/**
* Add our delivery sync type.
*/
public function register_sync_type() {
$structure = array(
'asset_state' => 0,
'generate' => '__return_false',
'priority' => 0.5,
'sync' => array( $this, 'create_delivery' ),
'validate' => array( $this, 'is_deliverable' ),
'state' => '',
'note' => '',
'realtime' => true,
);
$this->sync->register_sync_type( 'delivery', $structure );
$structure = array(
'asset_state' => 0,
'generate' => array( $this, 'generate_signature' ), // Method to generate a signature.
'priority' => 50,
'sync' => array( $this, 'update_relation' ),
'validate' => array( $this, 'is_deliverable' ),
'state' => '',
'note' => '',
'realtime' => true,
);
$this->sync->register_sync_type( 'relation', $structure );
}
/**
* Get the base content path.
*
* @return string
*/
protected function get_content_path() {
$dirs = wp_get_upload_dir();
return ltrim( wp_parse_url( trailingslashit( $dirs['baseurl'] ), PHP_URL_PATH ), '/' );
}
/**
* Remove a delivery relationship on delete of a post.
*
* @param int $attachment_id The attachment ID.
*/
public function delete_size_relationship( $attachment_id ) {
$relationship = Relationship::get_relationship( $attachment_id );
$relationship->delete();
do_action( 'cloudinary_flush_cache' );
}
/**
* Disable a delivery relationship on unsync.
*
* @param int $attachment_id The attachment ID.
*/
public function unsync_size_relationship( $attachment_id ) {
self::update_size_relations_public_id( $attachment_id, null );
self::update_size_relations_state( $attachment_id, 'disable' );
self::update_size_relations_transformations( $attachment_id, null );
}
/**
* Get the different sizes for an attachment.
*
* @param int $attachment_id The attachment ID.
*
* @return array
*/
public function get_sized( $attachment_id ) {
static $sizes = array(), $registered_sizes;
if ( ! $registered_sizes && is_callable( 'wp_get_registered_image_subsizes' ) ) {
$registered_sizes = wp_get_registered_image_subsizes();
}
if ( empty( $sizes[ $attachment_id ] ) ) {
$sizes[ $attachment_id ] = array();
$meta = wp_get_attachment_metadata( $attachment_id, true );
if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
// Keep the full URL for cloudinary_assets.
if ( Assets::POST_TYPE_SLUG === get_post_type( $attachment_id ) ) {
$local_url = Utils::clean_url( $this->media->local_url( $attachment_id ), true );
} else {
$local_url = Utils::get_path_from_url( $this->media->local_url( $attachment_id ), true );
}
$sizes[ $attachment_id ] = array(
'sized_url' => $local_url,
'size' => $meta['width'] . 'x' . $meta['height'],
);
return $sizes[ $attachment_id ];
}
}
return $sizes[ $attachment_id ];
}
/**
* Update relationship public ID.
*
* @param int $attachment_id The attachment ID.
* @param null|string $public_id The public ID.
*/
public static function update_size_relations_public_id( $attachment_id, $public_id ) {
$relationship = Relationship::get_relationship( $attachment_id );
if ( $relationship instanceof Relationship ) {
$relationship->public_id = $public_id;
$relationship->public_hash = md5( (string) $public_id );
$relationship->signature = self::get_settings_signature();
$relationship->media_context = Utils::get_media_context( $attachment_id );
$relationship->save();
}
}
/**
* Update relationship status.
*
* @param int $attachment_id The attachment ID.
* @param string $state The state to set.
*/
public static function update_size_relations_state( $attachment_id, $state ) {
$relationship = Relationship::get_relationship( $attachment_id );
if ( $relationship instanceof Relationship ) {
$relationship->post_state = $state;
$relationship->save();
}
do_action( 'cloudinary_flush_cache' );
}
/**
* Update relationship transformations.
*
* @param int $attachment_id The attachment ID.
* @param string|null $transformations The transformations to set.
*/
public static function update_size_relations_transformations( $attachment_id, $transformations ) {
Relate::update_transformations( $attachment_id, $transformations );
}
/**
* Delete unneeded sizes in bulk by ID.
*
* @param array $ids The IDs to delete.
*/
public static function delete_bulk_size_relations( $ids ) {
global $wpdb;
$ids = (array) $ids;
$list = implode( ', ', array_fill( 0, count( $ids ), '%d' ) );
$tablename = Utils::get_relationship_table();
$sql = "DELETE from {$tablename} WHERE id IN( {$list} )";
$prepared = $wpdb->prepare( $sql, $ids ); // phpcs:ignore WordPress.DB
$wpdb->query( $prepared );// phpcs:ignore WordPress.DB
do_action( 'cloudinary_flush_cache' );
}
/**
* Create a size relationship.
*
* @param int $attachment_id The attachment ID.
* @param string $sized_url The sized url.
* @param string $size The size in (width)x(height) format.
* @param string $parent_path The path of the parent if external.
*
* @return false|int
*/
public static function create_size_relation( $attachment_id, $sized_url, $size = '0x0', $parent_path = '' ) { // phpcs:ignore PHPCompatibility.Numbers.RemovedHexadecimalNumericStrings.Found, PHPCompatibility.Miscellaneous.ValidIntegers.HexNumericStringFound
global $wpdb;
static $media;
if ( ! $media ) {
$media = get_plugin_instance()->get_component( 'media' );
}
$type = 'attachment' === get_post_type( $attachment_id ) ? 'media' : 'asset';
$resource = $media->get_resource_type( $attachment_id );
$width_height = explode( 'x', $size );
$transformations = $media->get_post_meta( $attachment_id, Sync::META_KEYS['transformation'], true );
if ( ! is_null( $transformations ) ) {
$media->delete_post_meta( $attachment_id, Sync::META_KEYS['transformation'] );
}
$data = array(
'post_id' => $attachment_id,
'parent_path' => $parent_path,
'sized_url' => $sized_url,
'media_context' => Utils::get_media_context( $attachment_id ),
'width' => $width_height[0] ? $width_height[0] : 0,
'height' => $width_height[1] ? $width_height[1] : 0,
'format' => Utils::pathinfo( $sized_url, PATHINFO_EXTENSION ),
'sync_type' => $type,
'post_state' => 'inherit',
'transformations' => ! empty( $transformations ) ? Api::generate_transformation_string( $transformations, $resource ) : null,
'signature' => self::get_settings_signature(),
'url_hash' => md5( $sized_url ),
'parent_hash' => md5( $parent_path ),
);
$insert_id = false;
$created = $wpdb->replace( Utils::get_relationship_table(), $data ); // phpcs:ignore WordPress.DB
if ( 0 < $created ) {
$insert_id = $wpdb->insert_id;
$media->update_post_meta( $attachment_id, Sync::META_KEYS['relationship'], self::get_settings_signature() );
}
return $insert_id;
}
/**
* Get a signature of the current settings that result in a sync check.
*
* @return string string
*/
public static function get_settings_signature() {
static $signature;
if ( ! $signature ) {
$settings = get_plugin_instance()->settings->get_value( 'cloudinary_url', 'sync_media' );
$signature = md5( wp_json_encode( $settings ) );
}
return $signature;
}
/**
* Setup early needed hooks.
*/
protected function setup_hooks() {
// Add filters.
add_filter( 'content_save_pre', array( $this, 'filter_out_cloudinary' ) );
add_action( 'save_post', array( $this, 'remove_replace_cache' ) );
add_action( 'cloudinary_string_replace', array( $this, 'catch_urls' ), 10, 2 );
add_filter( 'post_thumbnail_html', array( $this, 'process_featured_image' ), 100, 3 );
add_filter( 'cloudinary_current_post_id', array( $this, 'get_current_post_id' ) );
add_filter( 'the_content', array( $this, 'add_post_id' ) );
add_action( 'wp_resource_hints', array( $this, 'dns_prefetch' ), 10, 2 );
$metadata = Utils::METADATA;
foreach ( $metadata['actions'] as $action ) {
foreach ( $metadata['objects'] as $object ) {
$inline_action = str_replace( '{object}', $object, $action );
add_action( $inline_action, array( $this, 'maybe_filter_out_metadata' ), 10, 4 );
}
}
// Clear cache on taxonomy update.
$taxonomies = get_taxonomies( array( 'show_ui' => true ) );
foreach ( $taxonomies as $taxonomy ) {
add_action( "saved_{$taxonomy}", array( $this, 'clear_cache' ) );
}
}
/**
* Add DNS prefetch link tag for assets.
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for, e.g. 'preconnect' or 'prerender'.
*
* @return array
*/
public function dns_prefetch( $urls, $relation_type ) {
/**
* Filter to provide option to omit prefetch.
*
* @hook cloudinary_dns_prefetch_types
* @since 3.2.12
* @default array ( 'dns-prefetch', 'preconnect' )
*
* @param $types {array} The types of resource hints to use.
*
* @return {array} The modified resource hints to use.
*/
$resource_hints = apply_filters( 'cloudinary_dns_prefetch_types', array( 'dns-prefetch', 'preconnect' ) );
if ( in_array( $relation_type, $resource_hints, true ) ) {
$urls[] = $this->media->base_url;
}
return $urls;
}
/**
* Clear cached meta.
*/
public function clear_cache() {
/**
* Action to flush delivery caches.
*
* @hook cloudinary_flush_cache
* @since 3.0.0
*/
do_action( 'cloudinary_flush_cache' );
}
/**
* Delete cached metadata.
*
* @param bool $hard Whether to hard flush the cache.
*
* @hook cloudinary_flush_cache
*/
public function do_clear_cache( $hard = true ) {
delete_post_meta_by_key( self::META_CACHE_KEY );
if ( $hard ) {
wp_cache_flush();
}
}
/**
* Add the Post ID to images and videos.
*
* @param string $content The content.
*
* @return string
*/
public function add_post_id( $content ) {
return str_replace(
array(
'wp-image-',
'wp-video-',
),
array(
'wp-post-' . get_the_ID() . ' wp-image-',
'wp-post-' . get_the_ID() . ' wp-video-',
),
$content
);
}
/**
* Get the current post ID.
*
* @return int|null
*/
public function get_current_post_id() {
return $this->current_post_id ? $this->current_post_id : null;
}
/**
* Setup component.
*/
public function setup() {
$this->filter = $this->media->filter;
$this->sync = $this->media->sync;
$this->setup_hooks();
}
/**
* Init delivery.
*/
protected function init_delivery() {
// Reset internals.
$this->known = array();
$this->unknown = array();
$this->found_urls = array();
$this->unusable = array();
add_filter( 'wp_calculate_image_srcset', array( $this->media, 'image_srcset' ), 10, 5 );
/**
* Action indicating that the delivery is starting.
*
* @hook cloudinary_init_delivery
* @since 2.7.5
*
* @param $delivery {Delivery} The delivery object.
*/
do_action( 'cloudinary_init_delivery', $this );
}
/**
* Add classes to the featured image tag.
*
* @param string $html The image the HTML to add to.
* @param int $post_id Ignored.
* @param int $attachment_id The attachment_id.
*
* @return string
*/
public function process_featured_image( $html, $post_id, $attachment_id ) {
if ( empty( $html ) ) {
return $html; // Ignore empty tags.
}
$tags = $this->get_media_tags( $html, 'img' );
$tags = array_map( array( $this, 'parse_element' ), $tags );
$tags = array_filter( $tags );
foreach ( $tags as $tag_element ) {
// Get tag element.
$tag_element['id'] = $attachment_id;
$tag_element['context'] = $post_id;
$tag_element['atts']['class'][] = 'wp-image-' . $attachment_id;
$tag_element['atts']['class'][] = 'wp-post-' . $post_id;
if ( true === (bool) get_post_meta( $post_id, Global_Transformations::META_FEATURED_IMAGE_KEY, true ) ) {
$tag_element['atts']['class'][] = 'cld-overwrite';
}
$new_tag = HTML::build_tag( $tag_element['tag'], $tag_element['atts'] );
$html = str_replace( $tag_element['original'], $new_tag, $html );
}
return $html;
}
/**
* Delete the content replacement cache data.
*
* @param int $post_id The post ID to remove cache from.
*/
public function remove_replace_cache( $post_id ) {
delete_post_meta( $post_id, self::META_CACHE_KEY );
}
/**
* Find the attachment sizes from a list of URLS.
*/
public function find_attachment_size_urls() {
global $wpdb;
$dirs = wp_get_upload_dir();
$baseurl = Utils::clean_url( $dirs['baseurl'] );
$search = array();
foreach ( $this->unknown as $url ) {
$url = ltrim( str_replace( $baseurl, '', $url ), '/' );
$search[] = $url;
}
$search = array_unique( $search );
$in = implode( ',', array_fill( 0, count( $search ), '%s' ) );
// Prepare a query to find all in a single request.
$sql = $wpdb->prepare(
"SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value IN ({$in}) limit 1000", // phpcs:ignore WordPress.DB
$search
);
$key = md5( $sql );
$cached = wp_cache_get( $key );
$auto_sync = $this->sync->is_auto_sync_enabled();
if ( false === $cached ) {
$cached = array();
$results = $wpdb->get_results( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
if ( $results ) {
foreach ( $results as $result ) {
/**
* Get the contextualized post id.
*
* @hook cloudinary_contextualized_post_id
* @since 3.2.0
*
* @param $post_id {int} The post ID.
*
* @return {int}
*/
$post_id = apply_filters( 'cloudinary_contextualized_post_id', $result->post_id );
if ( ! $this->is_deliverable( $post_id ) ) {
continue;
}
// If we are here, it means that an attachment in the media library doesn't have a delivery for the url.
// Reset the signature for delivery and add to sync, to update it.
$this->create_delivery( $post_id );
if ( true === $auto_sync ) {
$this->sync->add_to_sync( $post_id );
}
$size = $this->get_sized( $post_id );
$key = ! empty( $size['sized_url'] ) ? $size['sized_url'] : wp_get_attachment_url( $post_id );
$cached[ $key ] = (int) $post_id;
}
}
wp_cache_add( $key, $cached );
}
$this->known = array_merge( $this->known, $cached );
$this->unknown = array_diff_key( $this->unknown, $this->known );
}
/**
* Get all the caches from found contexts.
*
* @return array
*/
protected function get_context_cache() {
$cached = array();
foreach ( $this->post_contexts as $id ) {
$has_cache = get_post_meta( $id, self::META_CACHE_KEY, true );
if ( ! empty( $has_cache ) ) {
foreach ( $has_cache as $type => $cache ) {
if ( ! isset( $cached[ $type ] ) ) {
$cached[ $type ] = array();
}
$cached[ $type ] = array_merge( $cached[ $type ], $cache );
}
}
}
return $cached;
}
/**
* Get all image and video tags that match our found urls.
*
* @param string $content HTML content.
* @param string $tags List of tags to get.
*
* @return array The media tags found.
*/
public function get_media_tags( $content, $tags = 'img|video' ) {
$media = array();
if ( preg_match_all( '#(?P<tags><(' . $tags . ')[^>]*\>){1}#is', $content, $found ) ) {
$count = count( $found[0] );