forked from WebDevStudios/WDS-Multisite-Aggregate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wds-multisite-aggregate.php
874 lines (714 loc) · 28 KB
/
wds-multisite-aggregate.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
<?php
/*
Plugin Name: WDS Multisite Aggregate
Plugin URI: https://github.com/WebDevStudios/WDS-Multisite-Aggregate
Description: Creates a blog where all the most recent posts on a WordPress network may be found. Based on WordPress MU Sitewide Tags Pages plugin by Donncha O Caoimh. WP-CLI: `wp multisite_aggregate --help`.
Version: 1.0.3.5
Author: WebDevStudios
Author URI: http://webdevstudios.com
*/
/* Copyright 2008 Donncha O Caoimh (http://ocaoimh.ie/)
With contributions by Ron Rennick(http://wpmututorials.com/), Thomas Schneider(http://www.im-web-gefunden.de/) and others.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Autoloads files with classes when needed
*
* @param string $class_name Name of the class being requested
*
* @since 1.0.0
*/
function wds_ma_autoload_classes( $class_name ) {
if ( class_exists( $class_name, false ) ) {
return;
}
$file = dirname( __FILE__ ) . '/includes/' . $class_name . '.php';
if ( file_exists( $file ) ) {
@include_once( $file );
}
}
spl_autoload_register( 'wds_ma_autoload_classes' );
/**
* Get it started
*
* @since 1.0.0
*/
class WDS_Multisite_Aggregate {
protected $imported = [];
protected $total_imported = 0;
protected $doing_save_post = false;
protected $debug = false;
protected static $orig_img_url_key = '_wds_orig_image_url';
protected \WP_Post $post;
protected int $post_id = 0;
protected WDS_Multisite_Aggregate_Options $options;
protected WDS_Multisite_Aggregate_Admin $admin;
protected WDS_Multisite_Aggregate_Remove $remove;
protected WDS_Multisite_Aggregate_Frontend $frontend;
protected array $meta_to_sync = [];
public function __construct() {
// Options setter/getter and handles updating options on save
$this->options = new WDS_Multisite_Aggregate_Options();
$this->options->hooks();
// Handles Admin display
$this->admin = new WDS_Multisite_Aggregate_Admin( $this->options );
$this->admin->hooks();
// Handles removing posts from removed blogs
$this->remove = new WDS_Multisite_Aggregate_Remove( $this->options );
$this->remove->hooks();
// Handles frontend modification for aggregate site
$this->frontend = new WDS_Multisite_Aggregate_Frontend( $this->options );
$this->frontend->hooks();
if ( isset( $_REQUEST['aggregate_debug'] ) ) {
$this->debug = new WDS_Multisite_Aggregate_Debug();
$this->debug->hooks();
}
}
function hooks() {
add_action( 'save_post', [ $this, 'do_post_sync' ], 10, 2 );
add_action( 'wds_multisite_aggregate_post_sync', [ $this, 'save_meta_fields' ], 10, 3 );
add_action( 'wp_update_comment_count', [ $this, 'do_comment_sync' ] );
add_action( 'updated_post_meta', [ $this, 'update_thumbnail_meta' ], 10, 4 );
add_action( 'trash_post', [ $this, 'sync_post_delete' ] );
add_action( 'delete_post', [ $this, 'sync_post_delete' ] );
add_action( 'deleted_post_meta', [ $this, 'delete_thumbnail_meta' ], 10, 3 );
if ( ! empty( $_GET['action'] ) && 'populate_posts_from_blog' == $_GET['action'] ) {
define( 'WDS_Multisite_Aggregate', true );
add_action( 'init', [ $this, 'populate_posts_from_blog' ], 8 );
}
if ( ! empty( $_GET['page'] ) && 'wds-multisite-aggregate' == $_GET['page'] ) {
add_action( 'admin_init', [ $this, 'context_hooks' ] );
}
}
public function context_hooks() {
if ( isset( $_GET['total_imported'] ) ) {
add_action( 'all_admin_notices', [ $this, 'user_notice' ] );
}
$valid_nonce = isset( $_REQUEST['_wpnonce'] ) ? wp_verify_nonce( $_REQUEST['_wpnonce'], 'wds-multisite-aggregate' ) : false;
if ( ! $valid_nonce ) {
return;
}
if ( isset( $_GET['action'] ) && 'populate_from_blogs' == $_GET['action'] ) {
return $this->populate_from_blogs();
}
if ( ! empty( $_POST ) ) {
$this->options->update_options();
}
}
function populate_from_blogs() {
global $wpdb;
$this->total_imported = $this->options->make_integer_from_request( 'total_imported' );
$post_count = $this->options->make_integer_from_request( 'post_count' );
// Check query string
$blogs_to_import = $this->options->comma_delimited_to_array_from_request( 'blogs_to_import' );
// No query string? Check options
$blogs_to_import = ! empty( $blogs_to_import ) ? $blogs_to_import : $this->get_blogs_to_import();
$tags_blog_id = $this->options->get( 'tags_blog_id' );
if ( ! $tags_blog_id || empty( $blogs_to_import ) ) {
return false;
}
$blog_to_populate = array_shift( $blogs_to_import );
if ( $blog_to_populate != $tags_blog_id ) {
$this->imported = [];
$details = get_blog_details( $blog_to_populate );
$url = add_query_arg( [
'post_count' => $post_count,
'action' => 'populate_posts_from_blog',
'key' => md5( serialize( $details ) ),
], $details->siteurl );
$post_count = 0;
$_post_count = 0;
$result = wp_remote_get( $url, [ 'timeout' => 180 ] );
if ( is_wp_error( $result ) ) {
wp_die( $result->get_error_message() );
}
$response = wp_remote_retrieve_body( $result );
if ( $response ) {
$json = json_decode( $response );
$data = $json->success ? $json->data : false;
if ( $data ) {
$this->total_imported = $this->total_imported + count( $data->posts_imported );
$this->imported = (array) $data->posts_imported;
$_post_count = (int) $data->posts_done;
}
}
if ( $_post_count ) {
$post_count = $_post_count;
}
}
if ( $post_count || ! empty( $blogs_to_import ) ) {
$url = network_admin_url( 'settings.php' );
$args = [
'page' => 'wds-multisite-aggregate',
'action' => 'populate_from_blogs',
'post_count' => $post_count,
'total_imported' => (int) $this->total_imported,
'next_blog' => true,
];
if ( ! empty( $blogs_to_import ) ) {
$args['blogs_to_import'] = implode( ',', $blogs_to_import );
}
$url = add_query_arg( $args, wp_nonce_url( $url, 'wds-multisite-aggregate' ) );
$count = $this->strong_red( count( $this->imported ) );
$finished_blog = $this->strong_red( sprintf( __( 'Blog %d', 'wds-multisite-aggregate' ), (int) $blog_to_populate ), false );
$next_blog = $this->strong_red( sprintf( __( 'Blog %d', 'wds-multisite-aggregate' ), array_shift( $blogs_to_import ) ), false );
$msg = $this->heading( sprintf( __( 'Imported %s posts from %s', 'wds-multisite-aggregate' ), $count, $finished_blog ) );
$desc = $this->notice_description( sprintf( __( 'Please wait while posts from %s are imported.', 'wds-multisite-aggregate' ), $next_blog ) );
wp_die( $msg . $desc . $this->js_redirect( $url, 1 ) );
}
$this->save_user_notice();
wp_redirect( $this->admin->url() );
exit;
}
/**
* run populate function in local blog context because get_permalink does not produce the correct permalinks while switched
*/
function populate_posts_from_blog() {
global $wpdb;
$valid_key = isset( $_REQUEST['key'] ) ? $_REQUEST['key'] == md5( serialize( get_blog_details( $wpdb->blogid ) ) ) : false;
if ( ! $valid_key ) {
return $this->error( 'not a valid key.' );
}
$this->_populate_posts_from_blog( [
'post_count' => isset( $_GET['post_count'] ) ? (int) $_GET['post_count'] : 0,
] );
}
/**
* run populate function in local blog context because get_permalink does not produce the correct permalinks while switched
*/
function _populate_posts_from_blog( $args = [] ) {
global $wpdb;
$tags_blog_id = $this->options->get( 'tags_blog_id' );
$tags_blog_enabled = $this->options->get( 'tags_blog_enabled' );
if ( ! $tags_blog_enabled || ! $tags_blog_id || $tags_blog_id == $wpdb->blogid ) {
return $this->error( 'Aggregate blog not enabled OR there is no aggregate blog ID OR the current site IS the aggregate blog.' );
}
$posts_done = 0;
$post_count = isset( $args['post_count'] ) ? (int) $args['post_count'] : 0; // post count
$allowed_post_types = apply_filters( 'sitewide_tags_allowed_post_types', [ 'post' => true ] );
$post_types = array_keys( array_filter( $allowed_post_types, function ( $e ) {
return $e;
} ) );
$max_posts_per_loop = 1000;
$max_posts_per_query = $max_posts_per_loop / 10;
while ( $posts_done < $max_posts_per_loop ) {
$args = [
'fields' => 'ids',
'offset' => $post_count + $posts_done,
'posts_per_page' => $max_posts_per_query,
'post_status' => 'publish',
'post_type' => $post_types,
];
$posts = get_posts( $args );
if ( empty( $posts ) ) {
return $this->success( [
'posts_done' => 0,
'posts_imported' => $this->imported,
] );
}
foreach ( $posts as $post ) {
if ( 1 != $post && 2 != $post ) {
$maybe_error = $this->do_post_sync( $post, get_post( $post ) );
if ( $maybe_error ) {
return $this->error( $maybe_error );
}
}
}
$posts_done += $max_posts_per_query;
}
return $this->success( [
'posts_done' => $posts_done,
'posts_imported' => $this->imported,
] );
exit( $posts_done );
}
function do_post_sync( $post_id, $post_in ) {
// Lets clone the post so we don't modify the original ML 08/04/2023 20:05:52
$post = clone $post_in;
$this->post_id = $post_id;
$this->post = $post;
if ( $this->doing_save_post ) {
$this->doing_save_post = false;
return;
}
if ( $error = $this->check_for_site_problems() ) {
return $this->error_if_wpcli( $error );
}
// wp_insert_category()
include_once( ABSPATH . 'wp-admin/includes/admin.php' );
$allowed_post_types = apply_filters( 'sitewide_tags_allowed_post_types', [ 'post' => true ] );
if ( ! isset( $allowed_post_types[ $post->post_type ] ) || ! $allowed_post_types[ $post->post_type ] ) {
return;
}
$post_categories = wp_get_object_terms( $post_id, 'category' );
if ( $post_categories && ! is_wp_error( $post_categories ) && is_array( $post_categories ) ) {
$post->post_category = wp_list_pluck( $post_categories, 'term_id' );
} else {
$post->post_category = wp_get_post_categories( $post_id );
}
$post->tags_input = implode( ', ', wp_get_post_tags( $post_id, [ 'fields' => 'names', ] ) );
global $wpdb;
$post_blog_id = $wpdb->blogid;
$post->guid = "{$post_blog_id}.{$post_id}";
$this->meta_to_sync = [];
$meta_keys = apply_filters( 'sitewide_tags_meta_keys', $this->options->get( 'tags_blog_postmeta', [] ) );
if ( is_array( $meta_keys ) && ! empty( $meta_keys ) ) {
foreach ( $meta_keys as $key ) {
$this->meta_to_sync[ $key ] = get_post_meta( $post->ID, $key, true );
}
}
unset( $meta_keys );
$this->meta_to_sync['permalink'] = get_permalink( $post_id );
$this->meta_to_sync['blogid'] = $post_blog_id; // org_blog_id
// Post thumbnail
if ( $this->options->get( 'tags_blog_thumbs' ) && ( $thumb_id = get_post_thumbnail_id( $post->ID ) ) ) {
// URL for later import in aggregating blog
$this->meta_to_sync['thumbnail_url'] = wp_get_attachment_url( $thumb_id );
// Back compatibility
$thumb_sizes = apply_filters( 'sitewide_tags_thumb_size', [
'thumbnail',
] );
// Backer (!) compatibility
if ( is_string( $thumb_sizes ) ) {
$this->meta_to_sync['thumbnail_html'] = wp_get_attachment_image( $thumb_id, $thumb_sizes );
} else {
// back-compat
$this->meta_to_sync['thumbnail_html'] = wp_get_attachment_image( $thumb_id, 'thumbnail' );
}
// new(ish) hawtness
foreach ( (array) $thumb_sizes as $thumb_size ) {
$this->meta_to_sync["thumbnail_html_$thumb_size"] = wp_get_attachment_image( $thumb_id, $thumb_size );
}
}
// custom taxonomies
$taxonomies = apply_filters( 'sitewide_tags_custom_taxonomies', [] );
if ( ! empty( $taxonomies ) && 'publish' == $post->post_status ) {
$registered_tax = array_diff( get_taxonomies(), [ 'post_tag', 'category', 'link_category', 'nav_menu' ] );
$custom_tax = array_intersect( $taxonomies, $registered_tax );
$tax_input = [];
foreach ( $custom_tax as $tax ) {
$terms = wp_get_object_terms( $post_id, $tax, [ 'fields' => 'names' ] );
if ( empty( $terms ) ) {
continue;
}
if ( is_taxonomy_hierarchical( $tax ) ) {
$tax_input[ $tax ] = $terms;
} else {
$tax_input[ $tax ] = implode( ',', $terms );
}
}
if ( ! empty( $tax_input ) ) {
$post->tax_input = $tax_input;
}
}
$tags_blog_id = $this->options->get( 'tags_blog_id' );
switch_to_blog( $tags_blog_id );
// Filter categories before handling
$post_categories = apply_filters( 'wds_multisite_aggregate_filter_categories', $post_categories );
$category_ids = [];
if ( is_array( $post_categories ) && ! empty( $post_categories ) && 'publish' == $post->post_status ) {
foreach ( $post_categories as $t => $category ) {
$term = get_term_by( 'slug', $category->slug, 'category' );
$term = apply_filters( 'sitewide_tags_get_term', $term, $category, $this );
if ( $this->debug ) {
echo '<xmp>$category_to_migrate: ' . print_r( $category, true ) . '</xmp>';
echo '<xmp>$term_on_aggregate: ' . print_r( $term, true ) . '</xmp>';
}
if ( $term && 0 == $term->parent ) {
$category_ids[] = $term->term_id;
continue;
}
// Here is where we insert the category if necessary
$category_id = wp_insert_category( [
'cat_name' => $category->name,
'category_description' => $category->name,
'category_nicename' => $category->slug,
'category_parent' => '',
], true );
if (
is_wp_error( $category_id )
&& false !== stripos( $category_id->get_error_message(), 'already exists' )
&& is_numeric( $category_id->get_error_data() )
) {
$category_ids[] = $category_id->get_error_data();
} elseif ( is_numeric( $category_id ) ) {
$category_ids[] = $category_id;
}
}
}
if ( $this->debug ) {
wp_die( '<xmp>$category_ids_to_add_to_post: ' . print_r( $category_ids, true ) . '</xmp>' );
}
$global_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE guid IN (%s,%s)", $post->guid, esc_url( $post->guid ) ) );
if ( 'publish' != $post->post_status && is_object( $global_post ) && isset( $global_post->ID ) ) {
wp_delete_post( $global_post->ID );
} else {
if ( isset( $global_post->ID ) && $global_post->ID != '' ) {
$post->ID = $global_post->ID; // editing an old post
foreach ( array_keys( $this->meta_to_sync ) as $key ) {
delete_post_meta( $global_post->ID, $key );
}
} else {
unset( $post->ID ); // new post
}
}
if ( 'publish' == $post->post_status ) {
$post->ping_status = 'closed';
$post->comment_status = 'closed';
// Use the category IDs in the post
$post->post_category = $category_ids;
$this->doing_save_post = true;
$post_id = wp_insert_post( $post, true );
if ( ! is_wp_error( $post_id ) ) {
// do meta sync action
do_action( 'wds_multisite_aggregate_post_sync', $post_id, $post, $this->meta_to_sync );
$this->imported[] = $post;
}
}
restore_current_blog();
}
function check_for_site_problems() {
global $wpdb;
if ( ! $this->options->get( 'tags_blog_enabled' ) ) {
return __( 'Multisite Aggregate not enabled.', 'wds-multisite-aggregate' );
}
$tags_blog_id = $this->options->get( 'tags_blog_id' );
if ( ! $tags_blog_id || $tags_blog_id == $wpdb->blogid ) {
return __( 'No Multisite Aggregate blog ID, or current blog is Multisite Aggregate blog.', 'wds-multisite-aggregate' );
}
$blogs_to_import = $this->get_blogs_to_import();
if ( ! in_array( (int) $wpdb->blogid, $blogs_to_import ) ) {
return __( 'Blog ID is not saved to the "Blogs to Aggregate" setting.', 'wds-multisite-aggregate' );
}
$blog_status = get_blog_status( $wpdb->blogid, 'public' );
if ( 1 != $blog_status && ( 0 != $blog_status || 1 == $this->options->get( 'tags_blog_public' ) || 0 == $this->options->get( 'tags_blog_pub_check' ) ) ) {
return __( "This blog's status is not set to public", 'wds-multisite-aggregate' );
}
return false;
}
public function save_meta_fields( $post_id, $post, $meta_to_sync ) {
$updated = [];
if ( $this->options->get( 'tags_blog_thumbs' ) && ! empty( $meta_to_sync['thumbnail_url'] ) ) {
$this->set_thumbnail_by_url( $meta_to_sync['thumbnail_url'], $post_id );
unset( $meta_to_sync['thumbnail_url'] );
}
foreach ( (array) $meta_to_sync as $key => $value ) {
if ( $value ) {
$updated[ $key ] = add_post_meta( $post_id, $key, $value );
}
}
// return $this->error( compact( 'post_id', 'updated', 'post' ) );
}
/**
*
* When the thumbnail is set and nothing else is done in the admin, no 'save_post' action is fired.
* We need to watch at a lower level (the actual thumbnail meta value) to ensure proper sync to tags site.
*
* @param integer $meta_id Unused; first param for the filter
* @param integer $post_id The post possibly getting a new thumbnail
* @param string $meta_key The meta key. We have to to check all meta values because there's no filter specific to thumbnails
* @param mixed integer|string $thumbnail_id The meta value. If the key is the one we're looking for, this will be the ID to an image attachment.
*/
public function update_thumbnail_meta( $meta_id, $post_id, $meta_key, $thumbnail_id ) {
// Many, many reasons to bail out. We want to prevent needless calls to switch_to_blog. Here we go:
// Not updating a thumbnail
if ( '_thumbnail_id' != $meta_key ) {
return;
}
// Thumbnail is empty: probably means we're deleting, which we'll cover with the delete_meta hook
if ( empty( $thumbnail_id ) ) {
return;
}
$post = get_post( $post_id );
// Only published posts are synced
if ( 'publish' != $post->post_status ) {
return;
}
// Not syncing thumbnails (network config)
if ( ! $this->options->get( 'tags_blog_thumbs' ) ) {
return;
}
// Not an allowed post type
$allowed_post_types = apply_filters( 'sitewide_tags_allowed_post_types', [ 'post' => true ] );
if ( ! isset( $allowed_post_types[ $post->post_type ] ) || ! $allowed_post_types[ $post->post_type ] ) {
return;
}
// We're in the tags/aggregating blog/site
$tags_blog_id = $this->options->get( 'tags_blog_id' );
if ( ! $tags_blog_id || $tags_blog_id == get_current_blog_id() ) {
return;
}
// We're in the clear, let's go!
$post_blog_id = get_current_blog_id();
$thumbnail_url = wp_get_attachment_url( $thumbnail_id );
switch_to_blog( $tags_blog_id );
$global_post_id = $this->get_global_post_id( $post_blog_id, $post_id );
if ( null !== $global_post_id ) {
$this->set_thumbnail_by_url( $thumbnail_url, $global_post_id );
}
restore_current_blog();
}
/**
*
* Takes an image's URL, imports image in WP and assigns it as a post thumbnail
*
* @param string $thumbnail_url Image URL
* @param integer $post_id ID of the post for which the imported image will become the thumbnail
*/
private function set_thumbnail_by_url( $thumbnail_url, $post_id ) {
// Already imported? Just grab the ID
$attachment_id = $this->get_image_id_by_orig_url( $thumbnail_url );
// Not imported yet, import and associate with current post
if ( ! $attachment_id ) {
$attachment_id = $this->import_image( $thumbnail_url, $post_id );
}
if ( ! $attachment_id ) {
error_log( "Failed to add featured image to post $post_id" );
} else {
set_post_thumbnail( $post_id, $attachment_id );
}
}
/**
*
* Takes an image's URL, adds the image to the Media Library and associates it with a post,
* as if it was uploaded to said post.
*
* @param string $external_image_url Image URL
* @param integer $post_id ID of post to attach image to
*
* @return bool|int Attachement ID or false when something failed
*/
private function import_image( $external_image_url, $post_id ) {
// Get the image from the original site and download to new.
$image_url = media_sideload_image( $external_image_url, $post_id, null, 'src' );
if ( is_wp_error( $image_url ) ) {
return false;
}
// Get the ID of the attachment.
$image_id = $this->get_image_id( $image_url );
// Generate thumbnails, because WP usually do this for us.
wp_generate_attachment_metadata( $image_id, get_attached_file( $image_id ) );
// Save original URL to meta field for later lookups, used to prevent importing same image multiple times
update_post_meta( $image_id, $this::$orig_img_url_key, $external_image_url );
// Add the featured image to the target post.
return $image_id;
}
/**
* Find the ID of a media item, given it's URL.
*
* @param string $image_url URL to the media item.
*
* @return int Media item's ID
*/
protected function get_image_id( $image_url ) {
global $wpdb;
// Query the DB to get the attachment ID.
// @codingStandardsIgnoreStart
$attachment = $wpdb->get_col(
$wpdb->prepare(
'SELECT ID FROM ' . $wpdb->prefix . 'posts' . " WHERE guid='%s';",
$image_url
)
);
// @codingStandardsIgnoreEnd
// ID should be the first element of the returned array.
if ( is_array( $attachment ) && isset( $attachment[0] ) ) {
return $attachment[0];
}
return false;
}
protected function get_image_id_by_orig_url( $orig_image_url ) {
$candidates = get_posts( [
'post_type' => 'attachment',
'post_status' => 'any',
'meta_query' => [
[
'key' => $this::$orig_img_url_key,
'value' => $orig_image_url,
],
],
] );
return empty( $candidates ) ? false : $candidates[0]->ID;
}
function do_comment_sync( $post_id ) {
global $wpdb;
$tags_blog_id = $this->options->get( 'tags_blog_id' );
if ( ! $tags_blog_id || $tags_blog_id == $wpdb->blogid ) {
return;
}
$post_blog_id = $wpdb->blogid;
$new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id ) );
switch_to_blog( $tags_blog_id );
$guid = "{$post_blog_id}.{$post_id}";
$global_post_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid IN (%s,%s)", $guid, esc_url( $guid ) ) );
if ( null !== $global_post_id ) {
$wpdb->update( $wpdb->posts, [ 'comment_count' => $new ], [ 'ID' => $global_post_id ] );
clean_post_cache( $global_post_id );
}
restore_current_blog();
}
function sync_post_delete( $post_id ) {
/*
* what should we do if a post will be deleted and the tags blog feature is disabled?
* need an check if we have a post on the tags blog and if so - delete this
*/
$tags_blog_id = $this->options->get( 'tags_blog_id' );
if ( ! $tags_blog_id || $tags_blog_id == get_current_blog_id() ) {
return;
}
$post_blog_id = get_current_blog_id();
switch_to_blog( $tags_blog_id );
$global_post_id = $this->get_global_post_id( $post_blog_id, $post_id );
if ( null !== $global_post_id ) {
wp_delete_post( $global_post_id );
}
restore_current_blog();
}
/**
*
* Deletes the thumbnail from the tags site when it is deleted from a synced post (which is not deleted itself)
*
* @param array $meta_ids Unused, first parameter of the filter
* @param integer $post_id Post losing its thumbnail
* @param string $meta_key Meta key label. Since there is no filter specific for thumbnails,
* we have to hook into the generic 'meta' filter and inspect the key
*/
function delete_thumbnail_meta( $meta_ids, $post_id, $meta_key ) {
if ( '_thumbnail_id' != $meta_key ) {
return;
}
$tags_blog_id = $this->options->get( 'tags_blog_id' );
if ( ! $tags_blog_id || $tags_blog_id == get_current_blog_id() ) {
return;
}
$post_blog_id = get_current_blog_id();
switch_to_blog( $tags_blog_id );
$global_post_id = $this->get_global_post_id( $post_blog_id, $post_id );
if ( null !== $global_post_id ) {
delete_post_thumbnail( $global_post_id );
}
restore_current_blog();
}
protected function get_blogs_to_import() {
if ( $this->options->get( 'populate_all_blogs' ) ) {
global $wpdb;
return $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs ORDER BY blog_id DESC" );
}
// 'all blogs' not checked? check the blogs_to_import option
return $this->options->get( 'blogs_to_import', [] );
}
/**
*
* Pass it the ID of a blog (subsite) and the ID of a post (on said blog/subsite)
* and you'll get the ID of the corresponding post on the aggregating blog
* Does not take care of switch_to_blog() for you.
* Beware! It makes no sense to use this outside of the aggregating blog's context
*
* @param $blog_id
* @param $post_id
*
* @return null|string
*/
private function get_global_post_id( $blog_id, $post_id ) {
global $wpdb;
$guid = "{$blog_id}.{$post_id}";
return $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid IN (%s,%s)", $guid, esc_url( $guid ) ) );
}
public function save_user_notice() {
if ( $this->total_imported ) {
$class = 'updated';
$count = $this->strong_red( (int) $this->total_imported );
$message = $this->heading( sprintf( __( 'Finished importing and/or updating %s posts! %s', 'wds-multisite-aggregate' ), $count,
' ' . $this->anchor( $this->get_aggregate_site_url(), __( 'Check them out?', 'wds-multisite-aggregate' ) ) ), 3 );
} else {
$class = 'error';
$message = $this->heading( __( 'There are no posts to be aggregated.', 'wds-multisite-aggregate' ), 3 );
}
add_site_option( 'wds_multisite_aggregate_message', compact( 'class', 'message' ) );
}
public function print_user_notice() {
if ( $msg = get_site_option( 'wds_multisite_aggregate_message' ) ) {
printf( '<div id="message" class="%s">%s</div>', $msg['class'], $msg['message'] );
delete_site_option( 'wds_multisite_aggregate_message' );
}
}
protected function js_redirect( $url, $time_in_seconds = .5 ) {
return sprintf( '
<script type="text/javascript">
window.setTimeout( function() {
window.location.href = "%s";
}, %d );
</script>
', $url, $time_in_seconds * 1000 );
}
protected function notice_description( $text, $large = true ) {
$style = $large ? 'style="font-size: 120%;"' : '';
return '<p class="description" ' . $style . '>' . $text . '</p>';
}
protected function strong_red( $text, $red = true ) {
$style = $red ? ' style="color:red;"' : '';
return sprintf( '<strong%s>%s</strong>', $style, $text );
}
protected function anchor( $url, $text ) {
return sprintf( '<a href="%s">%s</a>', esc_url( $url ), $text );
}
protected function heading( $text, $level = 1 ) {
return sprintf( '<h%2$d>%1$s</h%2$d>', $text, absint( $level ) );
}
protected function get_aggregate_site_url() {
return get_site_url( $this->options->get( 'tags_blog_id' ) );
}
protected function error( $data ) {
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return [ 'success' => false, 'data' => $data ];
}
wp_send_json_error( $data );
}
protected function success( $data ) {
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return [ 'success' => true, 'data' => $data ];
}
wp_send_json_success( $data );
}
protected function error_if_wpcli( $data ) {
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return [ 'success' => false, 'data' => $data ];
}
}
/**
* Magic getter for our object.
*
* @param string $field
*
* @return mixed
* @throws Exception Throws an exception if the field is invalid.
*
*/
public function __get( $field ) {
switch ( $field ) {
case 'options':
case 'admin':
case 'remove':
case 'frontend':
case 'debug':
return $this->{$field};
default:
return new WP_Error( 'wds_multisite_aggregate', __( 'Inaccessible Parameter', 'wds-multisite-aggregate' ) );
}
}
}
$WDS_Multisite_Aggregate = new WDS_Multisite_Aggregate();
$WDS_Multisite_Aggregate->hooks();
if ( defined( 'WP_CLI' ) && WP_CLI ) {
include_once( dirname( __FILE__ ) . '/includes/WDS_Multisite_Aggregate_CLI.php' );
}