-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathutils.php
1294 lines (1132 loc) · 38.7 KB
/
utils.php
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
/**
* Utility functions
*
* @package distributor
*/
namespace Distributor\Utils;
use Distributor\DistributorPost;
/**
* Determine if this is a development install of Distributor.
*
* @since 2.0.0
*
* @return bool True if this is a development install, false otherwise.
*/
function is_development_version() {
return file_exists( DT_PLUGIN_PATH . 'composer.lock' );
}
/**
* Determine if we are on VIP
*
* @since 1.0
* @return boolean
*/
function is_vip_com() {
return ( defined( 'WPCOM_IS_VIP_ENV' ) && WPCOM_IS_VIP_ENV );
}
/**
* Determine if Gutenberg is being used.
*
* This duplicates the check from `use_block_editor_for_post()` in WordPress
* but removes the check for the `meta-box-loader` querystring parameter as
* it is not required for Distributor.
*
* @since 1.2
* @since 1.7 Update Gutenberg plugin sniff to avoid deprecated function.
* Update Classic Editor sniff to account for mu-plugins.
* @since 2.0 Duplicate the check from WordPress Core's `use_block_editor_for_post()`.
*
* @param int|WP_Post $post The post ID or object.
* @return boolean Whether post is using the block editor/Gutenberg.
*/
function is_using_gutenberg( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
// The posts page can't be edited in the block editor.
if ( absint( get_option( 'page_for_posts' ) ) === $post->ID && empty( $post->post_content ) ) {
return false;
}
// Make sure this post type supports Gutenberg
$use_block_editor = dt_use_block_editor_for_post_type( $post->post_type );
/** This filter is documented in wp-admin/includes/post.php */
return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
}
/**
* Get Distributor settings with defaults
*
* @since 1.0
* @return array
*/
function get_settings() {
$defaults = [
'override_author_byline' => true,
'media_handling' => 'featured',
'email' => '',
'license_key' => '',
'valid_license' => null,
];
$settings = get_option( 'dt_settings', [] );
$settings = wp_parse_args( $settings, $defaults );
return $settings;
}
/**
* Get Distributor network settings with defaults
*
* @since 1.2
* @return array
*/
function get_network_settings() {
$defaults = [
'email' => '',
'license_key' => '',
'valid_license' => null,
];
$settings = get_site_option( 'dt_settings', [] );
$settings = wp_parse_args( $settings, $defaults );
return $settings;
}
/**
* Hit license API to see if key/email is valid
*
* @param string $email Email address.
* @param string $license_key License key.
* @since 1.2
* @return bool
*/
function check_license_key( $email, $license_key ) {
$request = wp_remote_post(
'https://distributorplugin.com/wp-json/distributor-theme/v1/validate-license',
[
// phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout
'timeout' => 10,
'headers' => [
'X-Distributor-Version' => DT_VERSION,
],
'body' => [
'license_key' => $license_key,
'email' => $email,
],
]
);
if ( is_wp_error( $request ) ) {
return false;
}
if ( 200 === wp_remote_retrieve_response_code( $request ) ) {
return true;
}
return false;
}
/**
* Determine if plugin is in debug mode or not
*
* @since 1.0
* @return boolean
*/
function is_dt_debug() {
return ( defined( 'DISTRIBUTOR_DEBUG' ) && DISTRIBUTOR_DEBUG );
}
/**
* Given an array of meta, set meta to another post.
*
* Don't copy in excluded (Distributor) meta.
*
* @param int $post_id Post ID.
* @param array $meta Array of meta as key => value
*/
function set_meta( $post_id, $meta ) {
/**
* Fires before Distributor sets post meta.
*
* All sent meta is included in the `$meta` array, including excluded keys.
* Any excluded keys returned in this filter will be subsequently removed
* from the saved meta data.
*
* @since 2.0.0
* @hook dt_before_set_meta
*
* @param {array} $meta All received meta for the post
* @param {int} $post_id Post ID
*/
$meta = apply_filters( 'dt_before_set_meta', $meta, $post_id );
$existing_meta = get_post_meta( $post_id );
$excluded_meta = excluded_meta();
foreach ( $meta as $meta_key => $meta_values ) {
if ( in_array( $meta_key, $excluded_meta, true ) ) {
continue;
}
foreach ( (array) $meta_values as $meta_placement => $meta_value ) {
$has_prev_value = isset( $existing_meta[ $meta_key ] )
&& is_array( $existing_meta[ $meta_key ] )
&& array_key_exists( $meta_placement, $existing_meta[ $meta_key ] )
? true : false;
if ( $has_prev_value ) {
$prev_value = maybe_unserialize( $existing_meta[ $meta_key ][ $meta_placement ] );
}
if ( ! is_array( $meta_value ) ) {
$meta_value = maybe_unserialize( $meta_value );
}
if ( $has_prev_value ) {
update_post_meta( $post_id, wp_slash( $meta_key ), wp_slash( $meta_value ), $prev_value );
} else {
add_post_meta( $post_id, wp_slash( $meta_key ), wp_slash( $meta_value ) );
}
}
}
/**
* Fires after Distributor sets post meta.
*
* Note: All sent meta is included in the `$meta` array, including excluded keys.
* Take care to continue to filter out excluded keys in any further meta setting.
*
* @since 1.3.8
* @hook dt_after_set_meta
* @tutorial snippets
*
* @param {array} $meta All received meta for the post
* @param {array} $existing_meta Existing meta for the post
* @param {int} $post_id Post ID
*/
do_action( 'dt_after_set_meta', $meta, $existing_meta, $post_id );
}
/**
* Get post types available for pulling.
*
* This will compare the public post types from a remote site
* against the public post types from the origin site and return
* an array of post types supported on both.
*
* @param \Distributor\Connection $connection Connection object
* @param string $type Connection type
* @since 1.3
* @return array
*/
function available_pull_post_types( $connection, $type ) {
$post_types = array();
$local_post_types = array();
$remote_post_types = $connection->get_post_types();
$distributable_post_types = distributable_post_types();
// Return empty array, if the source site is not distributing any post type.
if ( empty( $remote_post_types ) || is_wp_error( $remote_post_types ) ) {
return [];
}
$local_post_types = array_diff_key( get_post_types( [ 'public' => true ], 'objects' ), array_flip( [ 'attachment', 'dt_ext_connection', 'dt_subscription' ] ) );
$available_post_types = array_intersect_key( $remote_post_types, $local_post_types );
if ( ! empty( $available_post_types ) ) {
foreach ( $available_post_types as $post_type ) {
$post_types[] = array(
'name' => 'external' === $type ? $post_type['name'] : $post_type->label,
'slug' => 'external' === $type ? $post_type['slug'] : $post_type->name,
);
}
}
/**
* Filter the post types that should be available for pull.
*
* Helpful for sites that want to pull custom post type content from another site into a different existing post type on the receiving end.
*
* @since 1.3.5
* @hook dt_available_pull_post_types
*
* @param {array} $post_types Post types available for pull with name and slug.
* @param {array} $remote_post_types Post types available from the remote connection.
* @param {array} $local_post_types Post types registered as public on the local site.
* @param {Connection} $connection Distributor connection object.
* @param {string} $type Distributor connection type.
*
* @return {array} Post types available for pull with name and slug.
*/
$pull_post_types = apply_filters( 'dt_available_pull_post_types', $post_types, $remote_post_types, $local_post_types, $connection, $type );
if ( ! empty( $pull_post_types ) ) {
$post_types = array();
foreach ( $pull_post_types as $post_type ) {
if ( in_array( $post_type['slug'], $distributable_post_types, true ) ) {
$post_types[] = $post_type;
}
}
}
return $post_types;
}
/**
* Return post types that are allowed to be distributed
*
* @param string $output Optional. The type of output to return.
* Accepts post type 'names' or 'objects'. Default 'names'.
*
* @since 1.0
* @since 1.7.0 $output parameter introduced.
* @return array
*/
function distributable_post_types( $output = 'names' ) {
$post_types = array_filter( get_post_types(), 'is_post_type_viewable' );
$exclude_post_types = [
'attachment',
'dt_ext_connection',
'dt_subscription',
];
foreach ( $exclude_post_types as $exclude_post_type ) {
unset( $post_types[ $exclude_post_type ] );
}
/**
* Filter post types that are distributable.
*
* @since 1.0.0
* @hook distributable_post_types
* @tutorial snippets
*
* @param {array} Post types that are distributable.
*
* @return {array} Post types that are distributable.
*/
$post_types = apply_filters( 'distributable_post_types', $post_types );
// Remove unregistered post types added via the filter.
$post_types = array_filter( $post_types, 'post_type_exists' );
if ( 'objects' === $output ) {
// Convert to objects.
$post_types = array_map( 'get_post_type_object', $post_types );
}
return $post_types;
}
/**
* Return post statuses that are allowed to be distributed.
*
* @since 1.0
* @return array
*/
function distributable_post_statuses() {
/**
* Filter the post statuses that are allowed to be distributed.
*
* By default only published posts can be distributed.
*
* @hook dt_distributable_post_statuses
*
* @param {array} $statuses Post statuses that are distributable. Default `publish`.
*
* @return {array} Post statuses that are distributable.
*/
return apply_filters( 'dt_distributable_post_statuses', array( 'publish' ) );
}
/**
* Returns list of excluded meta keys
*
* @since 1.2
* @deprecated 1.9.0 Use excluded_meta()
* @return array
*/
function blacklisted_meta() {
_deprecated_function( __FUNCTION__, '1.9.0', '\Distributor\Utils\excluded_meta()' );
return excluded_meta();
}
/**
* Returns list of excluded meta keys
*
* @since 1.9.0
* @return array
*/
function excluded_meta() {
/**
* Filter meta keys that are excluded from distribution.
*
* @since 1.0.0
* @deprecated 1.9.0 Use dt_excluded_meta
*
* @param array $meta_keys Excluded meta keys.
*
* @return array Excluded meta keys.
*/
$excluded_meta = apply_filters_deprecated(
'dt_blacklisted_meta',
[
[
'classic-editor-remember',
'dt_unlinked',
'dt_syndicate_time',
'dt_subscriptions',
'dt_subscription_update',
'dt_subscription_signature',
'dt_original_post_url',
'dt_original_post_id',
'dt_original_blog_id',
'dt_connection_map',
'_wp_old_slug',
'_wp_old_date',
'_wp_attachment_metadata',
'_wp_attached_file',
'_edit_lock',
'_edit_last',
],
],
'1.9.0',
'dt_excluded_meta',
__( 'Please consider writing more inclusive code.', 'distributor' )
);
/**
* Filter meta keys that are excluded from distribution.
*
* @since 1.9.0
* @hook dt_excluded_meta
* @tutorial snippets
*
* @param {array} $meta_keys Excluded meta keys. Default `dt_unlinked, dt_connection_map, dt_subscription_update, dt_subscriptions, dt_subscription_signature, dt_original_post_id, dt_original_post_url, dt_original_blog_id, dt_syndicate_time, _wp_attached_file, _wp_attachment_metadata, _edit_lock, _edit_last, _wp_old_slug, _wp_old_date`.
*
* @return {array} Excluded meta keys.
*/
return apply_filters( 'dt_excluded_meta', $excluded_meta );
}
/**
* Prepare meta for consumption
*
* @param int $post_id Post ID.
* @since 1.0
* @return array
*/
function prepare_meta( $post_id ) {
update_postmeta_cache( array( $post_id ) );
$meta = get_post_meta( $post_id );
if ( false === $meta ) {
return array();
}
$meta = is_array( $meta ) ? $meta : array();
$prepared_meta = array();
$excluded_meta = excluded_meta();
// Transfer all meta
foreach ( $meta as $meta_key => $meta_array ) {
foreach ( $meta_array as $meta_value ) {
if ( ! in_array( $meta_key, $excluded_meta, true ) ) {
$meta_value = maybe_unserialize( $meta_value );
/**
* Filter whether to sync meta.
*
* @hook dt_sync_meta
*
* @param {bool} $sync_meta Whether to sync meta. Default `true`.
* @param {string} $meta_key The meta key.
* @param {mixed} $meta_value The meta value.
* @param {int} $post_id The post ID.
*
* @return {bool} Whether to sync meta.
*/
if ( false === apply_filters( 'dt_sync_meta', true, $meta_key, $meta_value, $post_id ) ) {
continue;
}
$prepared_meta[ $meta_key ][] = $meta_value;
}
}
}
/**
* Filter prepared meta for consumption.
*
* Modify meta data before it is sent for consumption by a distributed
* post. The prepared meta data should not include any excluded meta.
* see `excluded_meta()`.
*
* @since 2.0.0
* @hook dt_prepared_meta
*
* @param {array} $prepared_meta Prepared meta.
* @param {int} $post_id Post ID.
*
* @return {array} Prepared meta.
*/
$prepared_meta = apply_filters( 'dt_prepared_meta', $prepared_meta, $post_id );
return $prepared_meta;
}
/**
* Format media items for consumption
*
* @param int $post_id Post ID.
* @since 1.0
* @return array
*/
function prepare_media( $post_id ) {
$dt_post = new DistributorPost( $post_id );
if ( ! $dt_post ) {
return array();
}
return $dt_post->get_media();
}
/**
* Format taxonomy terms for consumption
*
* @since 1.0
*
* @param int $post_id Post ID.
* @param array $args Taxonomy query arguments. See get_taxonomies().
* @return array[] Array of taxonomy terms.
*/
function prepare_taxonomy_terms( $post_id, $args = array() ) {
$post = get_post( $post_id );
if ( ! $post ) {
return array();
}
// Warm the term cache for the post.
update_object_term_cache( array( $post->ID ), $post->post_type );
if ( empty( $args ) ) {
$args = array( 'publicly_queryable' => true );
}
$taxonomy_terms = [];
$taxonomies = get_taxonomies( $args );
/**
* Filters the taxonomies that should be synced.
*
* @since 1.0
* @hook dt_syncable_taxonomies
*
* @param {array} $taxonomies Associative array list of taxonomies supported by current post in the format of `$taxonomy => $terms`.
* @param {WP_Post} $post The post object.
*
* @return {array} Associative array list of taxonomies supported by current post in the format of `$taxonomy => $terms`.
*/
$taxonomies = apply_filters( 'dt_syncable_taxonomies', $taxonomies, $post );
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_terms[ $taxonomy ] = wp_get_object_terms( $post_id, $taxonomy );
}
/**
* Filters the taxonomy terms for consumption.
*
* Modify taxonomies and terms prior to distribution. The array should be
* keyed by taxonomy. The returned data by filters should only return
* taxonomies permitted for distribution. See the `dt_syncable_taxonomies` hook.
*
* @since 2.0.0
* @hook dt_prepared_taxonomy_terms
*
* @param {array} $taxonomy_terms Associative array of terms keyed by taxonomy.
* @param {int} $post_id Post ID.
*
* @param {array} $args Modified array of terms keyed by taxonomy.
*/
$taxonomy_terms = apply_filters( 'dt_prepared_taxonomy_terms', $taxonomy_terms, $post_id );
return $taxonomy_terms;
}
/**
* Given an array of terms by taxonomy, set those terms to another post. This function will cleverly merge
* terms into the post and create terms that don't exist.
*
* @param int $post_id Post ID.
* @param array $taxonomy_terms Array with taxonomy as key and array of terms as values.
* @since 1.0
*/
function set_taxonomy_terms( $post_id, $taxonomy_terms ) {
// Now let's add the taxonomy/terms to syndicated post
foreach ( $taxonomy_terms as $taxonomy => $terms ) {
// Continue if taxonomy doesn't exist
if ( ! taxonomy_exists( $taxonomy ) ) {
continue;
}
$term_ids = [];
$term_id_mapping = [];
foreach ( $terms as $term_array ) {
if ( ! is_array( $term_array ) ) {
$term_array = (array) $term_array;
}
$term = get_term_by( 'slug', $term_array['slug'], $taxonomy );
// Create terms on remote site if they don't exist
/**
* Filter whether missing terms should be created.
*
* @since 1.0.0
* @hook dt_create_missing_terms
*
* @param {bool} true Whether missing terms should be created. Default `true`.
* @param {string} $taxonomy The taxonomy name.
* @param {array} $term_array Term data.
* @param {WP_Term|array|false} $term `WP_Term` object or `array` if found, `false` if not.
*
* @return {bool} Whether missing terms should be created.
*/
$create_missing_terms = apply_filters( 'dt_create_missing_terms', true, $taxonomy, $term_array, $term );
if ( empty( $term ) ) {
// Bail if terms shouldn't be created
if ( false === $create_missing_terms ) {
continue;
}
$term = wp_insert_term(
$term_array['name'],
$taxonomy,
[
'slug' => $term_array['slug'],
'description' => $term_array['description'],
]
);
if ( ! is_wp_error( $term ) ) {
$term_id_mapping[ $term_array['term_id'] ] = $term['term_id'];
$term_ids[] = $term['term_id'];
}
} else {
$term_id_mapping[ $term_array['term_id'] ] = $term->term_id;
$term_ids[] = $term->term_id;
}
}
// Handle hierarchical terms if they exist
/**
* Filter whether term hierarchy should be updated.
*
* @since 1.0.0
* @hook dt_update_term_hierarchy
*
* @param {bool} true Whether term hierarchy should be updated. Default `true`.
* @param {string} $taxonomy The taxonomy slug for the current term.
*
* @return {bool} Whether term hierarchy should be updated.
*/
$update_term_hierarchy = apply_filters( 'dt_update_term_hierarchy', true, $taxonomy );
if ( ! empty( $update_term_hierarchy ) ) {
foreach ( $terms as $term_array ) {
if ( ! is_array( $term_array ) ) {
$term_array = (array) $term_array;
}
if ( empty( $term_array['parent'] ) ) {
$term = wp_update_term(
$term_id_mapping[ $term_array['term_id'] ],
$taxonomy,
[
'parent' => '',
]
);
} elseif ( isset( $term_id_mapping[ $term_array['parent'] ] ) ) {
$term = wp_update_term(
$term_id_mapping[ $term_array['term_id'] ],
$taxonomy,
[
'parent' => $term_id_mapping[ $term_array['parent'] ],
]
);
}
}
}
wp_set_object_terms( $post_id, $term_ids, $taxonomy );
}
}
/**
* Given an array of media, set the media to a new post. This function will cleverly merge media into the
* new post deleting duplicates. Meta and featured image information for each image will be copied as well.
*
* @param int $post_id Post ID.
* @param array $media Array of media posts.
* @param array $args Additional args for set_media.
* @since 1.0
*/
function set_media( $post_id, $media, $args = [] ) {
$settings = get_settings(); // phpcs:ignore
$current_media_posts = get_attached_media( get_allowed_mime_types(), $post_id );
$current_media = [];
$args = wp_parse_args(
$args,
[
'use_filesystem' => false,
]
);
/**
* Allow filtering of the set_media args.
*
* @since 1.6.0
* @hook dt_set_media_args
*
* @param {array} $args List of args.
* @param {int} $post_id Post ID.
* @param {array} $media Array of media posts.
*
* @return {array} set_media args.
*/
$args = apply_filters( 'dt_set_media_args', $args, $post_id, $media );
// Create mapping so we don't create duplicates
foreach ( $current_media_posts as $media_post ) {
$original = get_post_meta( $media_post->ID, 'dt_original_media_url', true );
$current_media[ $original ] = $media_post->ID;
}
$found_featured_image = false;
// If we only want to process the featured image, remove all other media
if ( 'featured' === $settings['media_handling'] ) {
$featured_keys = wp_list_pluck( $media, 'featured' );
// Note: this is not a strict search because of issues with typecasting in some setups
$featured_key = array_search( true, $featured_keys ); // @codingStandardsIgnoreLine Ignore strict search requirement.
$media = ( false !== $featured_key ) ? array( $media[ $featured_key ] ) : array();
}
foreach ( $media as $media_item ) {
$args['source_file'] = $media_item['source_file'];
// Delete duplicate if it exists (unless filter says otherwise)
/**
* Filter whether media should be deleted and replaced if it already exists.
*
* @since 1.0.0
* @hook dt_sync_media_delete_and_replace
*
* @param {bool} true Whether pre-existing media should be deleted and replaced. Default `true`.
* @param {int} $post_id The post ID.
*
* @return {bool} Whether pre-existing media should be deleted and replaced.
*/
if ( apply_filters( 'dt_sync_media_delete_and_replace', true, $post_id ) ) {
if ( ! empty( $current_media[ $media_item['source_url'] ] ) ) {
wp_delete_attachment( $current_media[ $media_item['source_url'] ], true );
}
$image_id = process_media( $media_item['source_url'], $post_id, $args );
} else {
if ( ! empty( $current_media[ $media_item['source_url'] ] ) ) {
$image_id = $current_media[ $media_item['source_url'] ];
} else {
$image_id = process_media( $media_item['source_url'], $post_id, $args );
}
}
// Exit if the image ID is not valid.
if ( ! $image_id ) {
continue;
}
update_post_meta( $image_id, 'dt_original_media_url', $media_item['source_url'] );
update_post_meta( $image_id, 'dt_original_media_id', $media_item['id'] );
if ( $media_item['featured'] ) {
$found_featured_image = true;
set_post_thumbnail( $post_id, $image_id );
}
// Transfer all meta
if ( isset( $media_item['meta'] ) ) {
set_meta( $image_id, $media_item['meta'] );
}
// Transfer post properties
wp_update_post(
[
'ID' => $image_id,
'post_title' => $media_item['title'],
'post_content' => $media_item['description']['raw'],
'post_excerpt' => $media_item['caption']['raw'],
]
);
}
if ( ! $found_featured_image ) {
delete_post_meta( $post_id, '_thumbnail_id' );
}
}
/**
* This is a helper function for transporting/formatting data about a media post
*
* @param \WP_Post $media_post Media post.
* @param int $post_id Post ID.
* @since 1.0
* @return array
*/
function format_media_post( $media_post, $post_id = 0 ) {
$media_item = array(
'id' => $media_post->ID,
'title' => $media_post->post_title,
);
$media_item['featured'] = false;
if ( $post_id && (int) get_post_thumbnail_id( $post_id ) === $media_post->ID ) {
$media_item['featured'] = true;
}
$media_item['description'] = array(
'raw' => $media_post->post_content,
'rendered' => get_processed_content( $media_post->post_content ),
);
$media_item['caption'] = array(
'raw' => $media_post->post_excerpt,
);
$media_item['alt_text'] = get_post_meta( $media_post->ID, '_wp_attachment_image_alt', true );
$media_item['media_type'] = wp_attachment_is_image( $media_post->ID ) ? 'image' : 'file';
$media_item['mime_type'] = $media_post->post_mime_type;
/**
* Filter media details retrieved by `wp_get_attachment_metadata()`.
*
* @hook dt_get_media_details
*
* @param {array|false} $metadata Array of media metadata. `false` on failure.
* @param {int} $media_post->ID The media post ID.
*
* @return {array} Array of media metadata.
*/
$media_item['media_details'] = apply_filters( 'dt_get_media_details', wp_get_attachment_metadata( $media_post->ID ), $media_post->ID );
$media_item['post'] = $media_post->post_parent;
$media_item['source_url'] = wp_get_attachment_url( $media_post->ID );
$media_item['source_file'] = get_attached_file( $media_post->ID );
$media_item['meta'] = \Distributor\Utils\prepare_meta( $media_post->ID );
/**
* Filter formatted media item.
*
* @hook dt_media_item_formatted
*
* @param {array} $media_item Array of media item details.
* @param {int} $media_post->ID The media post ID.
*
* @return {array} Array of media item details.
*/
return apply_filters( 'dt_media_item_formatted', $media_item, $media_post->ID );
}
/**
* Simple function for sideloading media and returning the media id
*
* @param string $url URL of media.
* @param int $post_id Post ID that the media will be assigned to.
* @param array $args Additional args for process_media.
* @since 1.0
* @return int|bool
*/
function process_media( $url, $post_id, $args = [] ) {
global $wp_filesystem;
$args = wp_parse_args(
$args,
[
'use_filesystem' => false,
'source_file' => '',
]
);
/**
* Allow filtering of the process_media args.
*
* @since 1.6.0
* @hook dt_process_media_args
*
* @param array $args List of args.
* @param string $url URL of media.
* @param int $post_id Post ID.
*
* @return array Process media arguments.
*/
$args = apply_filters( 'dt_process_media_args', $args, $url, $post_id );
/**
* Filter allowed media extensions to be processed
*
* @since 1.3.7
* @hook dt_allowed_media_extensions
*
* @param {array} $allowed_extensions Allowed extensions array.
* @param {string} $url Media url.
* @param {int} $post_id Post ID.
*
* @return {array} Media extensions to be processed.
*/
$allowed_extensions = apply_filters( 'dt_allowed_media_extensions', array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ), $url, $post_id );
preg_match( '/[^\?]+\.(' . implode( '|', $allowed_extensions ) . ')\b/i', $url, $matches );
if ( ! $matches ) {
$media_name = null;
} else {
$media_name = basename( $matches[0] );
}
/**
* Filter name of the processing media.
*
* @since 1.3.7
* @hook dt_media_processing_filename
*
* @param {string} $media_name Filename of the media being processed.
* @param {string} $url Media url.
* @param {int} $post_id Post ID.
*
* @return {string} Filename of the media being processed.
*/
$media_name = apply_filters( 'dt_media_processing_filename', $media_name, $url, $post_id );
if ( is_null( $media_name ) ) {
return false;
}
$file_array = array();
$file_array['name'] = $media_name;
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$download_url = true;
$source_file = false;
$save_source_file_path = false;
if ( $args['use_filesystem'] && isset( $args['source_file'] ) && ! empty( $args['source_file'] ) ) {
$source_file = $args['source_file'];
if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base' ) ) {
$credentials = request_filesystem_credentials( site_url() );
wp_filesystem( $credentials );
}
// Copy the source file so we don't mess with the original file.
if ( $wp_filesystem->exists( $source_file ) ) {
$temp_name = wp_tempnam( $source_file );
$copied = $wp_filesystem->copy( $source_file, $temp_name, true );
if ( $copied ) {
/**
* Allow filtering whether to save the source file path.
*
* @since 1.6.0
* @hook dt_process_media_save_source_file_path
*
* @param {boolean} $save_file Whether to save the source file path. Default `false`.
*
* @return {boolean} Whether to save the source file path or not.
*/
$save_source_file_path = apply_filters( 'dt_process_media_save_source_file_path', false );
$file_array['tmp_name'] = $temp_name;
$download_url = false;
}
}
}
// Default for external or if a local file copy failed.
if ( $download_url ) {
// Set the scheme to http: if a relative URL is specified.
if ( str_starts_with( $url, '//' ) ) {
$url = 'http:' . $url;
}
// Allows to pull media from local IP addresses
// Uses a "magic number" for priority so we only unhook our call, just in case.
add_filter( 'http_request_host_is_external', '__return_true', 88 );
// Download file to temp location.
$file_array['tmp_name'] = download_url( $url );
remove_filter( 'http_request_host_is_external', '__return_true', 88 );
}
// If error storing temporarily, return the error.
if ( is_wp_error( $file_array['tmp_name'] ) ) {