-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathclass-media.php
More file actions
1323 lines (1179 loc) · 41.1 KB
/
class-media.php
File metadata and controls
1323 lines (1179 loc) · 41.1 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
/**
* Media class for the Cloudinary plugin.
*
* @package Cloudinary
*/
namespace Cloudinary;
use Cloudinary\Component\Setup;
use Cloudinary\Media\Filter;
use Cloudinary\Media\Upgrade;
use Cloudinary\Media\Global_Transformations;
use Cloudinary\Media\Video;
/**
* Class Media
*/
class Media implements Setup {
/**
* Holds the plugin instance.
*
* @since 0.1
*
* @var Plugin Instance of the global plugin.
*/
public $plugin;
/**
* Holds the base Cloudinary url.
*
* @since 0.1
*
* @var string.
*/
private $base_url;
/**
* Holds the Cloudinary folder.
*
* @since 0.1
*
* @var string.
*/
private $cloudinary_folder;
/**
* Holds the found Cloudinary ID's
*
* @since 0.1
*
* @var array.
*/
private $cloudinary_ids = array();
/**
* Cloudinary credentials.
*
* @var array.
*/
public $credentials;
/**
* Cloudinary url filtering instance.
*
* @var \Cloudinary\Media\Filter.
*/
public $filter;
/**
* Cloudinary upgrade instance.
*
* @var \Cloudinary\Media\Upgrade.
*/
public $upgrade;
/**
* Cloudinary global transformations.
*
* @var \Cloudinary\Media\Global_Transformations.
*/
public $global_transformations;
/**
* Video filter instance.
*
* @var \Cloudinary\Media\Video.
*/
public $video;
/**
* Flag if in image_downsize function to prevent overload.
*
* @var bool
*/
private $in_downsize = false;
/**
* Holds the max image width registered in WordPress.
*
* @var int
*/
private $max_width;
/**
* Media constructor.
*
* @param Plugin $plugin The global plugin instance.
*/
public function __construct( Plugin $plugin ) {
$this->plugin = $plugin;
}
/**
* Check if the attachment is a media file.
*
* @param int|\WP_Post $attachment The attachment to check.
*
* @return bool
*/
public function is_media( $attachment ) {
$is_media = false;
if ( 'attachment' === get_post_type( $attachment ) ) {
$is_media = $this->get_post_meta( $attachment, 'is_media', true );
if ( '' === $is_media ) {
$is_media = wp_attachment_is( 'image', $attachment ) || wp_attachment_is( 'video', $attachment );
$this->update_post_meta( $attachment, 'is_media', $is_media );
}
}
return $is_media;
}
/**
* Remove the crop size from a url.
*
* @param string $url The url to remove the crop from.
*
* @return string The uncropped url.
*/
public function uncropped_url( $url ) {
$cropped = $this->get_size_from_url( $url );
if ( false !== $cropped ) {
$file = pathinfo( $url );
$crop = '-' . implode( 'x', $cropped );
$file['filename'] = substr( $file['filename'], 0, strlen( $file['filename'] ) - strlen( $crop ) );
$url = $file['dirname'] . '/' . $file['filename'] . '.' . $file['extension'];
}
return $url;
}
/**
* Attempt to get an attachment_id from a url.
*
* @param string $url The url of the file.
*
* @return int The attachment id or 0 if not found.
*/
public function get_id_from_url( $url ) {
if ( $this->is_cloudinary_url( $url ) ) {
$path = wp_parse_url( $url, PHP_URL_PATH );
$parts = explode( '/', ltrim( $path, '/' ) );
// Need to find the version part as anything after this is the public id.
foreach ( $parts as $part ) {
array_shift( $parts ); // Get rid of the first element.
if ( 'v' === substr( $part, 0, 1 ) && is_numeric( substr( $part, 1 ) ) ) {
break; // Stop removing elements.
}
}
// The remaining items should be the file.
$file = implode( '/', $parts );
$pathinfo = pathinfo( $file );
$public_id = trim( $pathinfo['dirname'] . '/' . $pathinfo['filename'], './' );
$sync_key = $public_id;
$transformations = $this->get_transformations_from_string( $url );
if ( ! empty( $transformations ) ) {
$sync_key .= wp_json_encode( $transformations );
}
$attachment_id = $this->get_id_from_sync_key( $sync_key );
} else {
// Clear out any params.
if ( wp_parse_url( $url, PHP_URL_QUERY ) ) {
$url = strstr( $url, '?', true );
}
// Local URL.
$url = $this->uncropped_url( $url );
// Remove the base URL so we can match it to the post meta.
$dirs = wp_get_upload_dir();
$file = ltrim( substr( $url, strlen( $dirs['baseurl'] ) + 1 ), '/' ); // Keep the slash off.
if ( function_exists( 'wpcom_vip_attachment_url_to_postid' ) ) {
$attachment_id = wpcom_vip_attachment_url_to_postid( $file );
} else {
$attachment_id = attachment_url_to_postid( $file ); //phpcs:ignore
}
}
return $attachment_id;
}
/**
* Attempt to get an attachment_id from a sync key.
*
* @param string $sync_key Key for matching a post_id.
*
* @return int|false The attachment id or false if not found.
*/
public function get_id_from_sync_key( $sync_key ) {
$meta_query = array(
array(
'key' => '_' . md5( $sync_key ),
'compare' => 'EXISTS',
),
);
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => $meta_query, // phpcs:ignore
);
$query = new \WP_Query( $query_args );
$ids = $query->get_posts();
$attachment_id = false;
if ( ! empty( $ids ) ) {
// Essentially we should only have a single so use the first.
$attachment_id = array_shift( $ids );
}
return $attachment_id;
}
/**
* Get all ID's linked to a public_id.
*
* @param string $public_id Key for matching a post_id.
*
* @return array
*/
public function get_linked_attachments( $public_id ) {
$meta_query = array(
array(
'key' => '_' . md5( $public_id ),
'compare' => 'EXISTS',
),
);
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => $meta_query, // phpcs:ignore
);
$query = new \WP_Query( $query_args );
$ids = $query->get_posts();
return $ids;
}
/**
* Determine crop based on filename.
*
* @param string $url The url to get sizes from.
*
* @return array | bool Array of width and height else false if not found.
*/
public function get_size_from_url( $url ) {
$return = false;
// Check if its a cloudinary URL.
if ( $this->is_cloudinary_url( $url ) ) {
$transformations = $this->get_transformations_from_string( $url );
foreach ( $transformations as $transformation ) {
if ( ! empty( $transformation['crop'] ) && ! empty( $transformation['width'] ) && ! empty( $transformation['height'] ) ) {
$return = array(
$transformation['width'],
$transformation['height'],
);
break;
}
}
} else {
$file = pathinfo( $url );
$end_part = substr( strrchr( $file['filename'], '-' ), 1 );
if ( false !== $end_part || false !== strpos( $end_part, 'x' ) ) {
$size_parts = explode( 'x', $end_part );
$size_int = array_map( 'intval', $size_parts );
$size = array_filter( $size_int, 'is_int' );
if ( ! empty( $size ) && 2 === count( $size ) ) {
$return = $size;
}
}
}
return $return;
}
/**
* Get crop size of an image.
*
* @param string $url The url to get crop for.
* @param int $attachment_id image attachment id.
*
* @return array|bool The width and height of the crop, or false if size is custom.
*/
public function get_crop( $url, $attachment_id ) {
$meta = wp_get_attachment_metadata( $attachment_id );
if ( ! empty( $meta['sizes'] ) ) {
// Try and match the file name from the sizes meta data to prevent false positives from filenames that have numbers separated by an x.
$file = wp_basename( $url ); // We only need the base name to check.
$additional_sizes = wp_get_additional_image_sizes();
foreach ( $meta['sizes'] as $size_name => $size ) {
if ( $file === $size['file'] ) {
$cropped = false;
if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) {
$cropped = $additional_sizes[ $size_name ]['crop'];
}
// Make the WP Size array.
$wp_size = array(
'wpsize' => $size_name,
'width' => $size['width'],
'height' => $size['height'],
'crop' => $cropped ? 'fill' : 'scale',
);
if ( $cropped ) {
$wp_size['gravity'] = 'auto';
}
return $wp_size;
}
}
}
return false;
}
/**
* Set a transformation that is a single type only: quality, format.
*
* @param array $transformations The transformation set to check.
* @param string $type The type of transformation to set.
* @param string $value The value of the transformation.
* @param int|bool $index The index of the transformation array to set at.
*/
public function set_transformation( &$transformations, $type, $value, $index = false ) {
if ( false === $index ) {
$index = $this->get_transformation( $transformations, $type );
if ( false === $index ) {
$index = count( $transformations ); // Not found and no index set, append to transformation chain.
}
}
$transformations[ $index ][ $type ] = $value;
}
/**
* Check if a transformation exists.
*
* @param array $transformations The transformation set to check.
* @param string $type The type of transformation to check for.
*
* @return int|false
*/
public function get_transformation( $transformations, $type ) {
foreach ( $transformations as $index => $transformation ) {
if ( isset( $transformation[ $type ] ) ) {
return $index;
}
}
return false;
}
/**
* Extract the crop size part of a transformation that was done in the DAM widget.
*
* @param array $transformations The transformations to get crop from.
* @param array|bool $crop Optional crop size with width and height to balance transformations against.
*
* @return array|bool
*/
public function get_crop_from_transformation( $transformations, $crop = false ) {
if ( empty( $transformations ) ) {
return false;
}
$viable_parts = array_filter(
$transformations,
function ( $part ) {
$keys = array_keys( $part );
$return = false; // phpcs:ignore
foreach ( $keys as $key ) {
if ( in_array( $key, array( 'overlay', 'underlay' ), true ) ) {
return false; // end immediately since overlay and underlay has internal crops.
}
if ( in_array( $key, array( 'crop', 'width', 'height' ), true ) ) {
$return = true;
}
}
return $return;
}
);
if ( ! empty( $viable_parts ) ) {
// A final image size is determined by the last crop element.
$size = array_pop( $viable_parts );
if ( ! empty( $crop ) ) {
$size = $this->balance_crop( $crop, $size );
}
return $size;
}
return false;
}
/**
* Convert a url param based transformation string into an array.
*
* @param string $str The transformation string.
* @param string $type The type of transformation string.
*
* @return array The array of found transformations within the string.
*/
public function get_transformations_from_string( $str, $type = 'image' ) {
$params = \Cloudinary\Connect\Api::$transformation_index[ $type ];
$transformation_chains = explode( '/', $str );
$transformations = array();
foreach ( $transformation_chains as $index => $chain ) {
if ( false !== strpos( $chain, 'wpsize' ) ) {
continue; // A wpsize is not a transformation.
}
$items = explode( ',', $chain );
foreach ( $items as $item ) {
$item = trim( $item );
foreach ( $params as $param => $type ) {
if ( substr( $item, 0, strlen( $param ) + 1 ) === $param . '_' ) {
$transformations[ $index ][ $type ] = substr( $item, strlen( $param ) + 1 );
}
}
}
}
return array_values( $transformations ); // Reset the keys.
}
/**
* Get a cloudinary URL for an attachment.
*
* @param string $url The current url.
* @param int $attachment_id The attachment ID.
*
* @return string Cloudinary URL.
*/
public function attachment_url( $url, $attachment_id ) {
if ( ! doing_action( 'wp_insert_post_data' ) && wp_attachment_is( 'video', $attachment_id ) ) {
$cloudinary_id = $this->cloudinary_id( $attachment_id );
if ( false !== $cloudinary_id ) {
$url = $this->cloudinary_url( $attachment_id, $cloudinary_id );
}
}
return $url;
}
/**
* Apply default image transformations before building the URL.
*
* @param array $transformations The set of transformations.
* @param string $type Default transformations type.
*
* @return array
*/
public function apply_default_transformations( array $transformations, $type = 'image' ) {
// Base image level.
$new_transformations = array(
'image' => \Cloudinary\Connect\Api::generate_transformation_string( $transformations, $type ),
'global' => array(),
'tax' => array(),
'qf' => array(),
);
// Get Taxonomies.
$new_transformations['tax'] = $this->global_transformations->get_taxonomy_transformations( $type );
if ( ! $this->global_transformations->is_taxonomy_overwrite() ) {
// Get Lowest level.
$global = $this->global_transformations->globals[ $type ];
$default = array();
if ( 'video' === $type ) {
if ( isset( $global['video_limit_bitrate'] ) && 'on' === $global['video_limit_bitrate'] ) {
$default['bit_rate'] = $global['video_bitrate'] . 'k';
}
} else {
$default['fetch_format'] = $global[ $type . '_format' ] !== 'none' ? $global[ $type . '_format' ] : null;
if ( isset( $global[ $type . '_quality' ] ) ) {
$default['quality'] = $global[ $type . '_quality' ] !== 'none' ? $global[ $type . '_quality' ] : null;
} else {
$default['quality'] = 'auto';
}
}
$default = array_filter( $default ); // Clear out empty settings.
$new_transformations['qf'] = \Cloudinary\Connect\Api::generate_transformation_string( array( $default ), $type );
// Add freeform global transformations.
$freeform_type = $type . '_freeform';
if ( ! empty( $global[ $freeform_type ] ) ) {
$new_transformations['global'][] = trim( $global[ $freeform_type ] );
}
$new_transformations['global'] = implode( '/', $new_transformations['global'] );
}
// Clean out empty parts, and join into a sectioned string.
$new_transformations = array_filter( $new_transformations );
$new_transformations = implode( '/', $new_transformations );
// Take sectioned string, and create a transformation array set.
$transformations = $this->get_transformations_from_string( $new_transformations );
/**
* Filter the default cloudinary transformations.
*
* @param array $defaults The default transformations array.
*
* @return array
*/
$defaults = apply_filters(
'cloudinary_default_transformations',
$transformations
);
return $defaults;
}
/**
* Generate a Cloudinary URL based on attachment ID and required size.
*
* @param int $attachment_id The id of the attachment.
* @param array|string $size The wp size to set for the URL.
* @param array $transformations Set of transformations to apply to this url.
* @param string $cloudinary_id Optional forced cloudinary ID.
* @param bool $breakpoint Flag url is a breakpoint URL to stop re-applying default transformations.
* @param bool $clean Flag to present a clean url (With out a WP size variable.
*
* @return string|false The converted URL.
*/
public function cloudinary_url( $attachment_id, $size = array(), $transformations = array(), $cloudinary_id = null, $breakpoint = false, $clean = false ) {
if ( empty( $cloudinary_id ) ) {
$cloudinary_id = $this->cloudinary_id( $attachment_id );
}
if ( false === $cloudinary_id ) {
return false;
}
if ( empty( $transformations ) ) {
$transformations = $this->get_transformation_from_meta( $attachment_id );
}
// Get the attachment resource type.
$resource_type = wp_attachment_is( 'image', $attachment_id ) ? 'image' : 'video';
// Setup initial args for cloudinary_url.
$pre_args = array(
'secure' => is_ssl(),
'version' => $this->get_post_meta( $attachment_id, Sync::META_KEYS['version'], true ),
'resource_type' => $resource_type,
);
// Check size and correct if string or size.
if ( is_string( $size ) || ( is_array( $size ) && 3 === count( $size ) ) ) {
$intermediate = image_get_intermediate_size( $attachment_id, $size );
$size = $this->get_crop( $intermediate['url'], $attachment_id );
}
/**
* Filter the Cloudinary transformations.
*
* @param array $transformations Array of transformation options.
* @param int $attachment_id The id of the asset.
*
* @return array
*/
$pre_args['transformation'] = apply_filters( 'cloudinary_transformations', $transformations, $attachment_id );
// Defaults are only to be added on front, main images ( not breakpoints, since these are adapted down), and videos.
if ( ( ! defined( 'REST_REQUEST' ) || false === REST_REQUEST ) && ! is_admin() && false === $breakpoint ) {
$pre_args['transformation'] = $this->apply_default_transformations( $pre_args['transformation'], $resource_type );
}
// Make a copy as not to destroy the options in \Cloudinary::cloudinary_url().
$args = $pre_args;
$url = $this->plugin->components['connect']->api->cloudinary_url( $cloudinary_id, $args, $size, $clean );
/**
* Filter the final Cloudinary URL.
*
* @param string $url The Cloudinary URL.
* @param int $attachment_id The id of the attachment.
* @param array $pre_args The arguments used to create the url.
*
* @return string
*/
return apply_filters( 'cloudinary_converted_url', $url, $attachment_id, $pre_args );
}
/**
* Add domain to subdir.
*
* @param array $dirs The internal directory structures.
*
* @return array Altered array of paths.
*/
public function upload_dir( $dirs ) {
$folder = $this->cloudinary_folder;
$dirs['cloudinary_folder'] = trailingslashit( $folder );
return $dirs;
}
/**
* Get a public ID.
*
* @param int $attachment_id The Attachment ID.
*
* @return string A cloudinary public id.
*/
public function get_public_id( $attachment_id ) {
// Check for a public_id.
$public_id = $this->get_post_meta( $attachment_id, Sync::META_KEYS['public_id'], true );
if ( empty( $public_id ) ) {
// No public_id is an up-sync (WP->CLD).
// Build a public_id based on cloudinary folder, and filename.
$file = get_attached_file( $attachment_id );
$info = pathinfo( $file );
$cloudinary_folder = trailingslashit( $this->cloudinary_folder );
$public_id = $cloudinary_folder . $info['filename'];
}
return $public_id;
}
/**
* Get a Cloudinary ID.
*
* @param int $attachment_id The Attachment ID.
*
* @return string A cloudinary id.
*/
public function get_cloudinary_id( $attachment_id ) {
// A cloudinary_id is a public_id with a file extension.
$public_id = $this->get_public_id( $attachment_id );
$file = get_attached_file( $attachment_id );
$info = pathinfo( $file );
$cloudinary_id = $public_id . '.' . $info['extension'];
return $cloudinary_id;
}
/**
* Get a Cloudinary ID
*
* @param int $attachment_id The ID to get Cloudinary id for.
*
* @return string|bool the ID or false if not existing.
*/
public function cloudinary_id( $attachment_id ) {
if ( ! $this->is_media( $attachment_id ) ) {
return false;
}
// Return cached ID if we've already gotten it before.
if ( ! empty( $this->cloudinary_ids[ $attachment_id ] ) ) {
return $this->cloudinary_ids[ $attachment_id ];
}
$cloudinary_id = false;
if ( $this->plugin->components['sync']->is_synced( $attachment_id ) ) {
$cloudinary_id = $this->get_cloudinary_id( $attachment_id );
}
/**
* Filter the Cloudinary ID to allow extending it's availability.
*
* @param string|bool $cloudinary_id The public ID from Cloudinary, or false if not found.
* @param int $attachment_id The id of the asset.
*
* @return string|bool
*/
$cloudinary_id = apply_filters( 'cloudinary_id', $cloudinary_id, $attachment_id );
// Cache ID to prevent multiple lookups.
if ( false !== $cloudinary_id ) {
$this->cloudinary_ids[ $attachment_id ] = $cloudinary_id;
}
return $cloudinary_id;
}
/**
* Filter the requested image and return image source.
*
* @param null $image The null image value for short circuit check.
* @param int $attachment_id The ID of the attachment.
* @param string|array $size The requested size of the image.
*
* @return array|null The image array of size and url.
* @uses filter:image_downsize
*/
public function filter_downsize( $image, $attachment_id, $size ) {
// Don't do this while saving.
if ( true === $this->in_downsize || doing_action( 'wp_insert_post_data' ) || wp_attachment_is( 'video', $attachment_id ) ) {
return $image;
}
$cloudinary_id = $this->cloudinary_id( $attachment_id );
if ( false !== $cloudinary_id ) {
$this->in_downsize = true;
$image = image_downsize( $attachment_id, $size );
$this->in_downsize = false;
$image[0] = $this->convert_url( $image[0], $attachment_id );
}
return $image;
}
/**
* Convert an attachment URL to a Cloudinary one.
*
* @param string $url Url to convert.
* @param int $attachment_id Attachment ID.
* @param array $transformations Optional transformations.
*
* @return string Converted URL.
*/
public function convert_url( $url, $attachment_id, $transformations = array() ) {
$size = $this->get_crop( $url, $attachment_id );
return $this->cloudinary_url( $attachment_id, $size, $transformations, null, true );
}
/**
* Get the responsive breakpoints for the image.
*
* @param array $sources The original sources array.
* @param array $size_array The size array.
* @param string $image_src The original image source.
* @param array $image_meta The image meta array.
* @param int $attachment_id The attachment id.
*
* @return array Altered or same sources array.
*/
public function image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
$cloudinary_id = $this->cloudinary_id( $attachment_id );
if ( false === $cloudinary_id ) {
return $sources; // Return WordPress default sources.
}
// Get transformations from URL.
$transformations = $this->get_transformations_from_string( $image_src );
// Use Cloudinary breakpoints for same ratio.
if ( 'on' === $this->plugin->config['settings']['global_transformations']['enable_breakpoints'] && wp_image_matches_ratio( $image_meta['width'], $image_meta['height'], $size_array[0], $size_array[1] ) ) {
$meta = $this->get_post_meta( $attachment_id, Sync::META_KEYS['breakpoints'], true );
if ( ! empty( $meta ) ) {
// Since srcset is primary and src is a fallback, we need to set the first srcset with the main image.
$sources = array(
$size_array[0] => array(
'url' => $image_src,
'descriptor' => 'w',
'value' => $size_array[0],
),
);
// Check if the image has a crop.
$crop = $this->get_crop_from_transformation( $transformations );
if ( ! empty( $crop ) ) {
// Remove the crop from the transformation.
$transformations = array_filter(
$transformations,
function ( $item ) use ( $crop ) {
return $item !== $crop;
}
);
}
foreach ( $meta as $breakpoint ) {
$size = array(
'crop' => 'scale',
'width' => $breakpoint['width'],
);
$sources[ $breakpoint['width'] ] = array(
'url' => $this->cloudinary_url( $attachment_id, $size, $transformations, $cloudinary_id, true ),
'descriptor' => 'w',
'value' => $breakpoint['width'],
);
}
krsort( $sources, SORT_NUMERIC );
return $sources;
}
}
// Add the main size as the largest srcset src.
$crop = $this->get_crop_from_transformation( $transformations );
if ( ! empty( $crop ) ) {
// A valid crop could be just a crop mode and an edge size. Either width or height, or both.
$size = ! empty( $crop['width'] ) ? $crop['width'] : $crop['height'];
$type = ! empty( $crop['width'] ) ? 'w' : 'h';
$sources[ $size ] = array(
'url' => $image_src,
'descriptor' => $type,
'value' => $size,
);
}
// Use current sources, but convert the URLS.
foreach ( $sources as &$source ) {
if ( ! $this->is_cloudinary_url( $source['url'] ) ) {
$source['url'] = $this->convert_url( $source['url'], $attachment_id, $transformations );
}
}
return $sources;
}
/**
* Alter the image sizes metadata to match the Cloudinary ID so that WordPress can detect a matched source for responsive breakpoints.
*
* @param array $image_meta The image metadata array.
* @param array $size_array The size array.
* @param string $image_src The image src.
* @param int $attachment_id The attachment ID.
*
* @return array
*/
public function match_responsive_sources( $image_meta, $size_array, $image_src, $attachment_id ) {
if ( wp_attachment_is_image( $attachment_id ) && ! empty( $image_meta['sizes'] ) ) {
$cloudinary_id = $this->cloudinary_id( $attachment_id );
if ( $cloudinary_id ) {
// Set the file to the Cloudinary ID so that it will be matched.
$image_meta['file'] = $cloudinary_id;
}
}
return $image_meta;
}
/**
* Check if a url is a cloudinary url or not.
*
* @param string $url The url in question.
*
* @return bool
*/
public function is_cloudinary_url( $url ) {
if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
return false;
}
$test_parts = wp_parse_url( $url );
$cld_url = $this->plugin->components['connect']->api->asset_url;
return $test_parts['host'] === $cld_url;
}
/**
* Add media tab template.
*/
public function media_template() {
?>
<script type="text/html" id="tmpl-cloudinary-dam">
<div id="cloudinary-dam-{{ data.controller.cid }}" class="cloudinary-widget-wrapper"></div>
</script>
<?php
}
/**
* Setup and include cloudinary assets for DAM widget.
*/
public function editor_assets() {
// External assets.
wp_enqueue_script( 'cloudinary-media-library', 'https://media-library.cloudinary.com/global/all.js', array(), $this->plugin->version, true );
$params = array(
'nonce' => wp_create_nonce( 'wp_rest' ),
'mloptions' => array(
'cloud_name' => $this->credentials['cloud_name'],
'api_key' => $this->credentials['api_key'],
'cms_type' => 'wordpress',
'remove_header' => true,
'integration' => array(
'type' => 'wordpress_plugin',
'platform' => 'WordPress ' . get_bloginfo( 'version' ),
'version' => $this->plugin->version,
),
),
);
// Set folder if needed.
if ( ! empty( $this->cloudinary_folder ) ) {
$params['mloptions']['folder'] = array( 'path' => $this->cloudinary_folder );
}
$params['mloptions']['insert_transformation'] = true;
$params['mloptions']['inline_container'] = '#cloudinary-dam';
wp_add_inline_script( 'cloudinary-media-library', 'var CLDN = ' . wp_json_encode( $params ), 'before' );
}
/**
* Create a new attachment post item.
*
* @param array $asset The asset arrah data.
* @param string $public_id The cloudinary public id.
*
* @return int|\WP_Error
*/
private function create_attachment( $asset, $public_id ) {
// Create an attachment post.
$file_path = $asset['secure_url'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$post_args = array(
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
// Disable Upload_Sync to avoid sync loop.
add_filter( 'cloudinary_upload_sync_enabled', '__return_false' );
// Create the attachment.
$attachment_id = wp_insert_attachment( $post_args, false );
$sync_key = $public_id;
// Capture public_id. Use core update_post_meta since this attachment data doesnt exist yet.
update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], $public_id );
if ( ! empty( $asset['transformations'] ) ) {
// Save a combined key.
$sync_key .= wp_json_encode( $asset['transformations'] );
update_post_meta( $attachment_id, Sync::META_KEYS['transformation'], $asset['transformations'] );
}
// create a trackable key in post meta.
update_post_meta( $attachment_id, '_' . md5( $sync_key ), true );
// record a base to ensure primary isn't deleted.
update_post_meta( $attachment_id, '_' . md5( $public_id ), true );
// Capture the ALT Text.
if ( ! empty( $asset['context']['custom']['alt'] ) ) {
$alt_text = wp_strip_all_tags( $asset['context']['custom']['alt'] );
update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text );
}
return $attachment_id;
}
/**
* Balance a resize crop that's missing a height or width.
*
* @param array $size The current size.
* @param array $shift_size The size to balance to.
*
* @return array
*/
public function balance_crop( $size, $shift_size ) {
// Check if both width and height are present, and add missing dimension.
if ( empty( $shift_size['height'] ) ) {
$ratio_size = wp_constrain_dimensions( $size['width'], $size['height'], $shift_size['width'] );
$shift_size['height'] = $ratio_size[1];// Set the height.
} elseif ( empty( $shift_size['width'] ) ) {
// wp_constrain_dimensions only deals with width, so we pretend the image is a portrait to compensate.
$ratio_size = wp_constrain_dimensions( $size['height'], $size['width'], $shift_size['height'] );
$shift_size['width'] = $ratio_size[0];// Set the width.
}
return $shift_size;
}
/**
* Create and prepare a down sync asset from Cloudinary.
*/
public function down_sync_asset() {
$nonce = filter_input( INPUT_POST, 'nonce', FILTER_SANITIZE_STRING );
if ( wp_verify_nonce( $nonce, 'wp_rest' ) ) {
$args = array(
'asset' => array(
'flags' => FILTER_REQUIRE_ARRAY,
),
);
$data = filter_input_array( INPUT_POST, $args );
$asset = $data['asset'];
$public_id = filter_var( $asset['public_id'], FILTER_SANITIZE_STRING );
$format = filter_var( $asset['format'], FILTER_SANITIZE_STRING );
$sync_key = $public_id;