forked from Automattic/jetpack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class.json-api-endpoints.php
1901 lines (1646 loc) · 60.4 KB
/
class.json-api-endpoints.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
require_once( dirname( __FILE__ ) . '/json-api-config.php' );
require_once( dirname( __FILE__ ) . '/sal/class.json-api-links.php' );
require_once( dirname( __FILE__ ) . '/sal/class.json-api-metadata.php' );
require_once( dirname( __FILE__ ) . '/sal/class.json-api-date.php' );
// Endpoint
abstract class WPCOM_JSON_API_Endpoint {
// The API Object
public $api;
// The link-generating utility class
public $links;
public $pass_wpcom_user_details = false;
// One liner.
public $description;
// Object Grouping For Documentation (Users, Posts, Comments)
public $group;
// Stats extra value to bump
public $stat;
// HTTP Method
public $method = 'GET';
// Minimum version of the api for which to serve this endpoint
public $min_version = '0';
// Maximum version of the api for which to serve this endpoint
public $max_version = WPCOM_JSON_API__CURRENT_VERSION;
// Path at which to serve this endpoint: sprintf() format.
public $path = '';
// Identifiers to fill sprintf() formatted $path
public $path_labels = array();
// Accepted query parameters
public $query = array(
// Parameter name
'context' => array(
// Default value => description
'display' => 'Formats the output as HTML for display. Shortcodes are parsed, paragraph tags are added, etc..',
// Other possible values => description
'edit' => 'Formats the output for editing. Shortcodes are left unparsed, significant whitespace is kept, etc..',
),
'http_envelope' => array(
'false' => '',
'true' => 'Some environments (like in-browser JavaScript or Flash) block or divert responses with a non-200 HTTP status code. Setting this parameter will force the HTTP status code to always be 200. The JSON response is wrapped in an "envelope" containing the "real" HTTP status code and headers.',
),
'pretty' => array(
'false' => '',
'true' => 'Output pretty JSON',
),
'meta' => "(string) Optional. Loads data from the endpoints found in the 'meta' part of the response. Comma-separated list. Example: meta=site,likes",
'fields' => '(string) Optional. Returns specified fields only. Comma-separated list. Example: fields=ID,title',
// Parameter name => description (default value is empty)
'callback' => '(string) An optional JSONP callback function.',
);
// Response format
public $response_format = array();
// Request format
public $request_format = array();
// Is this endpoint still in testing phase? If so, not available to the public.
public $in_testing = false;
// Is this endpoint still allowed if the site in question is flagged?
public $allowed_if_flagged = false;
// Is this endpoint allowed if the site is red flagged?
public $allowed_if_red_flagged = false;
/**
* @var string Version of the API
*/
public $version = '';
/**
* @var string Example request to make
*/
public $example_request = '';
/**
* @var string Example request data (for POST methods)
*/
public $example_request_data = '';
/**
* @var string Example response from $example_request
*/
public $example_response = '';
/**
* @var bool Set to true if the endpoint implements its own filtering instead of the standard `fields` query method
*/
public $custom_fields_filtering = false;
/**
* @var bool Set to true if the endpoint accepts all cross origin requests. You probably should not set this flag.
*/
public $allow_cross_origin_request = false;
/**
* @var bool Set to true if the endpoint can recieve unauthorized POST requests.
*/
public $allow_unauthorized_request = false;
/**
* @var bool Set to true if the endpoint should accept site based (not user based) authentication.
*/
public $allow_jetpack_site_auth = false;
function __construct( $args ) {
$defaults = array(
'in_testing' => false,
'allowed_if_flagged' => false,
'allowed_if_red_flagged' => false,
'description' => '',
'group' => '',
'method' => 'GET',
'path' => '/',
'min_version' => '0',
'max_version' => WPCOM_JSON_API__CURRENT_VERSION,
'force' => '',
'deprecated' => false,
'new_version' => WPCOM_JSON_API__CURRENT_VERSION,
'jp_disabled' => false,
'path_labels' => array(),
'request_format' => array(),
'response_format' => array(),
'query_parameters' => array(),
'version' => 'v1',
'example_request' => '',
'example_request_data' => '',
'example_response' => '',
'required_scope' => '',
'pass_wpcom_user_details' => false,
'custom_fields_filtering' => false,
'allow_cross_origin_request' => false,
'allow_unauthorized_request' => false,
'allow_jetpack_site_auth' => false,
);
$args = wp_parse_args( $args, $defaults );
$this->in_testing = $args['in_testing'];
$this->allowed_if_flagged = $args['allowed_if_flagged'];
$this->allowed_if_red_flagged = $args['allowed_if_red_flagged'];
$this->description = $args['description'];
$this->group = $args['group'];
$this->stat = $args['stat'];
$this->force = $args['force'];
$this->jp_disabled = $args['jp_disabled'];
$this->method = $args['method'];
$this->path = $args['path'];
$this->path_labels = $args['path_labels'];
$this->min_version = $args['min_version'];
$this->max_version = $args['max_version'];
$this->deprecated = $args['deprecated'];
$this->new_version = $args['new_version'];
$this->pass_wpcom_user_details = $args['pass_wpcom_user_details'];
$this->custom_fields_filtering = (bool) $args['custom_fields_filtering'];
$this->allow_cross_origin_request = (bool) $args['allow_cross_origin_request'];
$this->allow_unauthorized_request = (bool) $args['allow_unauthorized_request'];
$this->allow_jetpack_site_auth = (bool) $args['allow_jetpack_site_auth'];
$this->version = $args['version'];
$this->required_scope = $args['required_scope'];
if ( $this->request_format ) {
$this->request_format = array_filter( array_merge( $this->request_format, $args['request_format'] ) );
} else {
$this->request_format = $args['request_format'];
}
if ( $this->response_format ) {
$this->response_format = array_filter( array_merge( $this->response_format, $args['response_format'] ) );
} else {
$this->response_format = $args['response_format'];
}
if ( false === $args['query_parameters'] ) {
$this->query = array();
} elseif ( is_array( $args['query_parameters'] ) ) {
$this->query = array_filter( array_merge( $this->query, $args['query_parameters'] ) );
}
$this->api = WPCOM_JSON_API::init(); // Auto-add to WPCOM_JSON_API
$this->links = WPCOM_JSON_API_Links::getInstance();
/** Example Request/Response ******************************************/
// Examples for endpoint documentation request
$this->example_request = $args['example_request'];
$this->example_request_data = $args['example_request_data'];
$this->example_response = $args['example_response'];
$this->api->add( $this );
}
// Get all query args. Prefill with defaults
function query_args( $return_default_values = true, $cast_and_filter = true ) {
$args = array_intersect_key( $this->api->query, $this->query );
if ( !$cast_and_filter ) {
return $args;
}
return $this->cast_and_filter( $args, $this->query, $return_default_values );
}
// Get POST body data
function input( $return_default_values = true, $cast_and_filter = true ) {
$input = trim( $this->api->post_body );
$content_type = $this->api->content_type;
if ( $content_type ) {
list ( $content_type ) = explode( ';', $content_type );
}
$content_type = trim( $content_type );
switch ( $content_type ) {
case 'application/json' :
case 'application/x-javascript' :
case 'text/javascript' :
case 'text/x-javascript' :
case 'text/x-json' :
case 'text/json' :
$return = json_decode( $input, true );
if ( function_exists( 'json_last_error' ) ) {
if ( JSON_ERROR_NONE !== json_last_error() ) {
return null;
}
} else {
if ( is_null( $return ) && json_encode( null ) !== $input ) {
return null;
}
}
break;
case 'multipart/form-data' :
$return = array_merge( stripslashes_deep( $_POST ), $_FILES );
break;
case 'application/x-www-form-urlencoded' :
//attempt JSON first, since probably a curl command
$return = json_decode( $input, true );
if ( is_null( $return ) ) {
wp_parse_str( $input, $return );
}
break;
default :
wp_parse_str( $input, $return );
break;
}
if ( !$cast_and_filter ) {
return $return;
}
return $this->cast_and_filter( $return, $this->request_format, $return_default_values );
}
function cast_and_filter( $data, $documentation, $return_default_values = false, $for_output = false ) {
$return_as_object = false;
if ( is_object( $data ) ) {
// @todo this should probably be a deep copy if $data can ever have nested objects
$data = (array) $data;
$return_as_object = true;
} elseif ( !is_array( $data ) ) {
return $data;
}
$boolean_arg = array( 'false', 'true' );
$naeloob_arg = array( 'true', 'false' );
$return = array();
foreach ( $documentation as $key => $description ) {
if ( is_array( $description ) ) {
// String or boolean array keys only
$whitelist = array_keys( $description );
if ( $whitelist === $boolean_arg || $whitelist === $naeloob_arg ) {
// Truthiness
if ( isset( $data[$key] ) ) {
$return[$key] = (bool) WPCOM_JSON_API::is_truthy( $data[$key] );
} elseif ( $return_default_values ) {
$return[$key] = $whitelist === $naeloob_arg; // Default to true for naeloob_arg and false for boolean_arg.
}
} elseif ( isset( $data[$key] ) && isset( $description[$data[$key]] ) ) {
// String Key
$return[$key] = (string) $data[$key];
} elseif ( $return_default_values ) {
// Default value
$return[$key] = (string) current( $whitelist );
}
continue;
}
$types = $this->parse_types( $description );
$type = array_shift( $types );
// Explicit default - string and int only for now. Always set these reguardless of $return_default_values
if ( isset( $type['default'] ) ) {
if ( !isset( $data[$key] ) ) {
$data[$key] = $type['default'];
}
}
if ( !isset( $data[$key] ) ) {
continue;
}
$this->cast_and_filter_item( $return, $type, $key, $data[$key], $types, $for_output );
}
if ( $return_as_object ) {
return (object) $return;
}
return $return;
}
/**
* Casts $value according to $type.
* Handles fallbacks for certain values of $type when $value is not that $type
* Currently, only handles fallback between string <-> array (two way), from string -> false (one way), and from object -> false (one way),
* and string -> object (one way)
*
* Handles "child types" - array:URL, object:category
* array:URL means an array of URLs
* object:category means a hash of categories
*
* Handles object typing - object>post means an object of type post
*/
function cast_and_filter_item( &$return, $type, $key, $value, $types = array(), $for_output = false ) {
if ( is_string( $type ) ) {
$type = compact( 'type' );
}
switch ( $type['type'] ) {
case 'false' :
$return[$key] = false;
break;
case 'url' :
$return[$key] = (string) esc_url_raw( $value );
break;
case 'string' :
// Fallback string -> array, or for string -> object
if ( is_array( $value ) || is_object( $value ) ) {
if ( !empty( $types[0] ) ) {
$next_type = array_shift( $types );
return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output );
}
}
// Fallback string -> false
if ( !is_string( $value ) ) {
if ( !empty( $types[0] ) && 'false' === $types[0]['type'] ) {
$next_type = array_shift( $types );
return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output );
}
}
$return[$key] = (string) $value;
break;
case 'html' :
$return[$key] = (string) $value;
break;
case 'safehtml' :
$return[$key] = wp_kses( (string) $value, wp_kses_allowed_html() );
break;
case 'media' :
if ( is_array( $value ) ) {
if ( isset( $value['name'] ) && is_array( $value['name'] ) ) {
// It's a $_FILES array
// Reformat into array of $_FILES items
$files = array();
foreach ( $value['name'] as $k => $v ) {
$files[$k] = array();
foreach ( array_keys( $value ) as $file_key ) {
$files[$k][$file_key] = $value[$file_key][$k];
}
}
$return[$key] = $files;
break;
}
} else {
// no break - treat as 'array'
}
// nobreak
case 'array' :
// Fallback array -> string
if ( is_string( $value ) ) {
if ( !empty( $types[0] ) ) {
$next_type = array_shift( $types );
return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output );
}
}
if ( isset( $type['children'] ) ) {
$children = array();
foreach ( (array) $value as $k => $child ) {
$this->cast_and_filter_item( $children, $type['children'], $k, $child, array(), $for_output );
}
$return[$key] = (array) $children;
break;
}
$return[$key] = (array) $value;
break;
case 'iso 8601 datetime' :
case 'datetime' :
// (string)s
$dates = $this->parse_date( (string) $value );
if ( $for_output ) {
$return[$key] = $this->format_date( $dates[1], $dates[0] );
} else {
list( $return[$key], $return["{$key}_gmt"] ) = $dates;
}
break;
case 'float' :
$return[$key] = (float) $value;
break;
case 'int' :
case 'integer' :
$return[$key] = (int) $value;
break;
case 'bool' :
case 'boolean' :
$return[$key] = (bool) WPCOM_JSON_API::is_truthy( $value );
break;
case 'object' :
// Fallback object -> false
if ( is_scalar( $value ) || is_null( $value ) ) {
if ( !empty( $types[0] ) && 'false' === $types[0]['type'] ) {
return $this->cast_and_filter_item( $return, 'false', $key, $value, $types, $for_output );
}
}
if ( isset( $type['children'] ) ) {
$children = array();
foreach ( (array) $value as $k => $child ) {
$this->cast_and_filter_item( $children, $type['children'], $k, $child, array(), $for_output );
}
$return[$key] = (object) $children;
break;
}
if ( isset( $type['subtype'] ) ) {
return $this->cast_and_filter_item( $return, $type['subtype'], $key, $value, $types, $for_output );
}
$return[$key] = (object) $value;
break;
case 'post' :
$return[$key] = (object) $this->cast_and_filter( $value, $this->post_object_format, false, $for_output );
break;
case 'comment' :
$return[$key] = (object) $this->cast_and_filter( $value, $this->comment_object_format, false, $for_output );
break;
case 'tag' :
case 'category' :
$docs = array(
'ID' => '(int)',
'name' => '(string)',
'slug' => '(string)',
'description' => '(HTML)',
'post_count' => '(int)',
'meta' => '(object)',
);
if ( 'category' === $type['type'] ) {
$docs['parent'] = '(int)';
}
$return[$key] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'post_reference' :
case 'comment_reference' :
$docs = array(
'ID' => '(int)',
'type' => '(string)',
'title' => '(string)',
'link' => '(URL)',
);
$return[$key] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'geo' :
$docs = array(
'latitude' => '(float)',
'longitude' => '(float)',
'address' => '(string)',
);
$return[$key] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'author' :
$docs = array(
'ID' => '(int)',
'user_login' => '(string)',
'login' => '(string)',
'email' => '(string|false)',
'name' => '(string)',
'first_name' => '(string)',
'last_name' => '(string)',
'nice_name' => '(string)',
'URL' => '(URL)',
'avatar_URL' => '(URL)',
'profile_URL' => '(URL)',
'is_super_admin' => '(bool)',
'roles' => '(array:string)'
);
$return[$key] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'role' :
$docs = array(
'name' => '(string)',
'display_name' => '(string)',
'capabilities' => '(object:boolean)',
);
$return[$key] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'attachment' :
$docs = array(
'ID' => '(int)',
'URL' => '(URL)',
'guid' => '(string)',
'mime_type' => '(string)',
'width' => '(int)',
'height' => '(int)',
'duration' => '(int)',
);
$return[$key] = (object) $this->cast_and_filter(
$value,
/**
* Filter the documentation returned for a post attachment.
*
* @module json-api
*
* @since 1.9.0
*
* @param array $docs Array of documentation about a post attachment.
*/
apply_filters( 'wpcom_json_api_attachment_cast_and_filter', $docs ),
false,
$for_output
);
break;
case 'metadata' :
$docs = array(
'id' => '(int)',
'key' => '(string)',
'value' => '(string|false|float|int|array|object)',
'previous_value' => '(string)',
'operation' => '(string)',
);
$return[$key] = (object) $this->cast_and_filter(
$value,
/** This filter is documented in class.json-api-endpoints.php */
apply_filters( 'wpcom_json_api_attachment_cast_and_filter', $docs ),
false,
$for_output
);
break;
case 'plugin' :
$docs = array(
'id' => '(safehtml) The plugin\'s ID',
'slug' => '(safehtml) The plugin\'s Slug',
'active' => '(boolean) The plugin status.',
'update' => '(object) The plugin update info.',
'name' => '(safehtml) The name of the plugin.',
'plugin_url' => '(url) Link to the plugin\'s web site.',
'version' => '(safehtml) The plugin version number.',
'description' => '(safehtml) Description of what the plugin does and/or notes from the author',
'author' => '(safehtml) The plugin author\'s name',
'author_url' => '(url) The plugin author web site address',
'network' => '(boolean) Whether the plugin can only be activated network wide.',
'autoupdate' => '(boolean) Whether the plugin is auto updated',
'log' => '(array:safehtml) An array of update log strings.',
);
$return[$key] = (object) $this->cast_and_filter(
$value,
/**
* Filter the documentation returned for a plugin.
*
* @module json-api
*
* @since 3.1.0
*
* @param array $docs Array of documentation about a plugin.
*/
apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
false,
$for_output
);
break;
case 'jetpackmodule' :
$docs = array(
'id' => '(string) The module\'s ID',
'active' => '(boolean) The module\'s status.',
'name' => '(string) The module\'s name.',
'description' => '(safehtml) The module\'s description.',
'sort' => '(int) The module\'s display order.',
'introduced' => '(string) The Jetpack version when the module was introduced.',
'changed' => '(string) The Jetpack version when the module was changed.',
'free' => '(boolean) The module\'s Free or Paid status.',
'module_tags' => '(array) The module\'s tags.'
);
$return[$key] = (object) $this->cast_and_filter(
$value,
/** This filter is documented in class.json-api-endpoints.php */
apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
false,
$for_output
);
break;
case 'sharing_button' :
$docs = array(
'ID' => '(string)',
'name' => '(string)',
'URL' => '(string)',
'icon' => '(string)',
'enabled' => '(bool)',
'visibility' => '(string)',
);
$return[$key] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'sharing_button_service':
$docs = array(
'ID' => '(string) The service identifier',
'name' => '(string) The service name',
'class_name' => '(string) Class name for custom style sharing button elements',
'genericon' => '(string) The Genericon unicode character for the custom style sharing button icon',
'preview_smart' => '(string) An HTML snippet of a rendered sharing button smart preview',
'preview_smart_js' => '(string) An HTML snippet of the page-wide initialization scripts used for rendering the sharing button smart preview'
);
$return[$key] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
case 'taxonomy':
$docs = array(
'name' => '(string) The taxonomy slug',
'label' => '(string) The taxonomy human-readable name',
'labels' => '(object) Mapping of labels for the taxonomy',
'description' => '(string) The taxonomy description',
'hierarchical' => '(bool) Whether the taxonomy is hierarchical',
'public' => '(bool) Whether the taxonomy is public',
'capabilities' => '(object) Mapping of current user capabilities for the taxonomy',
);
$return[$key] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
break;
default :
$method_name = $type['type'] . '_docs';
if ( method_exists( WPCOM_JSON_API_Jetpack_Overrides, $method_name ) ) {
$docs = WPCOM_JSON_API_Jetpack_Overrides::$method_name();
}
if ( ! empty( $docs ) ) {
$return[$key] = (object) $this->cast_and_filter(
$value,
/** This filter is documented in class.json-api-endpoints.php */
apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
false,
$for_output
);
} else {
trigger_error( "Unknown API casting type {$type['type']}", E_USER_WARNING );
}
}
}
function parse_types( $text ) {
if ( !preg_match( '#^\(([^)]+)\)#', ltrim( $text ), $matches ) ) {
return 'none';
}
$types = explode( '|', strtolower( $matches[1] ) );
$return = array();
foreach ( $types as $type ) {
foreach ( array( ':' => 'children', '>' => 'subtype', '=' => 'default' ) as $operator => $meaning ) {
if ( false !== strpos( $type, $operator ) ) {
$item = explode( $operator, $type, 2 );
$return[] = array( 'type' => $item[0], $meaning => $item[1] );
continue 2;
}
}
$return[] = compact( 'type' );
}
return $return;
}
/**
* Checks if the endpoint is publicly displayable
*/
function is_publicly_documentable() {
return '__do_not_document' !== $this->group && true !== $this->in_testing;
}
/**
* Auto generates documentation based on description, method, path, path_labels, and query parameters.
* Echoes HTML.
*/
function document( $show_description = true ) {
global $wpdb;
$original_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : 'unset';
unset( $GLOBALS['post'] );
$doc = $this->generate_documentation();
if ( $show_description ) :
?>
<caption>
<h1><?php echo wp_kses_post( $doc['method'] ); ?> <?php echo wp_kses_post( $doc['path_labeled'] ); ?></h1>
<p><?php echo wp_kses_post( $doc['description'] ); ?></p>
</caption>
<?php endif; ?>
<?php if ( true === $this->deprecated ) { ?>
<p><strong>This endpoint is deprecated in favor of version <?php echo floatval( $this->new_version ); ?></strong></p>
<?php } ?>
<section class="resource-info">
<h2 id="apidoc-resource-info">Resource Information</h2>
<table class="api-doc api-doc-resource-parameters api-doc-resource">
<thead>
<tr>
<th class="api-index-title" scope="column"> </th>
<th class="api-index-title" scope="column"> </th>
</tr>
</thead>
<tbody>
<tr class="api-index-item">
<th scope="row" class="parameter api-index-item-title">Method</th>
<td class="type api-index-item-title"><?php echo wp_kses_post( $doc['method'] ); ?></td>
</tr>
<tr class="api-index-item">
<th scope="row" class="parameter api-index-item-title">URL</th>
<?php
$version = WPCOM_JSON_API__CURRENT_VERSION;
if ( !empty( $this->max_version ) ) {
$version = $this->max_version;
}
?>
<td class="type api-index-item-title">https://public-api.wordpress.com/rest/v<?php echo floatval( $version ); ?><?php echo wp_kses_post( $doc['path_labeled'] ); ?></td>
</tr>
<tr class="api-index-item">
<th scope="row" class="parameter api-index-item-title">Requires authentication?</th>
<?php
$requires_auth = $wpdb->get_row( $wpdb->prepare( "SELECT requires_authentication FROM rest_api_documentation WHERE `version` = %s AND `path` = %s AND `method` = %s LIMIT 1", $version, untrailingslashit( $doc['path_labeled'] ), $doc['method'] ) );
?>
<td class="type api-index-item-title"><?php echo ( true === (bool) $requires_auth->requires_authentication ? 'Yes' : 'No' ); ?></td>
</tr>
</tbody>
</table>
</section>
<?php
foreach ( array(
'path' => 'Method Parameters',
'query' => 'Query Parameters',
'body' => 'Request Parameters',
'response' => 'Response Parameters',
) as $doc_section_key => $label ) :
$doc_section = 'response' === $doc_section_key ? $doc['response']['body'] : $doc['request'][$doc_section_key];
if ( !$doc_section ) {
continue;
}
$param_label = strtolower( str_replace( ' ', '-', $label ) );
?>
<section class="<?php echo $param_label; ?>">
<h2 id="apidoc-<?php echo esc_attr( $doc_section_key ); ?>"><?php echo wp_kses_post( $label ); ?></h2>
<table class="api-doc api-doc-<?php echo $param_label; ?>-parameters api-doc-<?php echo strtolower( str_replace( ' ', '-', $doc['group'] ) ); ?>">
<thead>
<tr>
<th class="api-index-title" scope="column">Parameter</th>
<th class="api-index-title" scope="column">Type</th>
<th class="api-index-title" scope="column">Description</th>
</tr>
</thead>
<tbody>
<?php foreach ( $doc_section as $key => $item ) : ?>
<tr class="api-index-item">
<th scope="row" class="parameter api-index-item-title"><?php echo wp_kses_post( $key ); ?></th>
<td class="type api-index-item-title"><?php echo wp_kses_post( $item['type'] ); // @todo auto-link? ?></td>
<td class="description api-index-item-body"><?php
$this->generate_doc_description( $item['description'] );
?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</section>
<?php endforeach; ?>
<?php
if ( 'unset' !== $original_post ) {
$GLOBALS['post'] = $original_post;
}
}
function add_http_build_query_to_php_content_example( $matches ) {
$trimmed_match = ltrim( $matches[0] );
$pad = substr( $matches[0], 0, -1 * strlen( $trimmed_match ) );
$pad = ltrim( $pad, ' ' );
$return = ' ' . str_replace( "\n", "\n ", $matches[0] );
return " http_build_query({$return}{$pad})";
}
/**
* Recursively generates the <dl>'s to document item descriptions.
* Echoes HTML.
*/
function generate_doc_description( $item ) {
if ( is_array( $item ) ) : ?>
<dl>
<?php foreach ( $item as $description_key => $description_value ) : ?>
<dt><?php echo wp_kses_post( $description_key . ':' ); ?></dt>
<dd><?php $this->generate_doc_description( $description_value ); ?></dd>
<?php endforeach; ?>
</dl>
<?php
else :
echo wp_kses_post( $item );
endif;
}
/**
* Auto generates documentation based on description, method, path, path_labels, and query parameters.
* Echoes HTML.
*/
function generate_documentation() {
$format = str_replace( '%d', '%s', $this->path );
$path_labeled = $format;
if ( ! empty( $this->path_labels ) ) {
$path_labeled = vsprintf( $format, array_keys( $this->path_labels ) );
}
$boolean_arg = array( 'false', 'true' );
$naeloob_arg = array( 'true', 'false' );
$doc = array(
'description' => $this->description,
'method' => $this->method,
'path_format' => $this->path,
'path_labeled' => $path_labeled,
'group' => $this->group,
'request' => array(
'path' => array(),
'query' => array(),
'body' => array(),
),
'response' => array(
'body' => array(),
)
);
foreach ( array( 'path_labels' => 'path', 'query' => 'query', 'request_format' => 'body', 'response_format' => 'body' ) as $_property => $doc_item ) {
foreach ( (array) $this->$_property as $key => $description ) {
if ( is_array( $description ) ) {
$description_keys = array_keys( $description );
if ( $boolean_arg === $description_keys || $naeloob_arg === $description_keys ) {
$type = '(bool)';
} else {
$type = '(string)';
}
if ( 'response_format' !== $_property ) {
// hack - don't show "(default)" in response format
reset( $description );
$description_key = key( $description );
$description[$description_key] = "(default) {$description[$description_key]}";
}
} else {
$types = $this->parse_types( $description );
$type = array();
$default = '';
if ( 'none' == $types ) {
$types = array();
$types[]['type'] = 'none';
}
foreach ( $types as $type_array ) {
$type[] = $type_array['type'];
if ( isset( $type_array['default'] ) ) {
$default = $type_array['default'];
if ( 'string' === $type_array['type'] ) {
$default = "'$default'";
}
}
}
$type = '(' . join( '|', $type ) . ')';
$noop = ''; // skip an index in list below
list( $noop, $description ) = explode( ')', $description, 2 );
$description = trim( $description );
if ( $default ) {
$description .= " Default: $default.";
}
}
$item = compact( 'type', 'description' );
if ( 'response_format' === $_property ) {
$doc['response'][$doc_item][$key] = $item;
} else {
$doc['request'][$doc_item][$key] = $item;
}
}
}
return $doc;
}
function user_can_view_post( $post_id ) {
$post = get_post( $post_id );
if ( !$post || is_wp_error( $post ) ) {
return false;
}
if ( 'inherit' === $post->post_status ) {
$parent_post = get_post( $post->post_parent );
$post_status_obj = get_post_status_object( $parent_post->post_status );
} else {
$post_status_obj = get_post_status_object( $post->post_status );
}
if ( !$post_status_obj->public ) {
if ( is_user_logged_in() ) {
if ( $post_status_obj->protected ) {
if ( !current_user_can( 'edit_post', $post->ID ) ) {
return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
}
} elseif ( $post_status_obj->private ) {
if ( !current_user_can( 'read_post', $post->ID ) ) {
return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
}
} elseif ( 'trash' === $post->post_status ) {
if ( !current_user_can( 'edit_post', $post->ID ) ) {
return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
}
} elseif ( 'auto-draft' === $post->post_status ) {
//allow auto-drafts
} else {
return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
}
} else {
return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
}
}
if (
-1 == get_option( 'blog_public' ) &&
/**
* Filter access to a specific post.
*
* @module json-api
*
* @since 3.4.0
*
* @param bool current_user_can( 'read_post', $post->ID ) Can the current user access the post.
* @param WP_Post $post Post data.
*/