-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathclass-sync.php
More file actions
1359 lines (1214 loc) · 42.2 KB
/
class-sync.php
File metadata and controls
1359 lines (1214 loc) · 42.2 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
/**
* Sync manages all of the sync components for the Cloudinary plugin.
*
* @package Cloudinary
*/
namespace Cloudinary;
use Cloudinary\Component\Assets;
use Cloudinary\Component\Setup;
use Cloudinary\Settings\Setting;
use Cloudinary\Sync\Delete_Sync;
use Cloudinary\Sync\Download_Sync;
use Cloudinary\Sync\Push_Sync;
use Cloudinary\Sync\Sync_Queue;
use Cloudinary\Sync\Upload_Sync;
use Cloudinary\Sync\Unsync;
use WP_Error;
/**
* Class Sync
*/
class Sync implements Setup, Assets {
/**
* Holds the plugin instance.
*
* @since 0.1
*
* @var Plugin Instance of the global plugin.
*/
public $plugin;
/**
* Contains all the different sync components.
*
* @var Delete_Sync[]|Push_Sync[]|Upload_Sync[]|Media[]|Unsync[]|Download_Sync[]
*/
public $managers;
/**
* Contains the sync base structure and callbacks.
*
* @var array
*/
protected $sync_base_struct;
/**
* Contains the sync types and callbacks.
*
* @var array
*/
protected $sync_types = array();
/**
* Holds a list of unsynced images to push on end.
*
* @var array
*/
private $to_sync = array();
/**
* Holds the settings slug.
*
* @var string
*/
public $settings_slug = 'sync_media';
/**
* Holds the sync settings object.
*
* @var Setting
*/
public $settings;
/**
* Holds the meta keys for sync meta to maintain consistency.
*/
const META_KEYS = array(
'breakpoints' => '_cloudinary_breakpoints',
'bypass' => '_bypass_delivery',
'cloudinary' => '_cloudinary',
'cloudinary_legacy' => '_cloudinary_v2',
'dashboard_cache' => '_cloudinary_dashboard_stats',
'delay' => '_cloudinary_sync_delay',
'delivery' => '_cloudinary_delivery',
'downloading' => '_cloudinary_downloading',
'file_size' => '_file_size',
'folder_sync' => '_folder_sync',
'last_oversize_check' => '_last_oversize_check',
'local_size' => '_cld_local_size',
'pending' => '_cloudinary_pending',
'plugin_version' => '_plugin_version',
'process_log' => '_cloudinary_process_log',
'process_log_legacy' => '_process_log',
'public_id' => '_public_id',
'queued' => '_cloudinary_sync_queued',
'relationship' => '_cld_relationship',
'remote_format' => '_cld_remote_format',
'remote_size' => '_cld_remote_size',
'signature' => '_sync_signature',
'storage' => '_cloudinary_storage',
'suffix' => '_suffix',
'sync_error' => '_cld_error',
'synced' => '_cld_synced',
'syncing' => '_cloudinary_syncing',
'transformation' => '_transformations',
'unsupported' => '_cld_unsupported',
'unsynced' => '_cld_unsynced',
'upgrading' => '_cloudinary_upgrading',
'version' => '_cloudinary_version',
'raw_url' => '_cloudinary_url',
'db_version' => '_cloudinary_db_version',
'debug' => '_cloudinary_debug',
);
/**
* Holds the Sync Media option key.
*/
const SYNC_MEDIA = 'cloudinary_sync_media';
/**
* Push_Sync constructor.
*
* @param Plugin $plugin Global instance of the main plugin.
*/
public function __construct( Plugin $plugin ) {
$this->plugin = $plugin;
$this->managers['push'] = new Push_Sync( $this->plugin );
$this->managers['upload'] = new Upload_Sync( $this->plugin );
$this->managers['download'] = new Download_Sync( $this->plugin );
$this->managers['delete'] = new Delete_Sync( $this->plugin );
$this->managers['queue'] = new Sync_Queue( $this->plugin );
$this->managers['unsync'] = new Unsync( $this->plugin );
// Register Settings.
add_filter( 'cloudinary_admin_pages', array( $this, 'settings' ) );
}
/**
* Setup assets/scripts.
*/
public function enqueue_assets() {
if ( $this->plugin->settings->get_param( 'connected' ) ) {
$data = array(
'restUrl' => esc_url_raw( Utils::rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
);
wp_add_inline_script( 'cloudinary', 'var cloudinaryApi = ' . wp_json_encode( $data ), 'before' );
}
}
/**
* Register Assets.
*/
public function register_assets() {
if ( $this->plugin->settings->get_param( 'connected' ) ) {
// Setup the sync_base_structure.
$this->setup_sync_base_struct();
// Setup sync types.
$this->setup_sync_types();
}
}
/**
* Is the component Active.
*/
public function is_active() {
return $this->settings && $this->settings->has_param( 'is_active' );
}
/**
* Checks if an asset has been synced and up to date.
*
* @param int $attachment_id The attachment id to check.
*
* @return bool
*/
public function been_synced( $attachment_id ) {
$been = false;
if ( $this->plugin->components['delivery']->is_deliverable( $attachment_id ) ) {
$public_id = $this->managers['media']->has_public_id( $attachment_id );
$meta = wp_get_attachment_metadata( $attachment_id, true );
$been = ! empty( $public_id ) || ! empty( $meta['cloudinary'] ); // From v1.
}
return $been;
}
/**
* Checks if an asset is synced and up to date.
*
* @param int $post_id The post id to check.
* @param bool $re_check Flag to bypass cache and recheck.
*
* @return bool
*/
public function is_synced( $post_id, $re_check = false ) {
static $synced = array();
if ( isset( $synced[ $post_id ] ) && false === $re_check ) {
return $synced[ $post_id ];
}
$return = false;
if ( $this->managers['media']->has_public_id( $post_id ) && $this->been_synced( $post_id ) ) {
$expecting = $this->generate_signature( $post_id );
if ( ! is_wp_error( $expecting ) ) {
$signature = $this->get_signature( $post_id );
// Sort to align orders for comparison.
ksort( $signature );
ksort( $expecting );
if ( ! empty( $signature ) && ! empty( $expecting ) && $expecting === $signature ) {
$return = true;
}
}
}
$synced[ $post_id ] = $return;
return $synced[ $post_id ];
}
/**
* Log a sync result.
*
* @param int $attachment_id The attachment id.
* @param string $type The sync type.
* @param mixed $result The result.
*/
public function log_sync_result( $attachment_id, $type, $result ) {
$log = $this->managers['media']->get_process_logs( $attachment_id, true );
$keys = $this->sync_base_struct;
if ( empty( $log ) || count( $log ) !== count( $keys ) ) {
$missing_keys = array_diff_key( $keys, $log );
$log = array_merge(
$log,
array_fill_keys( array_keys( $missing_keys ), array() )
);
}
if ( isset( $log[ $type ] ) ) {
if ( is_wp_error( $result ) ) {
$result = array(
'code' => $result->get_error_code(),
'message' => $result->get_error_message(),
);
update_post_meta( $attachment_id, self::META_KEYS['sync_error'], $result['message'] );
}
$log[ $type ][ '_' . time() ] = $result;
if ( 5 < count( $log[ $type ] ) ) {
array_shift( $log[ $type ] );
}
update_post_meta( $attachment_id, self::META_KEYS['process_log'], $log );
}
}
/**
* Check if sync type is required for rendering a Cloudinary URL.
*
* @param string|null $type The type to check.
* @param int $attachment_id The attachment ID.
*
* @return bool
*/
public function is_required( $type, $attachment_id ) {
$return = false;
if ( ! empty( $type ) && isset( $this->sync_base_struct[ $type ]['required'] ) ) {
if ( is_callable( $this->sync_base_struct[ $type ]['required'] ) ) {
$return = call_user_func( $this->sync_base_struct[ $type ]['required'], $attachment_id );
} else {
$return = $this->sync_base_struct[ $type ]['required'];
}
}
return $return;
}
/**
* Generate a signature based on whats required for a full sync.
*
* @param int $attachment_id The Attachment id to generate a signature for.
* @param bool $cache Flag to specify if a cached signature is to be used or build a new one.
*
* @return string|bool
*/
public function generate_signature( $attachment_id, $cache = true ) {
static $signatures = array(); // cache signatures.
if ( ! empty( $signatures[ $attachment_id ] ) && true === $cache ) {
$return = $signatures[ $attachment_id ];
} else {
$return = $this->sync_base( $attachment_id );
// Add to signature cache.
$signatures[ $attachment_id ] = $return;
}
return $return;
}
/**
* Check if an asset can be synced.
*
* @param int $attachment_id The attachment ID to check if it can be synced.
* @param string $type The type of sync to attempt.
*
* @return bool
*/
public function can_sync( $attachment_id, $type = 'file' ) {
$can = $this->is_auto_sync_enabled();
if ( $this->is_pending( $attachment_id ) ) {
$can = false;
} elseif ( $this->been_synced( $attachment_id ) ) {
$can = true;
}
if ( ! $this->managers['media']->is_uploadable_media( $attachment_id ) ) {
$can = false;
}
// Can sync only syncable delivery types.
if ( ! $this->is_syncable( $attachment_id ) ) {
$can = false;
}
// Only sync deliverable attachments.
if ( $can && ! $this->plugin->get_component( 'delivery' )->is_deliverable( $attachment_id ) ) {
$can = false;
}
/**
* Filter to allow changing if an asset is allowed to be synced.
* Return a WP Error with reason why it can't be synced.
*
* @param int $attachment_id The attachment post ID.
*
* @return bool|\WP_Error
*/
return apply_filters( 'cloudinary_can_sync_asset', $can, $attachment_id, $type );
}
/**
* Get the last version this asset was synced with.
*
* @param int $attachment_id The attachment ID.
*
* @return mixed
*/
public function get_sync_version( $attachment_id ) {
$version = $this->managers['media']->get_post_meta( $attachment_id, self::META_KEYS['plugin_version'], true );
return $version . '-' . $this->plugin->version;
}
/**
* Get the current sync signature of an asset.
*
* @param int $attachment_id The attachment ID.
* @param bool $cached Flag to specify if a cached signature is to be used or build a new one.
*
* @return array
*/
public function get_signature( $attachment_id, $cached = true ) {
static $signatures = array(); // Cache signatures already fetched.
$return = array();
if ( ! empty( $signatures[ $attachment_id ] ) && true === $cached ) {
$return = $signatures[ $attachment_id ];
} else {
$signature = $this->managers['media']->get_post_meta( $attachment_id, self::META_KEYS['signature'], true );
if ( empty( $signature ) ) {
$signature = array();
}
$signatures[ $attachment_id ] = $return;
// Remove any old or outdated signature items. against the expected.
if ( ! empty( $this->sync_types ) ) {
$signature = array_intersect_key( $signature, $this->sync_types );
$return = wp_parse_args( $signature, $this->sync_types );
}
}
/**
* Filter the get signature of the asset.
*
* @hook cloudinary_get_signature
*
* @param $return {array} The attachment signature.
* @param $attachment_id {int} The attachment ID.
*
* @return {array}
*/
$return = apply_filters( 'cloudinary_get_signature', $return, $attachment_id );
return $return;
}
/**
* Generate a new Public ID for an asset.
*
* @param int $attachment_id The attachment ID for the new public ID.
*
* @return string|null
*/
public function generate_public_id( $attachment_id ) {
$cld_folder = $this->managers['media']->get_cloudinary_folder();
if ( function_exists( 'wp_get_original_image_path' ) && wp_attachment_is_image( $attachment_id ) ) {
$file = wp_get_original_image_path( $attachment_id );
} else {
$file = get_attached_file( $attachment_id );
}
$filename = Utils::pathinfo( $file, PATHINFO_FILENAME );
$public_id = $cld_folder . $filename;
return ltrim( $public_id, '/' );
}
/**
* Is syncable asset.
*
* @param int $attachment_id The attachment ID.
*
* @return bool
*/
public function is_syncable( $attachment_id ) {
$syncable = false;
if (
$this->managers['media']->is_media( $attachment_id )
&& in_array(
$this->managers['media']->get_media_delivery( $attachment_id ),
$this->managers['media']->get_syncable_delivery_types(),
true
)
) {
$syncable = true;
}
if ( true === $syncable && $this->managers['media']->is_oversize_media( $attachment_id ) ) {
$syncable = false;
}
return $syncable;
}
/**
* Register a new sync type.
*
* @param string $type Sync type key. Must not exceed 20 characters and may
* only contain lowercase alphanumeric characters, dashes,
* and underscores. See sanitize_key().
* @param array $structure {
* Array of arguments for registering a sync type.
*
* @type callable $generate Callback method that generates the values to be used to sign a state.
* Returns a string or array.
*
* @type callable $validate Optional Callback method that validates the need to have the sync type applied.
* returns Bool.
*
* @type int $priority Priority in which the type takes place. Lower is higher priority.
* i.e a download should happen before an upload so download is lower in the chain.
*
* @type callable $sync Callback method that handles the sync. i.e uploads the file, adds meta data, etc..
*
* @type string $state State class to be added to the status icon in media library.
*
* @type string|callback $note The status text displayed next to a syncing asset in the media library.
* Can be a callback if the note needs to be dynamic. see type folder.
*
* }
*/
public function register_sync_type( $type, $structure ) {
// Apply a default to ensure parts exist.
$default = array(
'generate' => '__return_null',
'validate' => null,
'priority' => 50,
'sync' => '__return_null',
'state' => 'sync',
'note' => __( 'Synchronizing asset with Cloudinary', 'cloudinary' ),
'asset_state' => 1,
);
$this->sync_base_struct[ $type ] = wp_parse_args( $structure, $default );
}
/**
* Get built-in structures that form an assets entire sync state. This holds methods for building signatures for each state of synchronization.
* These can be extended via 3rd parties by adding to the structures with custom types and generation and sync methods.
*/
public function setup_sync_base_struct() {
$base_struct = array(
'upgrade' => array(
'generate' => array( $this, 'get_sync_version' ), // Method to generate a signature.
'validate' => array( $this, 'been_synced' ),
'priority' => 0.2,
'sync' => array( $this->managers['media']->upgrade, 'convert_cloudinary_version' ),
'state' => 'info syncing',
'note' => __( 'Upgrading from previous version', 'cloudinary' ),
'realtime' => true,
),
'download' => array(
'generate' => '__return_false',
'validate' => function ( $attachment_id ) {
return (bool) $this->managers['media']->get_post_meta( $attachment_id, self::META_KEYS['upgrading'], true );
},
'priority' => 1,
'sync' => array( $this->managers['download'], 'download_asset' ),
'state' => 'info downloading',
'note' => __( 'Downloading from Cloudinary', 'cloudinary' ),
),
'file' => array(
'asset_state' => 0,
'generate' => array( $this, 'generate_file_signature' ),
'priority' => 5.1,
'sync' => array( $this->managers['upload'], 'upload_asset' ),
'validate' => function ( $attachment_id ) {
$valid = ! $this->managers['media']->has_public_id( $attachment_id ) && ! $this->managers['media']->is_oversize_media( $attachment_id );
if ( $valid ) {
$valid = $this->plugin->get_component( 'delivery' )->is_deliverable( $attachment_id );
}
return $valid;
},
'state' => 'uploading',
'note' => __( 'Uploading to Cloudinary', 'cloudinary' ),
'required' => true, // Required to complete URL render flag.
),
'edit' => array(
'generate' => array( $this, 'generate_edit_signature' ),
'priority' => 5.2,
'sync' => array( $this->managers['upload'], 'edit_upload' ),
'validate' => function ( $attachment_id ) {
$valid = false;
$backup = get_post_meta( $attachment_id, '_wp_attachment_backup_sizes', true );
if ( ! empty( $backup ) ) {
$valid = true;
}
return $valid;
},
'state' => 'uploading',
'note' => __( 'Uploading to Cloudinary', 'cloudinary' ),
'required' => false, // Required to complete URL render flag.
'realtime' => true,
),
'folder' => array(
'generate' => array( $this->managers['media'], 'get_cloudinary_folder' ),
'validate' => array( $this->managers['media'], 'is_folder_synced' ),
'priority' => 10,
'sync' => array( $this->managers['upload'], 'upload_asset' ),
'state' => 'info syncing',
'note' => function () {
return sprintf(
/* translators: %s folder name */
__( 'Copying to folder %s.', 'cloudinary' ),
untrailingslashit( $this->managers['media']->get_cloudinary_folder() )
);
},
),
'public_id' => array(
'generate' => array( $this->managers['media'], 'get_public_id' ),
'validate' => function ( $attachment_id ) {
$public_id = $this->managers['media']->has_public_id( $attachment_id );
return false === $public_id;
},
'priority' => 20,
'sync' => array( $this->managers['media']->upgrade, 'convert_cloudinary_version' ), // Rename.
'state' => 'info syncing',
'note' => __( 'Updating metadata', 'cloudinary' ),
'required' => true,
),
'breakpoints' => array(
'generate' => array( $this->managers['media'], 'get_breakpoint_options' ),
'priority' => 25,
'sync' => array( $this->managers['upload'], 'explicit_update' ),
'validate' => function ( $attachment_id ) {
$delivery = $this->managers['media']->get_post_meta( $attachment_id, self::META_KEYS['delivery'], true );
return empty( $delivery ) || 'upload' === $delivery;
},
'state' => 'info syncing',
'note' => __( 'Updating breakpoints', 'cloudinary' ),
),
'options' => array(
'asset_state' => 0,
'generate' => function ( $attachment_id ) {
$options = $this->managers['media']->get_upload_options( $attachment_id );
unset( $options['eager'], $options['eager_async'] );
return $options;
},
'validate' => array( $this, 'been_synced' ),
'priority' => 30,
'sync' => array( $this->managers['upload'], 'context_update' ),
'state' => 'info syncing',
'note' => __( 'Updating metadata', 'cloudinary' ),
),
'cloud_name' => array(
'generate' => array( $this->managers['connect'], 'get_cloud_name' ),
'validate' => function ( $attachment_id ) {
$valid = true;
$credentials = $this->managers['connect']->get_credentials();
if ( isset( $credentials['cname'] ) ) {
$url = get_post_meta( $attachment_id, '_wp_attached_file', true );
if ( wp_http_validate_url( $url ) ) {
$domain = wp_parse_url( $url, PHP_URL_HOST );
$valid = $domain !== $credentials['cname'];
}
}
return $valid;
},
'priority' => 5.5,
'sync' => array( $this->managers['upload'], 'upload_asset' ),
'state' => 'uploading',
'note' => __( 'Uploading to new cloud name.', 'cloudinary' ),
'required' => true,
),
'meta_cleanup' => array(
'generate' => function ( $attachment_id ) {
$meta = $this->managers['media']->get_post_meta( $attachment_id );
$return = false;
foreach ( $meta as $key => $value ) {
if ( get_post_meta( $attachment_id, $key, true ) === $value ) {
$return = true;
break;
}
}
return $return;
},
'priority' => 100, // Always be the highest.
'sync' => function ( $attachment_id ) {
$meta = $this->managers['media']->get_post_meta( $attachment_id );
$cleanup_keys = array(
self::META_KEYS['cloudinary'],
self::META_KEYS['upgrading'],
);
foreach ( $meta as $key => $value ) {
if ( in_array( $key, $cleanup_keys, true ) ) {
$this->managers['media']->delete_post_meta( $attachment_id, $key );
continue;
}
delete_post_meta( $attachment_id, $key, $value );
}
$this->set_signature_item( $attachment_id, 'meta_cleanup' );
},
'required' => true,
'realtime' => true,
),
);
/**
* Filter the sync base structure to allow other plugins to sync component callbacks.
*
* @param array $base_struct The base sync structure.
*
* @return array
*/
$base_struct = apply_filters( 'cloudinary_sync_base_struct', $base_struct );
// Register each sync type.
foreach ( $base_struct as $type => $structure ) {
$this->register_sync_type( $type, $structure );
}
/**
* Do action for setting up sync types.
*
* @param \Cloudinary\Sync $this The sync object.
*/
do_action( 'cloudinary_register_sync_types', $this );
}
/**
* Setup the sync types in priority order based on sync struct.
*/
public function setup_sync_types() {
$sync_types = array();
foreach ( $this->sync_base_struct as $type => $struct ) {
if ( is_callable( $struct['sync'] ) ) {
$sync_types[ $type ] = floatval( $struct['priority'] );
}
}
asort( $sync_types );
$this->sync_types = $sync_types;
}
/**
* Get a method from a sync type.
*
* @param string $type The sync type to get from.
* @param string $method The method to get from the sync type.
*
* @return callable|null
*/
public function get_sync_type_method( $type, $method ) {
$return = null;
if ( isset( $this->sync_base_struct[ $type ][ $method ] ) && is_callable( $this->sync_base_struct[ $type ][ $method ] ) ) {
$return = $this->sync_base_struct[ $type ][ $method ];
}
return $return;
}
/**
* Run a sync method on and attachment_id.
*
* @param string $type The sync type to run.
* @param string $method The method to run.
* @param int $attachment_id The attachment ID to run method against.
*
* @return mixed
*/
public function run_sync_method( $type, $method, $attachment_id ) {
$return = null;
$run_method = $this->get_sync_type_method( $type, $method );
if ( $run_method ) {
$return = call_user_func( $run_method, $attachment_id );
}
return $return;
}
/**
* Generate a single sync type signature for an asset.
*
* @param string $type The sync type to run.
* @param int $attachment_id The attachment ID to run method against.
*
* @return mixed
*/
public function generate_type_signature( $type, $attachment_id ) {
$return = null;
$run_method = $this->get_sync_type_method( $type, 'generate' );
if ( $run_method ) {
$value = call_user_func( $run_method, $attachment_id );
if ( ! is_wp_error( $value ) ) {
if ( is_array( $value ) ) {
$value = wp_json_encode( $value );
}
$return = md5( $value );
}
}
return $return;
}
/**
* Get the asset state ( sync level ) of an attachment.
*
* @param int $attachment_id The attachment ID to get.
*
* @return int
*/
public function get_asset_state( $attachment_id ) {
$state = $this->been_synced( $attachment_id ) ? 1 : 0;
/**
* Filter the state of the asset.
*
* @hook cloudinary_asset_state
*
* @param $state {int} The attachment state.
* @param $attachment_id {int} The attachment ID.
*
* @return {array}
*/
return apply_filters( 'cloudinary_asset_state', $state, $attachment_id );
}
/**
* Prepares and asset for sync comparison by getting all sync types
* and running the generate methods for each type.
*
* @param int $attachment_id Attachment ID to prepare.
*
* @return array
*/
public function sync_base( $attachment_id ) {
$return = array();
$asset_state = $this->get_asset_state( $attachment_id );
if ( ! empty( $this->sync_types ) ) {
foreach ( array_keys( $this->sync_types ) as $type ) {
if ( $asset_state >= $this->sync_base_struct[ $type ]['asset_state'] ) {
$return[ $type ] = $this->generate_type_signature( $type, $attachment_id );
}
}
}
/**
* Filter the sync base to allow other plugins to add requested sync components for the sync signature.
*
* @hook cloudinary_sync_base
*
* @param $signatures {array} The attachments required signatures.
* @param $post {WP_Post} The attachment post.
* @param $sync {Sync} The sync object instance.
*
* @return {array}
*/
$return = apply_filters( 'cloudinary_sync_base', $return, get_post( $attachment_id ), $this );
return $return;
}
/**
* Prepare an asset to be synced, maybe.
*
* @param int $attachment_id The attachment ID.
*
* @return string | null
*/
public function maybe_prepare_sync( $attachment_id ) {
$type = $this->get_sync_type( $attachment_id );
$can = $this->can_sync( $attachment_id, $type );
if ( $type && true === $can ) {
$this->add_to_sync( $attachment_id );
}
return $type;
}
/**
* Get the type of sync, with the lowest priority for this asset.
*
* @param int $attachment_id The attachment ID.
* @param bool $cached Flag to specify if a cached signature is to be used or build a new one.
*
* @return string|null
*/
public function get_sync_type( $attachment_id, $cached = true ) {
if ( ! $this->managers['media']->is_media( $attachment_id ) || ! empty( get_post_meta( $attachment_id, self::META_KEYS['sync_error'], true ) ) ) {
return null; // Ignore non media items or errored syncs.
}
$return = null;
$required_signature = $this->generate_signature( $attachment_id, $cached );
$attachment_signature = $this->get_signature( $attachment_id, $cached );
$attachment_signature = array_intersect_key( $attachment_signature, $required_signature );
if ( is_array( $required_signature ) && ! empty( $this->sync_types ) ) {
$sync_items = array_filter(
$attachment_signature,
function ( $item, $key ) use ( $required_signature ) {
return $item !== $required_signature[ $key ];
},
ARRAY_FILTER_USE_BOTH
);
$ordered = array_intersect_key( $this->sync_types, $sync_items );
if ( ! empty( $ordered ) ) {
$types = array_keys( $ordered );
$type = array_shift( $types );
$return = $this->validate_sync_type( $type, $attachment_id );
}
}
return $return;
}
/**
* Validate the asset needs the sync type to be run, and generate a valid signature if not.
*
* @param string $type The sync type to validate.
* @param int $attachment_id The attachment ID to validate against.
*
* @return string|null
*/
public function validate_sync_type( $type, $attachment_id ) {
// Validate that this sync type applied (for optional types like upgrade).
if ( false === $this->run_sync_method( $type, 'validate', $attachment_id ) ) {
// If invalid, save the new signature.
$this->set_signature_item( $attachment_id, $type );
$type = $this->get_sync_type( $attachment_id, false ); // Set cache to false to get the new signature.
// Check if this is a realtime process.
} elseif ( ! empty( $this->sync_base_struct[ $type ]['realtime'] ) ) {
$result = $this->run_sync_method( $type, 'sync', $attachment_id );
if ( ! empty( $result ) ) {
$this->log_sync_result( $attachment_id, $type, $result );
}
$type = $this->get_sync_type( $attachment_id, false ); // Set cache to false to get the new signature.
}
return $type;
}
/**
* Checks the status of the media item.
*
* @param array $status Array of state and note.
* @param int $attachment_id The attachment id.
*
* @return array
*/
public function filter_status( $status, $attachment_id ) {
if ( $this->been_synced( $attachment_id ) || ( $this->is_pending( $attachment_id ) && $this->get_sync_type( $attachment_id ) ) ) {
$sync_type = $this->get_sync_type( $attachment_id );
if ( ! empty( $sync_type ) && isset( $this->sync_base_struct[ $sync_type ] ) ) {
// check process log in case theres an error.
$log = $this->managers['media']->get_process_logs( $attachment_id );
if ( ! empty( $log[ $sync_type ] ) && is_wp_error( $log[ $sync_type ] ) ) {
// Use error instead of sync note.
$status['state'] = 'error';
$status['note'] = $log[ $sync_type ]->get_error_message();
} else {
$status['state'] = $this->sync_base_struct[ $sync_type ]['state'];
$status['note'] = $this->sync_base_struct[ $sync_type ]['note'];
if ( is_callable( $status['note'] ) ) {
$status['note'] = call_user_func( $status['note'], $attachment_id );
}
}
}
// Check if there's an error.
$has_error = get_post_meta( $attachment_id, self::META_KEYS['sync_error'], true );
if ( ! empty( $has_error ) && $this->get_sync_type( $attachment_id ) ) {
$status['state'] = 'error';
$status['note'] = $has_error;
}
}
return $status;
}
/**
* Add media state to display syncing info.
*
* @param array $media_states List of the states.
* @param \WP_Post $post The current attachment post.
*
* @return array
*/
public function filter_media_states( $media_states, $post ) {
$status = apply_filters( 'cloudinary_media_status', array(), $post->ID );
if ( ! empty( $status ) ) {
$media_states[] = $status['note'];
}
return $media_states;
}
/**
* Check if the attachment is pending an upload sync.
*
* @param int $attachment_id The attachment ID to check.
*
* @return bool
*/
public function is_pending( $attachment_id ) {
// Check if it's not already in the to sync array.
if ( ! in_array( $attachment_id, $this->to_sync, true ) ) {
$is_pending = get_post_meta( $attachment_id, self::META_KEYS['pending'], true );
if ( empty( $is_pending ) || $is_pending < time() - 5 * 60 ) {
// No need to delete pending meta, since it will be updated with the new timestamp anyway.
return false;
}
}
return true;
}
/**
* Set an attachment as pending.
*
* @param int $attachment_id The attachment ID to set as pending.
*/
public function set_pending( $attachment_id ) {
update_post_meta( $attachment_id, self::META_KEYS['pending'], time() );
}
/**
* Add an attachment ID to the to_sync array.
*
* @param int $attachment_id The attachment ID to add.
*/
public function add_to_sync( $attachment_id ) {
if ( ! in_array( (int) $attachment_id, $this->to_sync, true ) ) {
// There are cases where we do not check can_sync. This is to make sure we don't add to the to_sync array if we can't sync.
if ( ! $this->plugin->get_component( 'delivery' )->is_deliverable( $attachment_id ) ) {
return;
}
// Flag image as pending to prevent duplicate upload.
$this->set_pending( $attachment_id );