forked from WP-API/WP-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-wp-json-posts.php
1115 lines (938 loc) · 35.4 KB
/
class-wp-json-posts.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
class WP_JSON_Posts {
/**
* Server object
*
* @var WP_JSON_ResponseHandler
*/
protected $server;
/**
* Constructor
*
* @param WP_JSON_ResponseHandler $server Server object
*/
public function __construct(WP_JSON_ResponseHandler $server) {
$this->server = $server;
}
/**
* Register the post-related routes
*
* @param array $routes Existing routes
* @return array Modified routes
*/
public function register_routes( $routes ) {
$post_routes = array(
// Post endpoints
'/posts' => array(
array( array( $this, 'get_posts' ), WP_JSON_Server::READABLE ),
array( array( $this, 'new_post' ), WP_JSON_Server::CREATABLE | WP_JSON_Server::ACCEPT_JSON ),
),
'/posts/(?P<id>\d+)' => array(
array( array( $this, 'get_post' ), WP_JSON_Server::READABLE ),
array( array( $this, 'edit_post' ), WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),
array( array( $this, 'delete_post' ), WP_JSON_Server::DELETABLE ),
),
'/posts/(?P<id>\d+)/revisions' => array( array( $this, 'get_revisions' ), WP_JSON_Server::READABLE ),
// Comments
'/posts/(?P<id>\d+)/comments' => array(
array( array( $this, 'get_comments' ), WP_JSON_Server::READABLE ),
array( '__return_null', WP_JSON_Server::CREATABLE | WP_JSON_Server::ACCEPT_JSON ),
),
'/posts/(?P<id>\d+)/comments/(?P<comment>\d+)' => array(
array( array( $this, 'get_comment' ), WP_JSON_Server::READABLE ),
array( '__return_null', WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),
array( array( $this, 'delete_comment' ), WP_JSON_Server::DELETABLE ),
),
// Meta-post endpoints
'/posts/types' => array( array( $this, 'get_post_types' ), WP_JSON_Server::READABLE ),
'/posts/types/(?P<type>\w+)' => array( array( $this, 'get_post_type' ), WP_JSON_Server::READABLE ),
'/posts/statuses' => array( array( $this, 'get_post_statuses' ), WP_JSON_Server::READABLE ),
);
return array_merge( $routes, $post_routes );
}
/**
* Get revisions for a specific post.
*
* @param int $id Post ID
* @uses wp_get_post_revisions
* @return WP_JSON_Response
*/
public function get_revisions( $id ) {
$id = (int) $id;
if ( empty( $id ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
// Todo: Query args filter for wp_get_post_revisions
$revisions = wp_get_post_revisions( $id );
foreach ( $revisions as $revision ) {
$post = get_object_vars( $revision );
$struct[] = $this->prepare_post( $post, 'view-revision' );
}
return $struct;
}
/**
* Retrieve posts.
*
* @since 3.4.0
*
* The optional $filter parameter modifies the query used to retrieve posts.
* Accepted keys are 'post_type', 'post_status', 'number', 'offset',
* 'orderby', and 'order'.
*
* The optional $fields parameter specifies what fields will be included
* in the response array.
*
* @uses wp_get_recent_posts()
* @see WP_JSON_Posts::get_post() for more on $fields
* @see get_posts() for more on $filter values
*
* @param array $filter Parameters to pass through to `WP_Query`
* @param string $context
* @param string|array $type Post type slug, or array of slugs
* @param int $page Page number (1-indexed)
* @return stdClass[] Collection of Post entities
*/
public function get_posts( $filter = array(), $context = 'view', $type = 'post', $page = 1 ) {
$query = array();
// Validate post types and permissions
$query['post_type'] = array();
foreach ( (array) $type as $type_name ) {
$post_type = get_post_type_object( $type_name );
if ( ! ( (bool) $post_type ) || ! $post_type->show_in_json )
return new WP_Error( 'json_invalid_post_type', sprintf( __( 'The post type "%s" is not valid' ), $type_name ), array( 'status' => 403 ) );
$query['post_type'][] = $post_type->name;
}
global $wp;
// Allow the same as normal WP
$valid_vars = apply_filters('query_vars', $wp->public_query_vars);
// If the user has the correct permissions, also allow use of internal
// query parameters, which are only undesirable on the frontend
//
// To disable anyway, use `add_filter('json_private_query_vars', '__return_empty_array');`
if ( current_user_can( $post_type->cap->edit_posts ) ) {
$private = apply_filters('json_private_query_vars', $wp->private_query_vars);
$valid_vars = array_merge($valid_vars, $private);
}
// Define our own in addition to WP's normal vars
$json_valid = array('posts_per_page');
$valid_vars = array_merge($valid_vars, $json_valid);
// Filter and flip for querying
$valid_vars = apply_filters('json_query_vars', $valid_vars);
$valid_vars = array_flip($valid_vars);
// Exclude the post_type query var to avoid dodging the permission
// check above
unset($valid_vars['post_type']);
foreach ($valid_vars as $var => $index) {
if ( isset( $filter[ $var ] ) ) {
$query[ $var ] = apply_filters( 'json_query_var-' . $var, $filter[ $var ] );
}
}
// Special parameter handling
$query['paged'] = absint( $page );
$post_query = new WP_Query();
$posts_list = $post_query->query( $query );
$response = new WP_JSON_Response();
$response->query_navigation_headers( $post_query );
if ( ! $posts_list ) {
$response->set_data( array() );
return $response;
}
// holds all the posts data
$struct = array();
$response->header( 'Last-Modified', mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), 0 ).' GMT' );
foreach ( $posts_list as $post ) {
$post = get_object_vars( $post );
// Do we have permission to read this post?
if ( ! $this->check_read_permission( $post ) )
continue;
$response->link_header( 'item', json_url( '/posts/' . $post['ID'] ), array( 'title' => $post['post_title'] ) );
$struct[] = $this->prepare_post( $post, $context );
}
$response->set_data( $struct );
return $response;
}
/**
* Check if we can read a post
*
* Correctly handles posts with the inherit status.
* @param array $post Post data
* @return boolean Can we read it?
*/
protected function check_read_permission( $post ) {
$post_type = get_post_type_object( $post['post_type'] );
// Ensure the post type can be read
if ( ! $post_type->show_in_json ) {
return false;
}
// Can we read the post?
if ( 'publish' === $post['post_status'] || current_user_can( $post_type->cap->read_post, $post['ID'] ) ) {
return true;
}
// Can we read the parent if we're inheriting?
if ( 'inherit' === $post['post_status'] && $post['post_parent'] > 0 ) {
$parent = get_post( $post['post_parent'], ARRAY_A );
if ( $this->check_read_permission( $parent ) ) {
return true;
}
}
// If we don't have a parent, but the status is set to inherit, assume
// it's published (as per get_post_status())
if ( 'inherit' === $post['post_status'] ) {
return true;
}
return false;
}
/**
* Create a new post for any registered post type.
*
* @since 3.4.0
* @internal 'data' is used here rather than 'content', as get_default_post_to_edit uses $_REQUEST['content']
*
* @param array $content Content data. Can contain:
* - post_type (default: 'post')
* - post_status (default: 'draft')
* - post_title
* - post_author
* - post_excerpt
* - post_content
* - post_date_gmt | post_date
* - post_format
* - post_password
* - comment_status - can be 'open' | 'closed'
* - ping_status - can be 'open' | 'closed'
* - sticky
* - post_thumbnail - ID of a media item to use as the post thumbnail/featured image
* - custom_fields - array, with each element containing 'key' and 'value'
* - terms - array, with taxonomy names as keys and arrays of term IDs as values
* - terms_names - array, with taxonomy names as keys and arrays of term names as values
* - enclosure
* - any other fields supported by wp_insert_post()
* @return array Post data (see {@see WP_JSON_Posts::get_post})
*/
function new_post( $data ) {
unset( $data['ID'] );
$result = $this->insert_post( $data );
if ( $result instanceof WP_Error ) {
return $result;
}
$response = json_ensure_response( $this->get_post( $result ) );
$response->set_status( 201 );
$response->header( 'Location', json_url( '/posts/' . $result ) );
return $response;
}
/**
* Retrieve a post.
*
* @uses get_post()
* @param int $id Post ID
* @param array $fields Post fields to return (optional)
* @return array Post entity
*/
public function get_post( $id, $context = 'view' ) {
$id = (int) $id;
if ( empty( $id ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
$post = get_post( $id, ARRAY_A );
if ( empty( $post['ID'] ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
if ( ! $this->check_read_permission( $post ) )
return new WP_Error( 'json_user_cannot_read', __( 'Sorry, you cannot read this post.' ), array( 'status' => 401 ) );
// Link headers (see RFC 5988)
$response = new WP_JSON_Response();
$response->header( 'Last-Modified', mysql2date( 'D, d M Y H:i:s', $post['post_modified_gmt'] ) . 'GMT' );
$post = $this->prepare_post( $post, $context );
if ( is_wp_error( $post ) )
return $post;
foreach ( $post['meta']['links'] as $rel => $url ) {
$response->link_header( $rel, $url );
}
$response->link_header( 'alternate', get_permalink( $id ), array( 'type' => 'text/html' ) );
$response->set_data( $post );
return $response;
}
/**
* Edit a post for any registered post type.
*
* The $data parameter only needs to contain fields that should be changed.
* All other fields will retain their existing values.
*
* @since 3.4.0
* @internal 'data' is used here rather than 'content', as get_default_post_to_edit uses $_REQUEST['content']
*
* @param int $id Post ID to edit
* @param array $data Data construct, see {@see WP_JSON_Posts::new_post}
* @param array $_headers Header data
* @return true on success
*/
function edit_post( $id, $data, $_headers = array() ) {
$id = (int) $id;
if ( empty( $id ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
$post = get_post( $id, ARRAY_A );
if ( empty( $post['ID'] ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
if ( isset( $_headers['IF_UNMODIFIED_SINCE'] ) ) {
// As mandated by RFC2616, we have to check all of RFC1123, RFC1036
// and C's asctime() format (and ignore invalid headers)
$formats = array( DateTime::RFC1123, DateTime::RFC1036, 'D M j H:i:s Y' );
foreach ( $formats as $format ) {
$check = WP_JSON_DateTime::createFromFormat( $format, $_headers['IF_UNMODIFIED_SINCE'] );
if ( $check !== false )
break;
}
// If the post has been modified since the date provided, return an error.
if ( $check && mysql2date( 'U', $post['post_modified_gmt'] ) > $check->format('U') ) {
return new WP_Error( 'json_old_revision', __( 'There is a revision of this post that is more recent.' ), array( 'status' => 412 ) );
}
}
$data['ID'] = $id;
$retval = $this->insert_post( $data );
if ( is_wp_error( $retval ) ) {
return $retval;
}
return $this->get_post( $id );
}
/**
* Delete a post for any registered post type
*
* @uses wp_delete_post()
* @param int $id
* @return true on success
*/
public function delete_post( $id, $force = false ) {
$id = (int) $id;
if ( empty( $id ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
$post = get_post( $id, ARRAY_A );
if ( empty( $post['ID'] ) )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
$post_type = get_post_type_object( $post['post_type'] );
if ( ! current_user_can( $post_type->cap->delete_post, $id ) )
return new WP_Error( 'json_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => 401 ) );
$result = wp_delete_post( $id, $force );
if ( ! $result )
return new WP_Error( 'json_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
if ( $force ) {
return array( 'message' => __( 'Permanently deleted post' ) );
}
else {
// TODO: return a HTTP 202 here instead
return array( 'message' => __( 'Deleted post' ) );
}
}
/**
* Delete a comment.
*
* @uses wp_delete_comment
* @param int $id Post ID
* @param int $comment Comment ID
* @param boolean $force Skip trash
* @return array
*/
public function delete_comment( $id, $comment, $force = false ) {
$comment = (int) $comment;
if ( empty( $comment ) )
return new WP_Error( 'json_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
$comment_array = get_comment( $comment, ARRAY_A );
if ( empty( $comment_array ) )
return new WP_Error( 'json_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
if ( ! current_user_can( 'edit_comment', $comment_array['comment_ID'] ) )
return new WP_Error( 'json_user_cannot_delete_comment', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => 401 ) );
$result = wp_delete_comment( $comment_array['comment_ID'], $force );
if ( ! $result )
return new WP_Error( 'json_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
if ( $force ) {
return array( 'message' => __( 'Permanently deleted comment' ) );
}
else {
// TODO: return a HTTP 202 here instead
return array( 'message' => __( 'Deleted comment' ) );
}
}
/**
* Retrieve comments
*
* @param int $id Post ID to retrieve comments for
* @return array List of Comment entities
*/
public function get_comments( $id ) {
//$args = array('status' => $status, 'post_id' => $id, 'offset' => $offset, 'number' => $number )l
$comments = get_comments( array('post_id' => $id) );
$post = get_post( $id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
}
if ( ! $this->check_read_permission( $post ) ) {
return new WP_Error( 'json_user_cannot_read', __( 'Sorry, you cannot read this post.' ), array( 'status' => 401 ) );
}
$struct = array();
foreach ( $comments as $comment ) {
$struct[] = $this->prepare_comment( $comment, array( 'comment', 'meta' ), 'collection' );
}
return $struct;
}
/**
* Retrieve a single comment
*
* @param int $comment Comment ID
* @return array Comment entity
*/
public function get_comment( $comment ) {
$comment = get_comment( $comment );
if ( empty( $comment ) ) {
return new WP_Error( 'json_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
}
$data = $this->prepare_comment( $comment );
return $data;
}
/**
* Get all public post types
*
* @uses self::get_post_type()
* @return array List of post type data
*/
public function get_post_types() {
$data = get_post_types( array(), 'objects' );
$types = array();
foreach ($data as $name => $type) {
$type = $this->get_post_type( $type, true );
if ( is_wp_error( $type ) )
continue;
$types[ $name ] = $type;
}
return $types;
}
/**
* Get a post type
*
* @param string|object $type Type name, or type object (internal use)
* @param boolean $_in_collection Is this in a collection? (internal use)
* @return array Post type data
*/
public function get_post_type( $type, $_in_collection = false ) {
if ( ! is_object( $type ) )
$type = get_post_type_object($type);
if ( $type->show_in_json === false ) {
return new WP_Error( 'json_cannot_read_type', __( 'Cannot view post type' ), array( 'status' => 403 ) );
}
$data = array(
'name' => $type->label,
'slug' => $type->name,
'description' => $type->description,
'labels' => $type->labels,
'queryable' => $type->publicly_queryable,
'searchable' => ! $type->exclude_from_search,
'hierarchical' => $type->hierarchical,
'meta' => array(
'links' => array()
),
);
if ( $_in_collection )
$data['meta']['links']['self'] = json_url( '/posts/types/' . $type->name );
else
$data['meta']['links']['collection'] = json_url( '/posts/types' );
if ( $type->publicly_queryable ) {
if ($type->name === 'post')
$data['meta']['links']['archives'] = json_url( '/posts' );
else
$data['meta']['links']['archives'] = json_url( add_query_arg( 'type', $type->name, '/posts' ) );
}
return apply_filters( 'json_post_type_data', $data, $type );
}
/**
* Get the registered post statuses
*
* @return array List of post status data
*/
public function get_post_statuses() {
$statuses = get_post_stati(array(), 'objects');
$data = array();
foreach ($statuses as $status) {
if ( $status->internal === true || ! $status->show_in_admin_status_list )
continue;
$data[ $status->name ] = array(
'name' => $status->label,
'slug' => $status->name,
'public' => $status->public,
'protected' => $status->protected,
'private' => $status->private,
'queryable' => $status->publicly_queryable,
'show_in_list' => $status->show_in_admin_all_list,
'meta' => array(
'links' => array()
),
);
if ( $status->publicly_queryable ) {
if ($status->name === 'publish')
$data[ $status->name ]['meta']['links']['archives'] = json_url( '/posts' );
else
$data[ $status->name ]['meta']['links']['archives'] = json_url( add_query_arg( 'status', $status->name, '/posts' ) );
}
}
return apply_filters( 'json_post_statuses', $data, $statuses );
}
/**
* Prepares post data for return in an XML-RPC object.
*
* @access protected
*
* @param array $post The unprepared post data
* @param string $context The context for the prepared post. (view|view-revision|edit)
* @return array The prepared post data
*/
protected function prepare_post( $post, $context = 'view' ) {
// holds the data for this post. built up based on $fields
$_post = array(
'ID' => (int) $post['ID'],
);
$post_type = get_post_type_object( $post['post_type'] );
if ( ! $this->check_read_permission( $post ) )
return new WP_Error( 'json_user_cannot_read', __( 'Sorry, you cannot read this post.' ), array( 'status' => 401 ) );
// prepare common post fields
$post_fields = array(
'title' => get_the_title( $post['ID'] ), // $post['post_title'],
'status' => $post['post_status'],
'type' => $post['post_type'],
'author' => (int) $post['post_author'],
'content' => apply_filters( 'the_content', $post['post_content'] ),
'parent' => (int) $post['post_parent'],
#'post_mime_type' => $post['post_mime_type'],
'link' => get_permalink( $post['ID'] ),
);
$post_fields_extended = array(
'slug' => $post['post_name'],
'guid' => apply_filters( 'get_the_guid', $post['guid'] ),
'excerpt' => $this->prepare_excerpt( $post['post_excerpt'] ),
'menu_order' => (int) $post['menu_order'],
'comment_status' => $post['comment_status'],
'ping_status' => $post['ping_status'],
'sticky' => ( $post['post_type'] === 'post' && is_sticky( $post['ID'] ) ),
);
$post_fields_raw = array(
'title_raw' => $post['post_title'],
'content_raw' => $post['post_content'],
'guid_raw' => $post['guid'],
'post_meta' => $this->prepare_meta( $post['ID'] ),
);
// Dates
$timezone = $this->server->get_timezone();
$date = WP_JSON_DateTime::createFromFormat( 'Y-m-d H:i:s', $post['post_date'], $timezone );
$post_fields['date'] = $date->format( 'c' );
$post_fields_extended['date_tz'] = $date->format( 'e' );
$post_fields_extended['date_gmt'] = date( 'c', strtotime( $post['post_date_gmt'] ) );
$modified = WP_JSON_DateTime::createFromFormat( 'Y-m-d H:i:s', $post['post_modified'], $timezone );
$post_fields['modified'] = $modified->format( 'c' );
$post_fields_extended['modified_tz'] = $modified->format( 'e' );
$post_fields_extended['modified_gmt'] = date( 'c', strtotime( $post['post_modified_gmt'] ) );
// Authorized fields
// TODO: Send `Vary: Authorization` to clarify that the data can be
// changed by the user's auth status
if ( current_user_can( $post_type->cap->edit_post, $post['ID'] ) ) {
$post_fields_extended['password'] = $post['post_password'];
}
// Consider future posts as published
if ( $post_fields['status'] === 'future' )
$post_fields['status'] = 'publish';
// Fill in blank post format
$post_fields['format'] = get_post_format( $post['ID'] );
if ( empty( $post_fields['format'] ) )
$post_fields['format'] = 'standard';
if ( ( 'view' === $context || 'view-revision' == $context ) && 0 !== $post['post_parent'] ) {
// Avoid nesting too deeply
// This gives post + post-extended + meta for the main post,
// post + meta for the parent and just meta for the grandparent
$parent = get_post( $post['post_parent'], ARRAY_A );
$post_fields['parent'] = $this->prepare_post( $parent, 'parent' );
}
// Merge requested $post_fields fields into $_post
$_post = array_merge( $_post, $post_fields );
// Include extended fields. We might come back to this.
$_post = array_merge( $_post, $post_fields_extended );
if ( 'edit' === $context ) {
if ( current_user_can( $post_type->cap->edit_post, $post['ID'] ) ) {
$_post = array_merge( $_post, $post_fields_raw );
} else {
return new WP_Error( 'json_cannot_edit', __( 'Sorry, you cannot edit this post' ), array( 'status' => 403 ) );
}
} elseif ( 'view-revision' == $context ) {
if ( current_user_can( $post_type->cap->edit_post, $post['ID'] ) ) {
$_post = array_merge( $_post, $post_fields_raw );
} else {
return new WP_Error( 'json_cannot_view', __( 'Sorry, you cannot view this revision' ), array( 'status' => 403 ) );
}
}
// Entity meta
$links = array(
'self' => json_url( '/posts/' . $post['ID'] ),
'author' => json_url( '/users/' . $post['post_author'] ),
'collection' => json_url( '/posts' ),
);
if ( 'view-revision' != $context ) {
$links['replies'] = json_url( '/posts/' . $post['ID'] . '/comments' );
$links['version-history'] = json_url( '/posts/' . $post['ID'] . '/revisions' );
}
$_post['meta'] = array( 'links' => $links );
if ( ! empty( $post['post_parent'] ) )
$_post['meta']['links']['up'] = json_url( '/posts/' . (int) $post['post_parent'] );
return apply_filters( 'json_prepare_post', $_post, $post, $context );
}
/**
* Retrieve the post excerpt.
*
* @return string
*/
protected function prepare_excerpt( $excerpt ) {
if ( post_password_required() ) {
return __( 'There is no excerpt because this is a protected post.' );
}
$excerpt = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $excerpt ) );
if ( empty( $excerpt ) ) {
return null;
}
return $excerpt;
}
/**
* Retrieve custom fields for post.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
* @return array Custom fields, if exist.
*/
protected function prepare_meta( $post_id ) {
$post_id = (int) $post_id;
$custom_fields = (array) get_post_meta( $post_id );
foreach ( $custom_fields as $meta_key => $meta_value ) {
// Don't expose protected fields.
if ( is_protected_meta( $meta_key ) )
unset( $custom_fields[$meta_key] );
}
return apply_filters( 'json_prepare_meta', $custom_fields, $post_id );
}
/**
* Helper method for wp_newPost and wp_editPost, containing shared logic.
*
* @since 3.4.0
* @uses wp_insert_post()
*
* @param WP_User $user The post author if post_author isn't set in $content_struct.
* @param array $content_struct Post data to insert.
*/
protected function insert_post( $data ) {
$post = array();
$update = ! empty( $data['ID'] );
if ( $update ) {
$current_post = get_post( absint( $data['ID'] ) );
if ( ! $current_post )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 400 ) );
$post['ID'] = absint( $data['ID'] );
}
else {
// Defaults
$post['post_author'] = 0;
$post['post_password'] = '';
$post['post_excerpt'] = '';
$post['post_content'] = '';
$post['post_title'] = '';
}
// Post type
if ( ! empty( $data['type'] ) ) {
// Changing post type
$post_type = get_post_type_object( $data['type'] );
if ( ! $post_type )
return new WP_Error( 'json_invalid_post_type', __( 'Invalid post type' ), array( 'status' => 400 ) );
$post['post_type'] = $data['type'];
}
elseif ( $update ) {
// Updating post, use existing post type
$current_post = get_post( $data['ID'] );
if ( ! $current_post )
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 400 ) );
$post_type = get_post_type_object( $current_post->post_type );
}
else {
// Creating new post, use default type
$post['post_type'] = apply_filters( 'json_insert_default_post_type', 'post' );
$post_type = get_post_type_object( $post['post_type'] );
if ( ! $post_type )
return new WP_Error( 'json_invalid_post_type', __( 'Invalid post type' ), array( 'status' => 400 ) );
}
// Permissions check
if ( $update ) {
if ( ! current_user_can( $post_type->cap->edit_post, $data['ID'] ) )
return new WP_Error( 'json_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => 401 ) );
if ( $post_type->name != get_post_type( $data['ID'] ) )
return new WP_Error( 'json_cannot_change_post_type', __( 'The post type may not be changed.' ), array( 'status' => 400 ) );
} else {
if ( ! current_user_can( $post_type->cap->create_posts ) || ! current_user_can( $post_type->cap->edit_posts ) )
return new WP_Error( 'json_cannot_create', __( 'Sorry, you are not allowed to post on this site.' ), array( 'status' => 400 ) );
}
// Post status
if ( ! empty( $data['status'] ) ) {
$post['post_status'] = $data['status'];
switch ( $post['post_status'] ) {
case 'draft':
case 'pending':
break;
case 'private':
if ( ! current_user_can( $post_type->cap->publish_posts ) )
return new WP_Error( 'json_cannot_create_private', __( 'Sorry, you are not allowed to create private posts in this post type' ), array( 'status' => 403 ) );
break;
case 'publish':
case 'future':
if ( ! current_user_can( $post_type->cap->publish_posts ) )
return new WP_Error( 'json_cannot_publish', __( 'Sorry, you are not allowed to publish posts in this post type' ), array( 'status' => 403 ) );
break;
default:
if ( ! get_post_status_object( $post['post_status'] ) )
$post['post_status'] = 'draft';
break;
}
}
// Post title
if ( ! empty( $data['title'] ) ) {
$post['post_title'] = $data['title'];
}
// Post date
if ( ! empty( $data['date'] ) ) {
list( $post['post_date'], $post['post_date_gmt'] ) = $this->server->get_date_with_gmt( $data['date'] );
}
elseif ( ! empty( $data['date_gmt'] ) ) {
list( $post['post_date'], $post['post_date_gmt'] ) = $this->server->get_date_with_gmt( $data['date_gmt'], true );
}
// Post modified
if ( ! empty( $data['modified'] ) ) {
list( $post['post_modified'], $post['post_modified_gmt'] ) = $this->server->get_date_with_gmt( $data['modified'] );
}
elseif ( ! empty( $data['modified_gmt'] ) ) {
list( $post['post_modified'], $post['post_modified_gmt'] ) = $this->server->get_date_with_gmt( $data['modified_gmt'], true );
}
// Post slug
if ( ! empty( $data['name'] ) ) {
$post['post_name'] = $data['name'];
}
// Author
if ( ! empty( $data['author'] ) ) {
// Allow passing an author object
if ( is_object( $data['author'] ) ) {
if ( empty( $data['author']->ID ) ) {
return new WP_Error( 'json_invalid_author', __( 'Invalid author object.' ), array( 'status' => 400 ) );
}
$data['author'] = absint( $data['author']->ID );
}
else {
$data['author'] = absint( $data['author'] );
}
// Only check edit others' posts if we are another user
if ( $data['author'] !== get_current_user_id() ) {
if ( ! current_user_can( $post_type->cap->edit_others_posts ) )
return new WP_Error( 'json_cannot_edit_others', __( 'You are not allowed to edit posts as this user.' ), array( 'status' => 401 ) );
$author = get_userdata( $data['author'] );
if ( ! $author )
return new WP_Error( 'json_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) );
}
$post['post_author'] = $data['author'];
}
// Post password
if ( ! empty( $data['password'] ) ) {
$post['post_password'] = $data['password'];
if ( ! current_user_can( $post_type->cap->publish_posts ) )
return new WP_Error( 'json_cannot_create_passworded', __( 'Sorry, you are not allowed to create password protected posts in this post type' ), array( 'status' => 401 ) );
}
// Content and excerpt
if ( ! empty( $data['content_raw'] ) ) {
$post['post_content'] = $data['content_raw'];
}
if ( ! empty( $data['excerpt_raw'] ) ) {
$post['post_excerpt'] = $data['excerpt_raw'];
}
// Parent
if ( ! empty( $data['parent'] ) ) {
$parent = get_post( $data['parent'] );
$post['post_parent'] = $data['post_parent'];
}
// Menu order
if ( ! empty( $data['menu_order'] ) ) {
$post['menu_order'] = $data['menu_order'];
}
// Comment status
if ( ! empty( $data['comment_status'] ) ) {
$post['comment_status'] = $data['comment_status'];
}
// Ping status
if ( ! empty( $data['ping_status'] ) ) {
$post['ping_status'] = $data['ping_status'];
}
// Post format
if ( ! empty( $data['post_format'] ) ) {
$formats = get_post_format_slugs();
if ( ! in_array( $data['post_format'], $formats ) ) {
return new WP_Error( 'json_invalid_post_format', __( 'Invalid post format.' ), array( 'status' => 400 ) );
}
$post['post_format'] = $data['post_format'];
}
// Pre-insert hook
$can_insert = apply_filters( 'json_pre_insert_post', true, $post, $data, $update );
if ( is_wp_error( $can_insert ) ) {
return $can_insert;
}
// Post meta
// TODO: implement this
$post_ID = $update ? wp_update_post( $post, true ) : wp_insert_post( $post, true );
if ( is_wp_error( $post_ID ) ) {
return $post_ID;
}
// If this is a new post, add the post ID to $post
if ( ! $update ) {
$post['ID'] = $post_ID;
}
// Sticky
if ( isset( $post['sticky'] ) ) {
if ( $post['sticky'] )
stick_post( $data['ID'] );
else
unstick_post( $data['ID'] );
}
do_action( 'json_insert_post', $post, $data, $update );
return $post_ID;
}
/**
* Parse an RFC3339 timestamp into a DateTime
*
* @param string $date RFC3339 timestamp
* @param boolean $force_utc Force UTC timezone instead of using the timestamp's TZ?
* @return DateTime
*/
protected function parse_date( $date, $force_utc = false ) {
// Default timezone to the server's current one
$timezone = self::get_timezone();
if ( $force_utc ) {
$date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
$timezone = new DateTimeZone( 'UTC' );
}
// Strip millisecond precision (a full stop followed by one or more digits)
if ( strpos( $date, '.' ) !== false ) {
$date = preg_replace( '/\.\d+/', '', $date );
}
$datetime = WP_JSON_DateTime::createFromFormat( DateTime::RFC3339, $date );
return $datetime;
}
/**
* Get a local date with its GMT equivalent, in MySQL datetime format
*
* @param string $date RFC3339 timestamp
* @param boolean $force_utc Should we force UTC timestamp?
* @return array Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s)
*/
protected function get_date_with_gmt( $date, $force_utc = false ) {
$datetime = $this->server->parse_date( $date, $force_utc );
$datetime->setTimezone( self::get_timezone() );
$local = $datetime->format( 'Y-m-d H:i:s' );
$datetime->setTimezone( new DateTimeZone( 'UTC' ) );
$utc = $datetime->format('Y-m-d H:i:s');
return array( $local, $utc );
}
/**
* Prepares comment data for returning as a JSON response.
*
* @param stdClass $comment Comment object
* @param array $requested_fields Fields to retrieve from the comment
* @param string $context Where is the comment being loaded?
* @return array Comment data for JSON serialization