-
Notifications
You must be signed in to change notification settings - Fork 156
/
WordPressExternalConnection.php
1109 lines (918 loc) · 33.3 KB
/
WordPressExternalConnection.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
/**
* WP external connection functionality
*
* @package distributor
*/
namespace Distributor\ExternalConnections;
use \Distributor\ExternalConnection as ExternalConnection;
use \Distributor\Utils;
/**
* Class handling WP external connections
*/
class WordPressExternalConnection extends ExternalConnection {
/**
* Connection slug
*
* @var string
*/
public static $slug = 'wp';
/**
* Connection pretty label
*
* This is to represent the authentication method,
* not the connection type. This value was previously
* "WordPress REST API".
*
* @since 1.4.0 Label as authentication method, not connection type
*
* @var string
*/
public static $label = 'Username / Password';
/**
* Auth handler to use
*
* @var string
*/
public static $auth_handler_class = '\Distributor\Authentications\WordPressBasicAuth';
/**
* REST API namespace
*
* @var string
*/
public static $namespace = 'wp/v2';
/**
* Remote request timeout
*
* @var integer
*/
public static $timeout = 5;
/**
* Default post type to pull.
*
* @var string
*/
public $pull_post_type;
/**
* Default post types supported.
*
* @var string
*/
public $pull_post_types;
/**
* This is a utility function for parsing annoying API link headers returned by the types endpoint
*
* @param array $type Types array.
* @since 0.8
* @return string|bool
*/
private function parse_type_items_link( $type ) {
try {
if ( isset( $type['_links']['wp:items'][0]['href'] ) ) {
$link = $type['_links']['wp:items'][0]['href'];
return $link;
}
} catch ( \Exception $e ) {
// Bummer
}
try {
if ( isset( $type['_links']['https://api.w.org/items'][0]['href'] ) ) {
$link = $type['_links']['https://api.w.org/items'][0]['href'];
return $link;
}
} catch ( \Exception $e ) {
// Even bigger bummer
}
return false;
}
/**
* Remotely get posts
*
* @param array $args Remote get args.
* @since 0.8
* @return array|\WP_Post|\WP_Error
*/
public function remote_get( $args = array() ) {
$id = ( empty( $args['id'] ) ) ? false : $args['id'];
$query_args = array();
$post_type = ( empty( $args['post_type'] ) ) ? 'post' : $args['post_type'];
if ( empty( $id ) ) {
$query_args['post_status'] = ( empty( $args['post_status'] ) ) ? 'any' : $args['post_status'];
$posts_per_page = ( empty( $args['posts_per_page'] ) ) ? get_option( 'posts_per_page' ) : $args['posts_per_page'];
$query_args['page'] = ( empty( $args['paged'] ) ) ? 1 : $args['paged'];
if ( isset( $args['post__in'] ) ) {
if ( empty( $args['post__in'] ) ) {
// If post__in is empty, we can just stop right here
/**
* Filter the remote_get request
*
* @since 1.0
*
* @param array $args {
* @type array Items to get.
* @type int Total number of items to get.
* }
* @param array $args The arguments originally passed to .remote_get'.
* @param object $this The authentication class.
*/
return apply_filters(
'dt_remote_get',
[
'items' => array(),
'total_items' => 0,
],
$args,
$this
);
}
$query_args['include'] = $args['post__in'];
} elseif ( isset( $args['post__not_in'] ) ) {
$query_args['exclude'] = $args['post__not_in'];
}
if ( ! empty( $args['s'] ) ) {
$query_args['search'] = $args['s'];
}
if ( ! empty( $args['orderby'] ) ) {
if ( 'post__in' === $args['orderby']) {
$query_args['orderby'] = 'include';
} else {
$query_args['orderby'] = strtolower( $args['orderby'] );
}
}
if ( ! empty( $args['order'] ) ) {
$query_args['order'] = strtolower( $args['order'] );
}
}
static $types_urls;
$types_urls = array();
if ( empty( $types_urls[ $post_type ] ) ) {
/**
* First let's get the actual route if not cached. We don't know the "plural" of our post type
*/
/**
* Todo: This should be cached in a transient
*/
$path = self::$namespace;
$types_path = untrailingslashit( $this->base_url ) . '/' . $path . '/types';
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$types_response = vip_safe_wp_remote_get(
$types_path,
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$types_response = wp_remote_get(
$types_path,
$this->auth_handler->format_get_args( array( 'timeout' => self::$timeout ) )
);
}
if ( is_wp_error( $types_response ) ) {
return $types_response;
}
if ( 404 === wp_remote_retrieve_response_code( $types_response ) ) {
return new \WP_Error( 'bad-endpoint', esc_html__( 'Could not connect to API endpoint.', 'distributor' ) );
}
$types_body = wp_remote_retrieve_body( $types_response );
if ( empty( $types_body ) ) {
return new \WP_Error( 'no-response-body', esc_html__( 'Response body is empty', 'distributor' ) );
}
$types_body_array = json_decode( $types_body, true );
if ( empty( $types_body_array ) || empty( $types_body_array[ $post_type ] ) ) {
return new \WP_Error( 'no-pull-post-type', esc_html__( 'Could not determine remote post type endpoint', 'distributor' ) );
}
$types_urls[ $post_type ] = $this->parse_type_items_link( $types_body_array[ $post_type ] );
if ( empty( $types_urls[ $post_type ] ) ) {
return new \WP_Error( 'no-pull-post-type', esc_html__( 'Could not determine remote post type endpoint', 'distributor' ) );
}
}
$args_str = '';
if ( ! empty( $posts_per_page ) ) {
$args_str .= 'per_page=' . (int) $posts_per_page;
}
/**
* Filter the remote_get query arguments
*
* @since 1.0
*
* @param array $query_args The existing query arguments.
* @param array $args The arguments originally passed to .remote_get'.
* @param object $this The authentication class.
*/
$query_args = apply_filters( 'dt_remote_get_query_args', $query_args, $args, $this );
foreach ( $query_args as $arg_key => $arg_value ) {
if ( is_array( $arg_value ) ) {
foreach ( $arg_value as $arg_value_value ) {
if ( ! empty( $args_str ) ) {
$args_str .= '&';
}
$args_str .= $arg_key . '[]=' . $arg_value_value;
}
} else {
if ( ! empty( $args_str ) ) {
$args_str .= '&';
}
$args_str .= $arg_key . '=' . $arg_value;
}
}
$context = 'view';
$prelim_get_args = $this->auth_handler->format_get_args();
/**
* See if we are trying to authenticate
*/
if ( ! empty( $prelim_get_args ) && ! empty( $prelim_get_args['headers'] ) && ! empty( $prelim_get_args['headers']['Authorization'] ) ) {
$context = 'edit';
if ( ! empty( $args_str ) ) {
$args_str .= '&';
}
$args_str .= 'context=edit';
}
if ( ! empty( $id ) ) {
$posts_url = untrailingslashit( $types_urls[ $post_type ] ) . '/' . $id . '/?context=' . $context;
} else {
$posts_url = untrailingslashit( $types_urls[ $post_type ] ) . '/?' . $args_str;
}
// Add request parameter to specify Distributor request
$posts_url = add_query_arg( 'distributor_request', '1', $posts_url );
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$posts_response = vip_safe_wp_remote_get(
/**
* Filter the URL that remote_get will use
*
* @since 1.0
*
* @param string $posts_url The posts URL
* @param string $args The arguments originally passed to .remote_get'.
* @param object $this The authentication class.
*/
apply_filters( 'dt_remote_get_url', $posts_url, $args, $this ),
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$posts_response = wp_remote_get( apply_filters( 'dt_remote_get_url', $posts_url, $args, $this ), $this->auth_handler->format_get_args( array( 'timeout' => 45 ) ) );
}
if ( is_wp_error( $posts_response ) ) {
return $posts_response;
}
$response_code = wp_remote_retrieve_response_code( $posts_response );
if ( 200 !== $response_code ) {
if ( 404 === $response_code ) {
return new \WP_Error( 'bad-endpoint', esc_html__( 'Could not connect to API endpoint.', 'distributor' ) );
}
$posts_body = json_decode( wp_remote_retrieve_body( $posts_response ), true );
$code = empty( $posts_body['code'] ) ? 'endpoint-error' : esc_html( $posts_body['code'] );
$message = empty( $posts_body['message'] ) ? esc_html__( 'API endpoint error.', 'distributor' ) : esc_html( $posts_body['message'] );
return new \WP_Error( $code, $message );
}
$posts_body = wp_remote_retrieve_body( $posts_response );
if ( empty( $posts_body ) ) {
return new \WP_Error( 'no-response-body', esc_html__( 'Response body is empty', 'distributor' ) );
}
$posts = json_decode( $posts_body, true );
$formatted_posts = array();
$response_headers = wp_remote_retrieve_headers( $posts_response );
if ( empty( $id ) ) {
foreach ( $posts as $post ) {
$post['full_connection'] = ( ! empty( $response_headers['X-Distributor'] ) );
$formatted_posts[] = $this->to_wp_post( $post );
}
$total_posts = wp_remote_retrieve_header( $posts_response, 'X-WP-Total' );
if ( empty( $total_posts ) ) {
$total_posts = count( $formatted_posts );
}
return apply_filters(
'dt_remote_get',
[
'items' => $formatted_posts,
'total_items' => $total_posts,
],
$args,
$this
);
} else {
return apply_filters( 'dt_remote_get', $this->to_wp_post( $posts ), $args, $this );
}
}
/**
* Pull items. Pass array of posts, each post should look like:
* [ 'remote_post_id' => POST ID TO GET, 'post_id' (optional) => POST ID TO MAP TO ]
*
* @param array $items Posts to pull.
* @since 0.8
* @return array
*/
public function pull( $items ) {
$created_posts = array();
foreach ( $items as $item_array ) {
$post = $this->remote_get(
[
'id' => $item_array['remote_post_id'],
'post_type' => $item_array['post_type'],
]
);
if ( is_wp_error( $post ) ) {
$created_posts[] = $post;
continue;
}
$post_props = get_object_vars( $post );
$post_array = array();
foreach ( $post_props as $key => $value ) {
$post_array[ $key ] = $value;
}
if ( ! empty( $item_array['post_id'] ) ) {
$post_array['ID'] = $item_array['post_id'];
} else {
unset( $post_array['ID'] );
}
if ( isset( $post_array['post_parent'] ) ) {
unset( $post_array['post_parent'] );
}
// Remove date stuff
unset( $post_array['post_date'] );
unset( $post_array['post_date_gmt'] );
unset( $post_array['post_modified'] );
unset( $post_array['post_modified_gmt'] );
/**
* Filter the arguments passed into wp_insert_post during a pull.
*
* @since 1.0
*
* @param array $post_array The post to be inserted.
* @param array $item_array['remote_post_id'] The remote post ID.
* @param object $post The request that got the post.
* @param ExternalConnection $this The distributor connection pulling the post.
*/
$new_post = wp_insert_post( apply_filters( 'dt_pull_post_args', $post_array, $item_array['remote_post_id'], $post, $this ) );
update_post_meta( $new_post, 'dt_original_post_id', (int) $item_array['remote_post_id'] );
update_post_meta( $new_post, 'dt_original_source_id', (int) $this->id );
update_post_meta( $new_post, 'dt_syndicate_time', time() );
update_post_meta( $new_post, 'dt_original_post_url', esc_url_raw( $post_array['link'] ) );
update_post_meta( $new_post, 'dt_original_site_name', sanitize_text_field( $post_array['original_site_name'] ) );
update_post_meta( $new_post, 'dt_original_site_url', sanitize_text_field( $post_array['original_site_url'] ) );
if ( ! empty( $post->post_parent ) ) {
update_post_meta( $new_post, 'dt_original_post_parent', (int) $post->post_parent );
}
if ( empty( $post_array['full_connection'] ) ) {
update_post_meta( $new_post, 'dt_full_connection', false );
} else {
update_post_meta( $new_post, 'dt_full_connection', true );
}
if ( ! empty( $post_array['meta'] ) ) {
\Distributor\Utils\set_meta( $new_post, $post_array['meta'] );
}
if ( ! empty( $post_array['terms'] ) ) {
\Distributor\Utils\set_taxonomy_terms( $new_post, $post_array['terms'] );
}
if ( ! empty( $post_array['media'] ) ) {
/**
* Allow bypassing of all media processing.
*
* @param bool true If Distributor should set the post media.
* @param int $new_post The newly created post ID.
* @param array $post_array['media'] List of media items attached to the post, formatted by {@see \Distributor\Utils\prepare_media()}.
* @param int $item_array['remote_post_id'] The original post ID.
* @param array $post_array The arguments passed into wp_insert_post.
* @param ExternalConnection $this The distributor connection being pulled from.
*/
if ( apply_filters( 'dt_pull_post_media', true, $new_post, $post_array['media'], $item_array['remote_post_id'], $post_array, $this ) ) {
\Distributor\Utils\set_media( $new_post, $post_array['media'] );
}
}
/**
* Action triggered when a post is pulled via distributor.
*
* @param int $new_post The newly created post ID.
* @param ExternalConnection $this The distributor connection pulling the post.
* @param array $post_array The original post data retrieved via the connection.
*/
do_action( 'dt_pull_post', $new_post, $this, $post_array );
$created_posts[] = $new_post;
}
return $created_posts;
}
/**
* Push a post to an external connection
*
* @param int $post_id Post id
* @param array $args Post args to push.
* @since 0.8
* @return bool|\WP_Error
*/
public function push( $post_id, $args = array() ) {
if ( empty( $post_id ) ) {
return new \WP_Error( 'no-push-post-id', esc_html__( 'Post id required to push', 'distributor' ) );
}
$post = get_post( $post_id );
$post_type = get_post_type( $post_id );
$path = self::$namespace;
/**
* First let's get the actual route. We don't know the "plural" of our post type
*/
$types_path = untrailingslashit( $this->base_url ) . '/' . $path . '/types';
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$response = vip_safe_wp_remote_get(
$types_path,
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$response = wp_remote_get(
$types_path,
$this->auth_handler->format_get_args(
array(
'timeout' => self::$timeout,
)
)
);
}
if ( is_wp_error( $response ) ) {
return $response;
}
$body = wp_remote_retrieve_body( $response );
if ( empty( $body ) ) {
return new \WP_Error( 'no-response-body', esc_html__( 'Response body is empty', 'distributor' ) );
}
$body_array = json_decode( $body, true );
$type_url = $this->parse_type_items_link( $body_array[ $post_type ] );
if ( empty( $type_url ) ) {
return new \WP_Error( 'no-push-post-type', esc_html__( 'Could not determine remote post type endpoint', 'distributor' ) );
}
$signature = \Distributor\Subscriptions\generate_signature();
/**
* Now let's push
*/
$post_body = [
'title' => get_the_title( $post_id ),
'slug' => $post->post_name,
'content' => Utils\get_processed_content( $post->post_content ),
'type' => $post->post_type,
'status' => ( ! empty( $args['post_status'] ) ) ? $args['post_status'] : 'publish',
'excerpt' => $post->post_excerpt,
'distributor_original_source_id' => $this->id,
'distributor_original_site_name' => get_bloginfo( 'name' ),
'distributor_original_site_url' => home_url(),
'distributor_original_post_url' => get_permalink( $post_id ),
'distributor_remote_post_id' => $post_id,
'distributor_signature' => $signature,
'distributor_media' => \Distributor\Utils\prepare_media( $post_id ),
'distributor_terms' => \Distributor\Utils\prepare_taxonomy_terms( $post_id ),
'distributor_meta' => \Distributor\Utils\prepare_meta( $post_id ),
];
// Gutenberg posts also distribute raw content.
if ( \Distributor\Utils\is_using_gutenberg( $post ) ) {
if ( \Distributor\Utils\dt_use_block_editor_for_post_type( $post->post_type ) ) {
$post_body['distributor_raw_content'] = $post->post_content;
}
}
if ( ! empty( $post->post_parent ) ) {
$post_body['distributor_original_post_parent'] = (int) $post->post_parent;
}
// Map to remote ID if a push has already happened
if ( ! empty( $args['remote_post_id'] ) ) {
$existing_post_url = untrailingslashit( $type_url ) . '/' . $args['remote_post_id'];
// Check to make sure remote post still exists
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$post_exists_response = vip_safe_wp_remote_get(
$existing_post_url,
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$post_exists_response = wp_remote_get( $existing_post_url, $this->auth_handler->format_get_args( array( 'timeout' => self::$timeout ) ) );
}
if ( ! is_wp_error( $post_exists_response ) ) {
$post_exists_response_code = wp_remote_retrieve_response_code( $post_exists_response );
if ( 200 === (int) $post_exists_response_code ) {
$type_url = $existing_post_url;
}
}
}
$response = wp_remote_post(
$type_url,
$this->auth_handler->format_post_args(
array(
/**
* Filter the timeout used when calling WordPressExternalConnection::push.
*
* @since 1.0
*
* @param int $timeout The timeout to use for the remote post. Default 5.
* @param object $post The post object
*/
'timeout' => apply_filters( 'dt_push_post_timeout', 45, $post ),
/**
* Filter the arguments sent to the remote server during a push.
*
* @since 1.0
*
* @param array $post_body The request body to send.
* @param object $post The WP_Post that is being pushed.
* @param array $args Post args to push.
* @param ExternalConnection $this The distributor connection being pushed to.
*/
'body' => apply_filters( 'dt_push_post_args', $post_body, $post, $args, $this ),
)
)
);
/**
* Action triggered when a post is pushed via distributor.
*
* @param array $response The HTTP response of the push.
* @param array $post_body The body that was POSTed.
* @param string $type_url The URL that was POSTed to.
* @param int $post_id The post ID that was pushed.
* @param array $args The arguments sent with the POST.
* @param ExternalConnection $this The distributor connection being pushed to.
*/
do_action( 'dt_push_post', $response, $post_body, $type_url, $post_id, $args, $this );
if ( is_wp_error( $response ) ) {
return $response;
}
$body = wp_remote_retrieve_body( $response );
if ( empty( $body ) ) {
return new \WP_Error( 'no-response-body', esc_html__( 'Response body is empty', 'distributor' ) );
}
$body_array = json_decode( $body, true );
try {
$remote_id = $body_array['id'];
} catch ( \Exception $e ) {
return new \WP_Error( 'no-push-post-remote-id', esc_html__( 'Could not determine remote post id.', 'distributor' ) );
}
$response_headers = wp_remote_retrieve_headers( $response );
if ( ! empty( $response_headers['X-Distributor'] ) ) {
// We have Distributor on the other side
\Distributor\Subscriptions\create_subscription( $post_id, $remote_id, untrailingslashit( $this->base_url ), $signature );
}
return $remote_id;
}
/**
* Get the available post types.
*
* @since 1.3
* @return array|\WP_Error
*/
public function get_post_types() {
$path = self::$namespace;
$types_path = untrailingslashit( $this->base_url ) . '/' . $path . '/types';
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$types_response = vip_safe_wp_remote_get(
$types_path,
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$types_response = wp_remote_get(
$types_path,
$this->auth_handler->format_get_args( array( 'timeout' => self::$timeout ) )
);
}
if ( is_wp_error( $types_response ) ) {
return $types_response;
}
if ( 404 === wp_remote_retrieve_response_code( $types_response ) ) {
return new \WP_Error( 'bad-endpoint', esc_html__( 'Could not connect to API endpoint.', 'distributor' ) );
}
$types_body = wp_remote_retrieve_body( $types_response );
if ( empty( $types_body ) ) {
return new \WP_Error( 'no-response-body', esc_html__( 'Response body is empty', 'distributor' ) );
}
$types_body_array = json_decode( $types_body, true );
return $types_body_array;
}
/**
* Check what we can do with a given external connection (push or pull)
*
* @since 0.8
* @return array
*/
public function check_connections() {
$output = array(
'errors' => array(),
'can_post' => array(),
'can_get' => array(),
'endpoint_suggestion' => false,
);
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$response = vip_safe_wp_remote_get(
untrailingslashit( $this->base_url ),
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$response = wp_remote_get( untrailingslashit( $this->base_url ), $this->auth_handler->format_get_args( array( 'timeout' => self::$timeout ) ) );
}
$body = wp_remote_retrieve_body( $response );
if ( is_wp_error( $response ) || empty( $body ) ) {
$output['errors']['no_external_connection'] = 'no_external_connection';
return $output;
}
$data = json_decode( $body, true );
if ( empty( $data ) ) {
$output['errors']['no_external_connection'] = 'no_external_connection';
}
$response_headers = wp_remote_retrieve_headers( $response );
$link_headers = (array) $response_headers['Link'];
$correct_endpoint = false;
foreach ( $link_headers as $link_header ) {
if ( strpos( $link_header, 'rel="https://api.w.org/"' ) !== false ) {
$correct_endpoint = preg_replace( '#.*<([^>]+)>.*#', '$1', $link_header );
}
}
if ( ! empty( $correct_endpoint ) && untrailingslashit( $this->base_url ) !== untrailingslashit( $correct_endpoint ) ) {
$output['errors']['no_external_connection'] = 'no_external_connection';
$output['endpoint_suggestion'] = untrailingslashit( $correct_endpoint );
}
if ( empty( $data['routes'] ) && empty( $output['errors']['no_external_connection'] ) ) {
$output['errors']['no_types'] = 'no_types';
}
if ( ! empty( $output['errors'] ) ) {
return $output;
}
if ( empty( $response_headers['X-Distributor'] ) ) {
$output['errors']['no_distributor'] = 'no_distributor';
}
$routes = $data['routes'];
$types_path = untrailingslashit( $this->base_url ) . '/' . self::$namespace . '/types';
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$types_response = vip_safe_wp_remote_get(
$types_path,
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$types_response = wp_remote_get( $types_path, $this->auth_handler->format_get_args( array( 'timeout' => self::$timeout ) ) );
}
$types_body = wp_remote_retrieve_body( $types_response );
if ( is_wp_error( $types_response ) || empty( $types_body ) ) {
$output['errors']['no_types'] = 'no_types';
} else {
$types = json_decode( $types_body, true );
if ( 200 !== wp_remote_retrieve_response_code( $types_response ) || empty( $types ) ) {
$output['errors']['no_types'] = 'no_types';
} else {
$can_get = array();
$can_post = array();
$blacklisted_types = [ 'dt_subscription' ];
foreach ( $types as $type_key => $type ) {
if ( in_array( $type_key, $blacklisted_types, true ) ) {
continue;
}
$link = $this->parse_type_items_link( $type );
if ( empty( $link ) ) {
continue;
}
$route = str_replace( untrailingslashit( $this->base_url ), '', $link );
if ( ! empty( $routes[ $route ] ) ) {
if ( in_array( 'GET', $routes[ $route ]['methods'], true ) ) {
if ( function_exists( 'vip_safe_wp_remote_get' ) && \Distributor\Utils\is_vip_com() ) {
$type_response = vip_safe_wp_remote_get(
$link,
false,
3,
3,
10,
$this->auth_handler->format_get_args()
);
} else {
$type_response = wp_remote_get( $link, $this->auth_handler->format_get_args( array( 'timeout' => self::$timeout ) ) );
}
if ( ! is_wp_error( $type_response ) ) {
$code = (int) wp_remote_retrieve_response_code( $type_response );
if ( 401 !== $code ) {
$can_get[] = $type_key;
}
}
}
if ( in_array( 'POST', $routes[ $route ]['methods'], true ) ) {
$type_response = wp_remote_post(
$link,
$this->auth_handler->format_post_args(
array(
'timeout' => self::$timeout,
'body' => array( 'test' => 1 ),
)
)
);
if ( ! is_wp_error( $type_response ) ) {
$code = (int) wp_remote_retrieve_response_code( $type_response );
if ( 401 !== $code ) {
$can_post[] = $type_key;
}
}
}
}
}
$output['can_get'] = $can_get;
$output['can_post'] = $can_post;
}
}
return $output;
}
/**
* Convert array to WP_Post object suitable for insert/update.
*
* Some field names in the REST API response object do not match DB field names.
*
* @see \WP_REST_Posts_Controller::prepare_item_for_database()
* @param array $post Post as array.
* @since 0.8
* @return \WP_Post
*/
private function to_wp_post( $post ) {
$obj = new \stdClass();
$obj->ID = $post['id'];
$obj->post_title = $post['title']['rendered'];
if ( isset( $post['excerpt']['raw'] ) ) {
$obj->post_excerpt = $post['excerpt']['raw'];
} elseif ( isset( $post['excerpt']['rendered'] ) ) {
$obj->post_excerpt = $post['excerpt']['rendered'];
} else {
$obj->post_excerpt = '';
}
$obj->post_status = 'draft';
$obj->post_author = get_current_user_id();
$obj->post_password = $post['password'];
$obj->post_date = $post['date'];
$obj->post_date_gmt = $post['date_gmt'];
$obj->guid = $post['guid']['rendered'];
$obj->post_modified = $post['modified'];
$obj->post_modified_gmt = $post['modified_gmt'];
$obj->post_type = $post['type'];
$obj->link = $post['link'];
$obj->comment_status = $post['comment_status'];
$obj->ping_status = $post['ping_status'];
// Use raw content if both remote and local are using Gutenberg.
$obj->post_content = \Distributor\Utils\is_using_gutenberg( new \WP_Post( $obj ) ) && isset( $post['is_using_gutenberg'] ) ?
$post['content']['raw'] :
Utils\get_processed_content( $post['content']['raw'] );
/**
* These will only be set if Distributor is active on the other side
*/
$obj->meta = ( ! empty( $post['distributor_meta'] ) ) ? $post['distributor_meta'] : [];
$obj->terms = ( ! empty( $post['distributor_terms'] ) ) ? $post['distributor_terms'] : [];
$obj->media = ( ! empty( $post['distributor_media'] ) ) ? $post['distributor_media'] : [];
$obj->original_site_name = ( ! empty( $post['distributor_original_site_name'] ) ) ? $post['distributor_original_site_name'] : null;
$obj->original_site_url = ( ! empty( $post['distributor_original_site_url'] ) ) ? $post['distributor_original_site_url'] : null;
$obj->full_connection = ( ! empty( $post['full_connection'] ) );
/**
* Filter the post item.
*
* @since 1.0
*
* @param object $obj The WP_Post that is being pushed.
* @param ExternalConnection $this The external connection the post concerns.
*/
return apply_filters( 'dt_item_mapping', new \WP_Post( $obj ), $post, $this );
}
/**
* Setup actions and filters that are need on every page load
*
* @since 1.0
*/
public static function bootstrap() {
add_action( 'template_redirect', array( '\Distributor\ExternalConnections\WordPressExternalConnection', 'canonicalize_front_end' ) );
}
/**
* Setup canonicalization on front end
*
* @since 1.0
*/
public static function canonicalize_front_end() {
add_filter( 'get_canonical_url', array( '\Distributor\ExternalConnections\WordPressExternalConnection', 'canonical_url' ), 10, 2 );
add_filter( 'wpseo_canonical', array( '\Distributor\ExternalConnections\WordPressExternalConnection', 'wpseo_canonical_url' ) );
add_filter( 'wpseo_opengraph_url', array( '\Distributor\ExternalConnections\WordPressExternalConnection', 'wpseo_og_url' ) );
add_filter( 'the_author', array( '\Distributor\ExternalConnections\WordPressExternalConnection', 'the_author_distributed' ) );
add_filter( 'author_link', array( '\Distributor\ExternalConnections\WordPressExternalConnection', 'author_posts_url_distributed' ), 10, 3 );
}
/**
* Override author with site name on distributed post
*
* @param string $link Author link.
* @param int $author_id Author ID.
* @param string $author_nicename Author name.
* @since 1.0
* @return string
*/
public static function author_posts_url_distributed( $link, $author_id, $author_nicename ) {
global $post;
if ( empty( $post ) ) {
return $link;
}
$settings = Utils\get_settings();
if ( empty( $settings['override_author_byline'] ) ) {
return $link;
}
$original_source_id = get_post_meta( $post->ID, 'dt_original_source_id', true );
$original_site_url = get_post_meta( $post->ID, 'dt_original_site_url', true );
$unlinked = (bool) get_post_meta( $post->ID, 'dt_unlinked', true );
if ( empty( $original_source_id ) || empty( $original_site_url ) || $unlinked ) {
return $link;