PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.8.3
Jetpack – WP Security, Backup, Speed, & Growth v7.8.3
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / class.json-api-endpoints.php
class.json-api-endpoints.php
2,100 lines 67.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 use Automattic\Jetpack\Connection\Client;
4
5 require_once dirname( __FILE__ ) . '/json-api-config.php';
6 require_once dirname( __FILE__ ) . '/sal/class.json-api-links.php';
7 require_once dirname( __FILE__ ) . '/sal/class.json-api-metadata.php';
8 require_once dirname( __FILE__ ) . '/sal/class.json-api-date.php';
9
10 // Endpoint
11 abstract class WPCOM_JSON_API_Endpoint {
12 // The API Object
13 public $api;
14
15 // The link-generating utility class
16 public $links;
17
18 public $pass_wpcom_user_details = false;
19
20 // One liner.
21 public $description;
22
23 // Object Grouping For Documentation (Users, Posts, Comments)
24 public $group;
25
26 // Stats extra value to bump
27 public $stat;
28
29 // HTTP Method
30 public $method = 'GET';
31
32 // Minimum version of the api for which to serve this endpoint
33 public $min_version = '0';
34
35 // Maximum version of the api for which to serve this endpoint
36 public $max_version = WPCOM_JSON_API__CURRENT_VERSION;
37
38 // Path at which to serve this endpoint: sprintf() format.
39 public $path = '';
40
41 // Identifiers to fill sprintf() formatted $path
42 public $path_labels = array();
43
44 // Accepted query parameters
45 public $query = array(
46 // Parameter name
47 'context' => array(
48 // Default value => description
49 'display' => 'Formats the output as HTML for display. Shortcodes are parsed, paragraph tags are added, etc..',
50 // Other possible values => description
51 'edit' => 'Formats the output for editing. Shortcodes are left unparsed, significant whitespace is kept, etc..',
52 ),
53 'http_envelope' => array(
54 'false' => '',
55 '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.',
56 ),
57 'pretty' => array(
58 'false' => '',
59 'true' => 'Output pretty JSON',
60 ),
61 'meta' => "(string) Optional. Loads data from the endpoints found in the 'meta' part of the response. Comma-separated list. Example: meta=site,likes",
62 'fields' => '(string) Optional. Returns specified fields only. Comma-separated list. Example: fields=ID,title',
63 // Parameter name => description (default value is empty)
64 'callback' => '(string) An optional JSONP callback function.',
65 );
66
67 // Response format
68 public $response_format = array();
69
70 // Request format
71 public $request_format = array();
72
73 // Is this endpoint still in testing phase? If so, not available to the public.
74 public $in_testing = false;
75
76 // Is this endpoint still allowed if the site in question is flagged?
77 public $allowed_if_flagged = false;
78
79 // Is this endpoint allowed if the site is red flagged?
80 public $allowed_if_red_flagged = false;
81
82 // Is this endpoint allowed if the site is deleted?
83 public $allowed_if_deleted = false;
84
85 /**
86 * @var string Version of the API
87 */
88 public $version = '';
89
90 /**
91 * @var string Example request to make
92 */
93 public $example_request = '';
94
95 /**
96 * @var string Example request data (for POST methods)
97 */
98 public $example_request_data = '';
99
100 /**
101 * @var string Example response from $example_request
102 */
103 public $example_response = '';
104
105 /**
106 * @var bool Set to true if the endpoint implements its own filtering instead of the standard `fields` query method
107 */
108 public $custom_fields_filtering = false;
109
110 /**
111 * @var bool Set to true if the endpoint accepts all cross origin requests. You probably should not set this flag.
112 */
113 public $allow_cross_origin_request = false;
114
115 /**
116 * @var bool Set to true if the endpoint can recieve unauthorized POST requests.
117 */
118 public $allow_unauthorized_request = false;
119
120 /**
121 * @var bool Set to true if the endpoint should accept site based (not user based) authentication.
122 */
123 public $allow_jetpack_site_auth = false;
124
125 /**
126 * @var bool Set to true if the endpoint should accept auth from an upload token.
127 */
128 public $allow_upload_token_auth = false;
129
130 function __construct( $args ) {
131 $defaults = array(
132 'in_testing' => false,
133 'allowed_if_flagged' => false,
134 'allowed_if_red_flagged' => false,
135 'allowed_if_deleted' => false,
136 'description' => '',
137 'group' => '',
138 'method' => 'GET',
139 'path' => '/',
140 'min_version' => '0',
141 'max_version' => WPCOM_JSON_API__CURRENT_VERSION,
142 'force' => '',
143 'deprecated' => false,
144 'new_version' => WPCOM_JSON_API__CURRENT_VERSION,
145 'jp_disabled' => false,
146 'path_labels' => array(),
147 'request_format' => array(),
148 'response_format' => array(),
149 'query_parameters' => array(),
150 'version' => 'v1',
151 'example_request' => '',
152 'example_request_data' => '',
153 'example_response' => '',
154 'required_scope' => '',
155 'pass_wpcom_user_details' => false,
156 'custom_fields_filtering' => false,
157 'allow_cross_origin_request' => false,
158 'allow_unauthorized_request' => false,
159 'allow_jetpack_site_auth' => false,
160 'allow_upload_token_auth' => false,
161 );
162
163 $args = wp_parse_args( $args, $defaults );
164
165 $this->in_testing = $args['in_testing'];
166
167 $this->allowed_if_flagged = $args['allowed_if_flagged'];
168 $this->allowed_if_red_flagged = $args['allowed_if_red_flagged'];
169 $this->allowed_if_deleted = $args['allowed_if_deleted'];
170
171 $this->description = $args['description'];
172 $this->group = $args['group'];
173 $this->stat = $args['stat'];
174 $this->force = $args['force'];
175 $this->jp_disabled = $args['jp_disabled'];
176
177 $this->method = $args['method'];
178 $this->path = $args['path'];
179 $this->path_labels = $args['path_labels'];
180 $this->min_version = $args['min_version'];
181 $this->max_version = $args['max_version'];
182 $this->deprecated = $args['deprecated'];
183 $this->new_version = $args['new_version'];
184
185 // Ensure max version is not less than min version
186 if ( version_compare( $this->min_version, $this->max_version, '>' ) ) {
187 $this->max_version = $this->min_version;
188 }
189
190 $this->pass_wpcom_user_details = $args['pass_wpcom_user_details'];
191 $this->custom_fields_filtering = (bool) $args['custom_fields_filtering'];
192
193 $this->allow_cross_origin_request = (bool) $args['allow_cross_origin_request'];
194 $this->allow_unauthorized_request = (bool) $args['allow_unauthorized_request'];
195 $this->allow_jetpack_site_auth = (bool) $args['allow_jetpack_site_auth'];
196 $this->allow_upload_token_auth = (bool) $args['allow_upload_token_auth'];
197
198 $this->version = $args['version'];
199
200 $this->required_scope = $args['required_scope'];
201
202 if ( $this->request_format ) {
203 $this->request_format = array_filter( array_merge( $this->request_format, $args['request_format'] ) );
204 } else {
205 $this->request_format = $args['request_format'];
206 }
207
208 if ( $this->response_format ) {
209 $this->response_format = array_filter( array_merge( $this->response_format, $args['response_format'] ) );
210 } else {
211 $this->response_format = $args['response_format'];
212 }
213
214 if ( false === $args['query_parameters'] ) {
215 $this->query = array();
216 } elseif ( is_array( $args['query_parameters'] ) ) {
217 $this->query = array_filter( array_merge( $this->query, $args['query_parameters'] ) );
218 }
219
220 $this->api = WPCOM_JSON_API::init(); // Auto-add to WPCOM_JSON_API
221 $this->links = WPCOM_JSON_API_Links::getInstance();
222
223 /** Example Request/Response */
224
225 // Examples for endpoint documentation request
226 $this->example_request = $args['example_request'];
227 $this->example_request_data = $args['example_request_data'];
228 $this->example_response = $args['example_response'];
229
230 $this->api->add( $this );
231 }
232
233 // Get all query args. Prefill with defaults
234 function query_args( $return_default_values = true, $cast_and_filter = true ) {
235 $args = array_intersect_key( $this->api->query, $this->query );
236
237 if ( ! $cast_and_filter ) {
238 return $args;
239 }
240
241 return $this->cast_and_filter( $args, $this->query, $return_default_values );
242 }
243
244 // Get POST body data
245 function input( $return_default_values = true, $cast_and_filter = true ) {
246 $input = trim( $this->api->post_body );
247 $content_type = $this->api->content_type;
248 if ( $content_type ) {
249 list ( $content_type ) = explode( ';', $content_type );
250 }
251 $content_type = trim( $content_type );
252 switch ( $content_type ) {
253 case 'application/json':
254 case 'application/x-javascript':
255 case 'text/javascript':
256 case 'text/x-javascript':
257 case 'text/x-json':
258 case 'text/json':
259 $return = json_decode( $input, true );
260
261 if ( function_exists( 'json_last_error' ) ) {
262 if ( JSON_ERROR_NONE !== json_last_error() ) { // phpcs:ignore PHPCompatibility
263 return null;
264 }
265 } else {
266 if ( is_null( $return ) && json_encode( null ) !== $input ) {
267 return null;
268 }
269 }
270
271 break;
272 case 'multipart/form-data':
273 $return = array_merge( stripslashes_deep( $_POST ), $_FILES );
274 break;
275 case 'application/x-www-form-urlencoded':
276 // attempt JSON first, since probably a curl command
277 $return = json_decode( $input, true );
278
279 if ( is_null( $return ) ) {
280 wp_parse_str( $input, $return );
281 }
282
283 break;
284 default:
285 wp_parse_str( $input, $return );
286 break;
287 }
288
289 if ( isset( $this->api->query['force'] )
290 && 'secure' === $this->api->query['force']
291 && isset( $return['secure_key'] ) ) {
292 $this->api->post_body = $this->get_secure_body( $return['secure_key'] );
293 $this->api->query['force'] = false;
294 return $this->input( $return_default_values, $cast_and_filter );
295 }
296
297 if ( $cast_and_filter ) {
298 $return = $this->cast_and_filter( $return, $this->request_format, $return_default_values );
299 }
300 return $return;
301 }
302
303
304 protected function get_secure_body( $secure_key ) {
305 $response = Client::wpcom_json_api_request_as_blog(
306 sprintf( '/sites/%d/secure-request', Jetpack_Options::get_option( 'id' ) ),
307 '1.1',
308 array( 'method' => 'POST' ),
309 array( 'secure_key' => $secure_key )
310 );
311 if ( 200 !== $response['response']['code'] ) {
312 return null;
313 }
314 return json_decode( $response['body'], true );
315 }
316
317 function cast_and_filter( $data, $documentation, $return_default_values = false, $for_output = false ) {
318 $return_as_object = false;
319 if ( is_object( $data ) ) {
320 // @todo this should probably be a deep copy if $data can ever have nested objects
321 $data = (array) $data;
322 $return_as_object = true;
323 } elseif ( ! is_array( $data ) ) {
324 return $data;
325 }
326
327 $boolean_arg = array( 'false', 'true' );
328 $naeloob_arg = array( 'true', 'false' );
329
330 $return = array();
331
332 foreach ( $documentation as $key => $description ) {
333 if ( is_array( $description ) ) {
334 // String or boolean array keys only
335 $whitelist = array_keys( $description );
336
337 if ( $whitelist === $boolean_arg || $whitelist === $naeloob_arg ) {
338 // Truthiness
339 if ( isset( $data[ $key ] ) ) {
340 $return[ $key ] = (bool) WPCOM_JSON_API::is_truthy( $data[ $key ] );
341 } elseif ( $return_default_values ) {
342 $return[ $key ] = $whitelist === $naeloob_arg; // Default to true for naeloob_arg and false for boolean_arg.
343 }
344 } elseif ( isset( $data[ $key ] ) && isset( $description[ $data[ $key ] ] ) ) {
345 // String Key
346 $return[ $key ] = (string) $data[ $key ];
347 } elseif ( $return_default_values ) {
348 // Default value
349 $return[ $key ] = (string) current( $whitelist );
350 }
351
352 continue;
353 }
354
355 $types = $this->parse_types( $description );
356 $type = array_shift( $types );
357
358 // Explicit default - string and int only for now. Always set these reguardless of $return_default_values
359 if ( isset( $type['default'] ) ) {
360 if ( ! isset( $data[ $key ] ) ) {
361 $data[ $key ] = $type['default'];
362 }
363 }
364
365 if ( ! isset( $data[ $key ] ) ) {
366 continue;
367 }
368
369 $this->cast_and_filter_item( $return, $type, $key, $data[ $key ], $types, $for_output );
370 }
371
372 if ( $return_as_object ) {
373 return (object) $return;
374 }
375
376 return $return;
377 }
378
379 /**
380 * Casts $value according to $type.
381 * Handles fallbacks for certain values of $type when $value is not that $type
382 * Currently, only handles fallback between string <-> array (two way), from string -> false (one way), and from object -> false (one way),
383 * and string -> object (one way)
384 *
385 * Handles "child types" - array:URL, object:category
386 * array:URL means an array of URLs
387 * object:category means a hash of categories
388 *
389 * Handles object typing - object>post means an object of type post
390 */
391 function cast_and_filter_item( &$return, $type, $key, $value, $types = array(), $for_output = false ) {
392 if ( is_string( $type ) ) {
393 $type = compact( 'type' );
394 }
395
396 switch ( $type['type'] ) {
397 case 'false':
398 $return[ $key ] = false;
399 break;
400 case 'url':
401 if ( is_object( $value ) && isset( $value->url ) && false !== strpos( $value->url, 'https://videos.files.wordpress.com/' ) ) {
402 $value = $value->url;
403 }
404 // Check for string since esc_url_raw() expects one.
405 if ( ! is_string( $value ) ) {
406 break;
407 }
408 $return[ $key ] = (string) esc_url_raw( $value );
409 break;
410 case 'string':
411 // Fallback string -> array, or for string -> object
412 if ( is_array( $value ) || is_object( $value ) ) {
413 if ( ! empty( $types[0] ) ) {
414 $next_type = array_shift( $types );
415 return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output );
416 }
417 }
418
419 // Fallback string -> false
420 if ( ! is_string( $value ) ) {
421 if ( ! empty( $types[0] ) && 'false' === $types[0]['type'] ) {
422 $next_type = array_shift( $types );
423 return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output );
424 }
425 }
426 $return[ $key ] = (string) $value;
427 break;
428 case 'html':
429 $return[ $key ] = (string) $value;
430 break;
431 case 'safehtml':
432 $return[ $key ] = wp_kses( (string) $value, wp_kses_allowed_html() );
433 break;
434 case 'zip':
435 case 'media':
436 if ( is_array( $value ) ) {
437 if ( isset( $value['name'] ) && is_array( $value['name'] ) ) {
438 // It's a $_FILES array
439 // Reformat into array of $_FILES items
440 $files = array();
441
442 foreach ( $value['name'] as $k => $v ) {
443 $files[ $k ] = array();
444 foreach ( array_keys( $value ) as $file_key ) {
445 $files[ $k ][ $file_key ] = $value[ $file_key ][ $k ];
446 }
447 }
448
449 foreach ( $files as $k => $file ) {
450 if ( ! isset( $file['tmp_name'] ) || ! is_string( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) {
451 unset( $files[ $k ] );
452 }
453 }
454 if ( $files ) {
455 $return[ $key ] = $files;
456 }
457 } elseif ( isset( $value['tmp_name'] ) && is_string( $value['tmp_name'] ) && is_uploaded_file( $value['tmp_name'] ) ) {
458 $return[ $key ] = $value;
459 }
460 }
461 break;
462 case 'array':
463 // Fallback array -> string
464 if ( is_string( $value ) ) {
465 if ( ! empty( $types[0] ) ) {
466 $next_type = array_shift( $types );
467 return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output );
468 }
469 }
470
471 if ( isset( $type['children'] ) ) {
472 $children = array();
473 foreach ( (array) $value as $k => $child ) {
474 $this->cast_and_filter_item( $children, $type['children'], $k, $child, array(), $for_output );
475 }
476 $return[ $key ] = (array) $children;
477 break;
478 }
479
480 $return[ $key ] = (array) $value;
481 break;
482 case 'iso 8601 datetime':
483 case 'datetime':
484 // (string)s
485 $dates = $this->parse_date( (string) $value );
486 if ( $for_output ) {
487 $return[ $key ] = $this->format_date( $dates[1], $dates[0] );
488 } else {
489 list( $return[ $key ], $return[ "{$key}_gmt" ] ) = $dates;
490 }
491 break;
492 case 'float':
493 $return[ $key ] = (float) $value;
494 break;
495 case 'int':
496 case 'integer':
497 $return[ $key ] = (int) $value;
498 break;
499 case 'bool':
500 case 'boolean':
501 $return[ $key ] = (bool) WPCOM_JSON_API::is_truthy( $value );
502 break;
503 case 'object':
504 // Fallback object -> false
505 if ( is_scalar( $value ) || is_null( $value ) ) {
506 if ( ! empty( $types[0] ) && 'false' === $types[0]['type'] ) {
507 return $this->cast_and_filter_item( $return, 'false', $key, $value, $types, $for_output );
508 }
509 }
510
511 if ( isset( $type['children'] ) ) {
512 $children = array();
513 foreach ( (array) $value as $k => $child ) {
514 $this->cast_and_filter_item( $children, $type['children'], $k, $child, array(), $for_output );
515 }
516 $return[ $key ] = (object) $children;
517 break;
518 }
519
520 if ( isset( $type['subtype'] ) ) {
521 return $this->cast_and_filter_item( $return, $type['subtype'], $key, $value, $types, $for_output );
522 }
523
524 $return[ $key ] = (object) $value;
525 break;
526 case 'post':
527 $return[ $key ] = (object) $this->cast_and_filter( $value, $this->post_object_format, false, $for_output );
528 break;
529 case 'comment':
530 $return[ $key ] = (object) $this->cast_and_filter( $value, $this->comment_object_format, false, $for_output );
531 break;
532 case 'tag':
533 case 'category':
534 $docs = array(
535 'ID' => '(int)',
536 'name' => '(string)',
537 'slug' => '(string)',
538 'description' => '(HTML)',
539 'post_count' => '(int)',
540 'feed_url' => '(string)',
541 'meta' => '(object)',
542 );
543 if ( 'category' === $type['type'] ) {
544 $docs['parent'] = '(int)';
545 }
546 $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
547 break;
548 case 'post_reference':
549 case 'comment_reference':
550 $docs = array(
551 'ID' => '(int)',
552 'type' => '(string)',
553 'title' => '(string)',
554 'link' => '(URL)',
555 );
556 $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
557 break;
558 case 'geo':
559 $docs = array(
560 'latitude' => '(float)',
561 'longitude' => '(float)',
562 'address' => '(string)',
563 );
564 $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
565 break;
566 case 'author':
567 $docs = array(
568 'ID' => '(int)',
569 'user_login' => '(string)',
570 'login' => '(string)',
571 'email' => '(string|false)',
572 'name' => '(string)',
573 'first_name' => '(string)',
574 'last_name' => '(string)',
575 'nice_name' => '(string)',
576 'URL' => '(URL)',
577 'avatar_URL' => '(URL)',
578 'profile_URL' => '(URL)',
579 'is_super_admin' => '(bool)',
580 'roles' => '(array:string)',
581 'ip_address' => '(string|false)',
582 );
583 $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
584 break;
585 case 'role':
586 $docs = array(
587 'name' => '(string)',
588 'display_name' => '(string)',
589 'capabilities' => '(object:boolean)',
590 );
591 $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output );
592 break;
593 case 'attachment':
594 $docs = array(
595 'ID' => '(int)',
596 'URL' => '(URL)',
597 'guid' => '(string)',
598 'mime_type' => '(string)',
599 'width' => '(int)',
600 'height' => '(int)',
601 'duration' => '(int)',
602 );
603 $return[ $key ] = (object) $this->cast_and_filter(
604 $value,
605 /**
606 * Filter the documentation returned for a post attachment.
607 *
608 * @module json-api
609 *
610 * @since 1.9.0
611 *
612 * @param array $docs Array of documentation about a post attachment.
613 */
614 apply_filters( 'wpcom_json_api_attachment_cast_and_filter', $docs ),
615 false,
616 $for_output
617 );
618 break;
619 case 'metadata':
620 $docs = array(
621 'id' => '(int)',
622 'key' => '(string)',
623 'value' => '(string|false|float|int|array|object)',
624 'previous_value' => '(string)',
625 'operation' => '(string)',
626 );
627 $return[ $key ] = (object) $this->cast_and_filter(
628 $value,
629 /** This filter is documented in class.json-api-endpoints.php */
630 apply_filters( 'wpcom_json_api_attachment_cast_and_filter', $docs ),
631 false,
632 $for_output
633 );
634 break;
635 case 'plugin':
636 $docs = array(
637 'id' => '(safehtml) The plugin\'s ID',
638 'slug' => '(safehtml) The plugin\'s Slug',
639 'active' => '(boolean) The plugin status.',
640 'update' => '(object) The plugin update info.',
641 'name' => '(safehtml) The name of the plugin.',
642 'plugin_url' => '(url) Link to the plugin\'s web site.',
643 'version' => '(safehtml) The plugin version number.',
644 'description' => '(safehtml) Description of what the plugin does and/or notes from the author',
645 'author' => '(safehtml) The plugin author\'s name',
646 'author_url' => '(url) The plugin author web site address',
647 'network' => '(boolean) Whether the plugin can only be activated network wide.',
648 'autoupdate' => '(boolean) Whether the plugin is auto updated',
649 'log' => '(array:safehtml) An array of update log strings.',
650 'action_links' => '(array) An array of action links that the plugin uses.',
651 );
652 $return[ $key ] = (object) $this->cast_and_filter(
653 $value,
654 /**
655 * Filter the documentation returned for a plugin.
656 *
657 * @module json-api
658 *
659 * @since 3.1.0
660 *
661 * @param array $docs Array of documentation about a plugin.
662 */
663 apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
664 false,
665 $for_output
666 );
667 break;
668 case 'plugin_v1_2':
669 $docs = class_exists( 'Jetpack_JSON_API_Get_Plugins_v1_2_Endpoint' )
670 ? Jetpack_JSON_API_Get_Plugins_v1_2_Endpoint::$_response_format
671 : Jetpack_JSON_API_Plugins_Endpoint::$_response_format_v1_2;
672 $return[ $key ] = (object) $this->cast_and_filter(
673 $value,
674 /**
675 * Filter the documentation returned for a plugin.
676 *
677 * @module json-api
678 *
679 * @since 3.1.0
680 *
681 * @param array $docs Array of documentation about a plugin.
682 */
683 apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
684 false,
685 $for_output
686 );
687 break;
688 case 'file_mod_capabilities':
689 $docs = array(
690 'reasons_modify_files_unavailable' => '(array) The reasons why files can\'t be modified',
691 'reasons_autoupdate_unavailable' => '(array) The reasons why autoupdates aren\'t allowed',
692 'modify_files' => '(boolean) true if files can be modified',
693 'autoupdate_files' => '(boolean) true if autoupdates are allowed',
694 );
695 $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
696 break;
697 case 'jetpackmodule':
698 $docs = array(
699 'id' => '(string) The module\'s ID',
700 'active' => '(boolean) The module\'s status.',
701 'name' => '(string) The module\'s name.',
702 'description' => '(safehtml) The module\'s description.',
703 'sort' => '(int) The module\'s display order.',
704 'introduced' => '(string) The Jetpack version when the module was introduced.',
705 'changed' => '(string) The Jetpack version when the module was changed.',
706 'free' => '(boolean) The module\'s Free or Paid status.',
707 'module_tags' => '(array) The module\'s tags.',
708 'override' => '(string) The module\'s override. Empty if no override, otherwise \'active\' or \'inactive\'',
709 );
710 $return[ $key ] = (object) $this->cast_and_filter(
711 $value,
712 /** This filter is documented in class.json-api-endpoints.php */
713 apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
714 false,
715 $for_output
716 );
717 break;
718 case 'sharing_button':
719 $docs = array(
720 'ID' => '(string)',
721 'name' => '(string)',
722 'URL' => '(string)',
723 'icon' => '(string)',
724 'enabled' => '(bool)',
725 'visibility' => '(string)',
726 );
727 $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
728 break;
729 case 'sharing_button_service':
730 $docs = array(
731 'ID' => '(string) The service identifier',
732 'name' => '(string) The service name',
733 'class_name' => '(string) Class name for custom style sharing button elements',
734 'genericon' => '(string) The Genericon unicode character for the custom style sharing button icon',
735 'preview_smart' => '(string) An HTML snippet of a rendered sharing button smart preview',
736 'preview_smart_js' => '(string) An HTML snippet of the page-wide initialization scripts used for rendering the sharing button smart preview',
737 );
738 $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
739 break;
740 case 'site_keyring':
741 $docs = array(
742 'keyring_id' => '(int) Keyring ID',
743 'service' => '(string) The service name',
744 'external_user_id' => '(string) External user id for the service',
745 );
746 $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
747 break;
748 case 'taxonomy':
749 $docs = array(
750 'name' => '(string) The taxonomy slug',
751 'label' => '(string) The taxonomy human-readable name',
752 'labels' => '(object) Mapping of labels for the taxonomy',
753 'description' => '(string) The taxonomy description',
754 'hierarchical' => '(bool) Whether the taxonomy is hierarchical',
755 'public' => '(bool) Whether the taxonomy is public',
756 'capabilities' => '(object) Mapping of current user capabilities for the taxonomy',
757 );
758 $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output );
759 break;
760
761 default:
762 $method_name = $type['type'] . '_docs';
763 if ( method_exists( 'WPCOM_JSON_API_Jetpack_Overrides', $method_name ) ) {
764 $docs = WPCOM_JSON_API_Jetpack_Overrides::$method_name();
765 }
766
767 if ( ! empty( $docs ) ) {
768 $return[ $key ] = (object) $this->cast_and_filter(
769 $value,
770 /** This filter is documented in class.json-api-endpoints.php */
771 apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ),
772 false,
773 $for_output
774 );
775 } else {
776 trigger_error( "Unknown API casting type {$type['type']}", E_USER_WARNING );
777 }
778 }
779 }
780
781 function parse_types( $text ) {
782 if ( ! preg_match( '#^\(([^)]+)\)#', ltrim( $text ), $matches ) ) {
783 return 'none';
784 }
785
786 $types = explode( '|', strtolower( $matches[1] ) );
787 $return = array();
788 foreach ( $types as $type ) {
789 foreach ( array(
790 ':' => 'children',
791 '>' => 'subtype',
792 '=' => 'default',
793 ) as $operator => $meaning ) {
794 if ( false !== strpos( $type, $operator ) ) {
795 $item = explode( $operator, $type, 2 );
796 $return[] = array(
797 'type' => $item[0],
798 $meaning => $item[1],
799 );
800 continue 2;
801 }
802 }
803 $return[] = compact( 'type' );
804 }
805
806 return $return;
807 }
808
809 /**
810 * Checks if the endpoint is publicly displayable
811 */
812 function is_publicly_documentable() {
813 return '__do_not_document' !== $this->group && true !== $this->in_testing;
814 }
815
816 /**
817 * Auto generates documentation based on description, method, path, path_labels, and query parameters.
818 * Echoes HTML.
819 */
820 function document( $show_description = true ) {
821 global $wpdb;
822 $original_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : 'unset';
823 unset( $GLOBALS['post'] );
824
825 $doc = $this->generate_documentation();
826
827 if ( $show_description ) :
828 ?>
829 <caption>
830 <h1><?php echo wp_kses_post( $doc['method'] ); ?> <?php echo wp_kses_post( $doc['path_labeled'] ); ?></h1>
831 <p><?php echo wp_kses_post( $doc['description'] ); ?></p>
832 </caption>
833
834 <?php endif; ?>
835
836 <?php if ( true === $this->deprecated ) { ?>
837 <p><strong>This endpoint is deprecated in favor of version <?php echo floatval( $this->new_version ); ?></strong></p>
838 <?php } ?>
839
840 <section class="resource-info">
841 <h2 id="apidoc-resource-info">Resource Information</h2>
842
843 <table class="api-doc api-doc-resource-parameters api-doc-resource">
844
845 <thead>
846 <tr>
847 <th class="api-index-title" scope="column">&nbsp;</th>
848 <th class="api-index-title" scope="column">&nbsp;</th>
849 </tr>
850 </thead>
851 <tbody>
852
853 <tr class="api-index-item">
854 <th scope="row" class="parameter api-index-item-title">Method</th>
855 <td class="type api-index-item-title"><?php echo wp_kses_post( $doc['method'] ); ?></td>
856 </tr>
857
858 <tr class="api-index-item">
859 <th scope="row" class="parameter api-index-item-title">URL</th>
860 <?php
861 $version = WPCOM_JSON_API__CURRENT_VERSION;
862 if ( ! empty( $this->max_version ) ) {
863 $version = $this->max_version;
864 }
865 ?>
866 <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>
867 </tr>
868
869 <tr class="api-index-item">
870 <th scope="row" class="parameter api-index-item-title">Requires authentication?</th>
871 <?php
872 $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'] ) );
873 ?>
874 <td class="type api-index-item-title"><?php echo ( true === (bool) $requires_auth->requires_authentication ? 'Yes' : 'No' ); ?></td>
875 </tr>
876
877 </tbody>
878 </table>
879
880 </section>
881
882 <?php
883
884 foreach ( array(
885 'path' => 'Method Parameters',
886 'query' => 'Query Parameters',
887 'body' => 'Request Parameters',
888 'response' => 'Response Parameters',
889 ) as $doc_section_key => $label ) :
890 $doc_section = 'response' === $doc_section_key ? $doc['response']['body'] : $doc['request'][ $doc_section_key ];
891 if ( ! $doc_section ) {
892 continue;
893 }
894
895 $param_label = strtolower( str_replace( ' ', '-', $label ) );
896 ?>
897
898 <section class="<?php echo $param_label; ?>">
899
900 <h2 id="apidoc-<?php echo esc_attr( $doc_section_key ); ?>"><?php echo wp_kses_post( $label ); ?></h2>
901
902 <table class="api-doc api-doc-<?php echo $param_label; ?>-parameters api-doc-<?php echo strtolower( str_replace( ' ', '-', $doc['group'] ) ); ?>">
903
904 <thead>
905 <tr>
906 <th class="api-index-title" scope="column">Parameter</th>
907 <th class="api-index-title" scope="column">Type</th>
908 <th class="api-index-title" scope="column">Description</th>
909 </tr>
910 </thead>
911 <tbody>
912
913 <?php foreach ( $doc_section as $key => $item ) : ?>
914
915 <tr class="api-index-item">
916 <th scope="row" class="parameter api-index-item-title"><?php echo wp_kses_post( $key ); ?></th>
917 <td class="type api-index-item-title"><?php echo wp_kses_post( $item['type'] ); // @todo auto-link? ?></td>
918 <td class="description api-index-item-body">
919 <?php
920
921 $this->generate_doc_description( $item['description'] );
922
923 ?>
924 </td>
925 </tr>
926
927 <?php endforeach; ?>
928 </tbody>
929 </table>
930 </section>
931 <?php endforeach; ?>
932
933 <?php
934 if ( 'unset' !== $original_post ) {
935 $GLOBALS['post'] = $original_post;
936 }
937 }
938
939 function add_http_build_query_to_php_content_example( $matches ) {
940 $trimmed_match = ltrim( $matches[0] );
941 $pad = substr( $matches[0], 0, -1 * strlen( $trimmed_match ) );
942 $pad = ltrim( $pad, ' ' );
943 $return = ' ' . str_replace( "\n", "\n ", $matches[0] );
944 return " http_build_query({$return}{$pad})";
945 }
946
947 /**
948 * Recursively generates the <dl>'s to document item descriptions.
949 * Echoes HTML.
950 */
951 function generate_doc_description( $item ) {
952 if ( is_array( $item ) ) :
953 ?>
954
955 <dl>
956 <?php foreach ( $item as $description_key => $description_value ) : ?>
957
958 <dt><?php echo wp_kses_post( $description_key . ':' ); ?></dt>
959 <dd><?php $this->generate_doc_description( $description_value ); ?></dd>
960
961 <?php endforeach; ?>
962
963 </dl>
964
965 <?php
966 else :
967 echo wp_kses_post( $item );
968 endif;
969 }
970
971 /**
972 * Auto generates documentation based on description, method, path, path_labels, and query parameters.
973 * Echoes HTML.
974 */
975 function generate_documentation() {
976 $format = str_replace( '%d', '%s', $this->path );
977 $path_labeled = $format;
978 if ( ! empty( $this->path_labels ) ) {
979 $path_labeled = vsprintf( $format, array_keys( $this->path_labels ) );
980 }
981 $boolean_arg = array( 'false', 'true' );
982 $naeloob_arg = array( 'true', 'false' );
983
984 $doc = array(
985 'description' => $this->description,
986 'method' => $this->method,
987 'path_format' => $this->path,
988 'path_labeled' => $path_labeled,
989 'group' => $this->group,
990 'request' => array(
991 'path' => array(),
992 'query' => array(),
993 'body' => array(),
994 ),
995 'response' => array(
996 'body' => array(),
997 ),
998 );
999
1000 foreach ( array(
1001 'path_labels' => 'path',
1002 'query' => 'query',
1003 'request_format' => 'body',
1004 'response_format' => 'body',
1005 ) as $_property => $doc_item ) {
1006 foreach ( (array) $this->$_property as $key => $description ) {
1007 if ( is_array( $description ) ) {
1008 $description_keys = array_keys( $description );
1009 if ( $boolean_arg === $description_keys || $naeloob_arg === $description_keys ) {
1010 $type = '(bool)';
1011 } else {
1012 $type = '(string)';
1013 }
1014
1015 if ( 'response_format' !== $_property ) {
1016 // hack - don't show "(default)" in response format
1017 reset( $description );
1018 $description_key = key( $description );
1019 $description[ $description_key ] = "(default) {$description[$description_key]}";
1020 }
1021 } else {
1022 $types = $this->parse_types( $description );
1023 $type = array();
1024 $default = '';
1025
1026 if ( 'none' == $types ) {
1027 $types = array();
1028 $types[]['type'] = 'none';
1029 }
1030
1031 foreach ( $types as $type_array ) {
1032 $type[] = $type_array['type'];
1033 if ( isset( $type_array['default'] ) ) {
1034 $default = $type_array['default'];
1035 if ( 'string' === $type_array['type'] ) {
1036 $default = "'$default'";
1037 }
1038 }
1039 }
1040 $type = '(' . join( '|', $type ) . ')';
1041 $noop = ''; // skip an index in list below
1042 list( $noop, $description ) = explode( ')', $description, 2 );
1043 $description = trim( $description );
1044 if ( $default ) {
1045 $description .= " Default: $default.";
1046 }
1047 }
1048
1049 $item = compact( 'type', 'description' );
1050
1051 if ( 'response_format' === $_property ) {
1052 $doc['response'][ $doc_item ][ $key ] = $item;
1053 } else {
1054 $doc['request'][ $doc_item ][ $key ] = $item;
1055 }
1056 }
1057 }
1058
1059 return $doc;
1060 }
1061
1062 function user_can_view_post( $post_id ) {
1063 $post = get_post( $post_id );
1064 if ( ! $post || is_wp_error( $post ) ) {
1065 return false;
1066 }
1067
1068 if ( 'inherit' === $post->post_status ) {
1069 $parent_post = get_post( $post->post_parent );
1070 $post_status_obj = get_post_status_object( $parent_post->post_status );
1071 } else {
1072 $post_status_obj = get_post_status_object( $post->post_status );
1073 }
1074
1075 if ( ! $post_status_obj->public ) {
1076 if ( is_user_logged_in() ) {
1077 if ( $post_status_obj->protected ) {
1078 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1079 return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
1080 }
1081 } elseif ( $post_status_obj->private ) {
1082 if ( ! current_user_can( 'read_post', $post->ID ) ) {
1083 return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
1084 }
1085 } elseif ( in_array( $post->post_status, array( 'inherit', 'trash' ) ) ) {
1086 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1087 return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
1088 }
1089 } elseif ( 'auto-draft' === $post->post_status ) {
1090 // allow auto-drafts
1091 } else {
1092 return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
1093 }
1094 } else {
1095 return new WP_Error( 'unauthorized', 'User cannot view post', 403 );
1096 }
1097 }
1098
1099 if (
1100 -1 == get_option( 'blog_public' ) &&
1101 /**
1102 * Filter access to a specific post.
1103 *
1104 * @module json-api
1105 *
1106 * @since 3.4.0
1107 *
1108 * @param bool current_user_can( 'read_post', $post->ID ) Can the current user access the post.
1109 * @param WP_Post $post Post data.
1110 */
1111 ! apply_filters(
1112 'wpcom_json_api_user_can_view_post',
1113 current_user_can( 'read_post', $post->ID ),
1114 $post
1115 )
1116 ) {
1117 return new WP_Error(
1118 'unauthorized',
1119 'User cannot view post',
1120 array(
1121 'status_code' => 403,
1122 'error' => 'private_blog',
1123 )
1124 );
1125 }
1126
1127 if ( strlen( $post->post_password ) && ! current_user_can( 'edit_post', $post->ID ) ) {
1128 return new WP_Error(
1129 'unauthorized',
1130 'User cannot view password protected post',
1131 array(
1132 'status_code' => 403,
1133 'error' => 'password_protected',
1134 )
1135 );
1136 }
1137
1138 return true;
1139 }
1140
1141 /**
1142 * Returns author object.
1143 *
1144 * @param object $author user ID, user row, WP_User object, comment row, post row
1145 * @param bool $show_email_and_ip output the author's email address and IP address?
1146 *
1147 * @return object
1148 */
1149 function get_author( $author, $show_email_and_ip = false ) {
1150 $ip_address = isset( $author->comment_author_IP ) ? $author->comment_author_IP : '';
1151
1152 if ( isset( $author->comment_author_email ) ) {
1153 $ID = 0;
1154 $login = '';
1155 $email = $author->comment_author_email;
1156 $name = $author->comment_author;
1157 $first_name = '';
1158 $last_name = '';
1159 $URL = $author->comment_author_url;
1160 $avatar_URL = $this->api->get_avatar_url( $author );
1161 $profile_URL = 'https://en.gravatar.com/' . md5( strtolower( trim( $email ) ) );
1162 $nice = '';
1163 $site_id = -1;
1164
1165 // Comment author URLs and Emails are sent through wp_kses() on save, which replaces "&" with "&amp;"
1166 // "&" is the only email/URL character altered by wp_kses()
1167 foreach ( array( 'email', 'URL' ) as $field ) {
1168 $$field = str_replace( '&amp;', '&', $$field );
1169 }
1170 } else {
1171 if ( isset( $author->user_id ) && $author->user_id ) {
1172 $author = $author->user_id;
1173 } elseif ( isset( $author->user_email ) ) {
1174 $author = $author->ID;
1175 } elseif ( isset( $author->post_author ) ) {
1176 // then $author is a Post Object.
1177 if ( 0 == $author->post_author ) {
1178 return null;
1179 }
1180 /**
1181 * Filter whether the current site is a Jetpack site.
1182 *
1183 * @module json-api
1184 *
1185 * @since 3.3.0
1186 *
1187 * @param bool false Is the current site a Jetpack site. Default to false.
1188 * @param int get_current_blog_id() Blog ID.
1189 */
1190 $is_jetpack = true === apply_filters( 'is_jetpack_site', false, get_current_blog_id() );
1191 $post_id = $author->ID;
1192 if ( $is_jetpack && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
1193 $ID = get_post_meta( $post_id, '_jetpack_post_author_external_id', true );
1194 $email = get_post_meta( $post_id, '_jetpack_author_email', true );
1195 $login = '';
1196 $name = get_post_meta( $post_id, '_jetpack_author', true );
1197 $first_name = '';
1198 $last_name = '';
1199 $URL = '';
1200 $nice = '';
1201 } else {
1202 $author = $author->post_author;
1203 }
1204 }
1205
1206 if ( ! isset( $ID ) ) {
1207 $user = get_user_by( 'id', $author );
1208 if ( ! $user || is_wp_error( $user ) ) {
1209 trigger_error( 'Unknown user', E_USER_WARNING );
1210
1211 return null;
1212 }
1213 $ID = $user->ID;
1214 $email = $user->user_email;
1215 $login = $user->user_login;
1216 $name = $user->display_name;
1217 $first_name = $user->first_name;
1218 $last_name = $user->last_name;
1219 $URL = $user->user_url;
1220 $nice = $user->user_nicename;
1221 }
1222 if ( defined( 'IS_WPCOM' ) && IS_WPCOM && ! $is_jetpack ) {
1223 $active_blog = get_active_blog_for_user( $ID );
1224 $site_id = $active_blog->blog_id;
1225 if ( $site_id > -1 ) {
1226 $site_visible = (
1227 -1 != $active_blog->public ||
1228 is_private_blog_user( $site_id, get_current_user_id() )
1229 );
1230 }
1231 $profile_URL = "https://en.gravatar.com/{$login}";
1232 } else {
1233 $profile_URL = 'https://en.gravatar.com/' . md5( strtolower( trim( $email ) ) );
1234 $site_id = -1;
1235 }
1236
1237 $avatar_URL = $this->api->get_avatar_url( $email );
1238 }
1239
1240 if ( $show_email_and_ip ) {
1241 $email = (string) $email;
1242 $ip_address = (string) $ip_address;
1243 } else {
1244 $email = false;
1245 $ip_address = false;
1246 }
1247
1248 $author = array(
1249 'ID' => (int) $ID,
1250 'login' => (string) $login,
1251 'email' => $email, // (string|bool)
1252 'name' => (string) $name,
1253 'first_name' => (string) $first_name,
1254 'last_name' => (string) $last_name,
1255 'nice_name' => (string) $nice,
1256 'URL' => (string) esc_url_raw( $URL ),
1257 'avatar_URL' => (string) esc_url_raw( $avatar_URL ),
1258 'profile_URL' => (string) esc_url_raw( $profile_URL ),
1259 'ip_address' => $ip_address, // (string|bool)
1260 );
1261
1262 if ( $site_id > -1 ) {
1263 $author['site_ID'] = (int) $site_id;
1264 $author['site_visible'] = $site_visible;
1265 }
1266
1267 return (object) $author;
1268 }
1269
1270 function get_media_item( $media_id ) {
1271 $media_item = get_post( $media_id );
1272
1273 if ( ! $media_item || is_wp_error( $media_item ) ) {
1274 return new WP_Error( 'unknown_media', 'Unknown Media', 404 );
1275 }
1276
1277 $response = array(
1278 'id' => strval( $media_item->ID ),
1279 'date' => (string) $this->format_date( $media_item->post_date_gmt, $media_item->post_date ),
1280 'parent' => $media_item->post_parent,
1281 'link' => wp_get_attachment_url( $media_item->ID ),
1282 'title' => $media_item->post_title,
1283 'caption' => $media_item->post_excerpt,
1284 'description' => $media_item->post_content,
1285 'metadata' => wp_get_attachment_metadata( $media_item->ID ),
1286 );
1287
1288 if ( defined( 'IS_WPCOM' ) && IS_WPCOM && is_array( $response['metadata'] ) && ! empty( $response['metadata']['file'] ) ) {
1289 remove_filter( '_wp_relative_upload_path', 'wpcom_wp_relative_upload_path', 10 );
1290 $response['metadata']['file'] = _wp_relative_upload_path( $response['metadata']['file'] );
1291 add_filter( '_wp_relative_upload_path', 'wpcom_wp_relative_upload_path', 10, 2 );
1292 }
1293
1294 $response['meta'] = (object) array(
1295 'links' => (object) array(
1296 'self' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_id ),
1297 'help' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_id, 'help' ),
1298 'site' => (string) $this->links->get_site_link( $this->api->get_blog_id_for_output() ),
1299 ),
1300 );
1301
1302 return (object) $response;
1303 }
1304
1305 function get_media_item_v1_1( $media_id, $media_item = null, $file = null ) {
1306
1307 if ( ! $media_item ) {
1308 $media_item = get_post( $media_id );
1309 }
1310
1311 if ( ! $media_item || is_wp_error( $media_item ) ) {
1312 return new WP_Error( 'unknown_media', 'Unknown Media', 404 );
1313 }
1314
1315 $attachment_file = get_attached_file( $media_item->ID );
1316
1317 $file = basename( $attachment_file ? $attachment_file : $file );
1318 $file_info = pathinfo( $file );
1319 $ext = isset( $file_info['extension'] ) ? $file_info['extension'] : null;
1320
1321 $response = array(
1322 'ID' => $media_item->ID,
1323 'URL' => wp_get_attachment_url( $media_item->ID ),
1324 'guid' => $media_item->guid,
1325 'date' => (string) $this->format_date( $media_item->post_date_gmt, $media_item->post_date ),
1326 'post_ID' => $media_item->post_parent,
1327 'author_ID' => (int) $media_item->post_author,
1328 'file' => $file,
1329 'mime_type' => $media_item->post_mime_type,
1330 'extension' => $ext,
1331 'title' => $media_item->post_title,
1332 'caption' => $media_item->post_excerpt,
1333 'description' => $media_item->post_content,
1334 'alt' => get_post_meta( $media_item->ID, '_wp_attachment_image_alt', true ),
1335 'icon' => wp_mime_type_icon( $media_item->ID ),
1336 'thumbnails' => array(),
1337 );
1338
1339 if ( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif' ) ) ) {
1340 $metadata = wp_get_attachment_metadata( $media_item->ID );
1341 if ( isset( $metadata['height'], $metadata['width'] ) ) {
1342 $response['height'] = $metadata['height'];
1343 $response['width'] = $metadata['width'];
1344 }
1345
1346 if ( isset( $metadata['sizes'] ) ) {
1347 /**
1348 * Filter the thumbnail sizes available for each attachment ID.
1349 *
1350 * @module json-api
1351 *
1352 * @since 3.9.0
1353 *
1354 * @param array $metadata['sizes'] Array of thumbnail sizes available for a given attachment ID.
1355 * @param string $media_id Attachment ID.
1356 */
1357 $sizes = apply_filters( 'rest_api_thumbnail_sizes', $metadata['sizes'], $media_item->ID );
1358 if ( is_array( $sizes ) ) {
1359 foreach ( $sizes as $size => $size_details ) {
1360 $response['thumbnails'][ $size ] = dirname( $response['URL'] ) . '/' . $size_details['file'];
1361 }
1362 /**
1363 * Filter the thumbnail URLs for attachment files.
1364 *
1365 * @module json-api
1366 *
1367 * @since 7.1.0
1368 *
1369 * @param array $metadata['sizes'] Array with thumbnail sizes as keys and URLs as values.
1370 */
1371 $response['thumbnails'] = apply_filters( 'rest_api_thumbnail_size_urls', $response['thumbnails'] );
1372 }
1373 }
1374
1375 if ( isset( $metadata['image_meta'] ) ) {
1376 $response['exif'] = $metadata['image_meta'];
1377 }
1378 }
1379
1380 if ( in_array( $ext, array( 'mp3', 'm4a', 'wav', 'ogg' ) ) ) {
1381 $metadata = wp_get_attachment_metadata( $media_item->ID );
1382 $response['length'] = $metadata['length'];
1383 $response['exif'] = $metadata;
1384 }
1385
1386 $is_video = false;
1387
1388 if (
1389 in_array( $ext, array( 'ogv', 'mp4', 'mov', 'wmv', 'avi', 'mpg', '3gp', '3g2', 'm4v' ) )
1390 ||
1391 $response['mime_type'] === 'video/videopress'
1392 ) {
1393 $is_video = true;
1394 }
1395
1396 if ( $is_video ) {
1397 $metadata = wp_get_attachment_metadata( $media_item->ID );
1398
1399 if ( isset( $metadata['height'], $metadata['width'] ) ) {
1400 $response['height'] = $metadata['height'];
1401 $response['width'] = $metadata['width'];
1402 }
1403
1404 if ( isset( $metadata['length'] ) ) {
1405 $response['length'] = $metadata['length'];
1406 }
1407
1408 // add VideoPress info
1409 if ( function_exists( 'video_get_info_by_blogpostid' ) ) {
1410 $info = video_get_info_by_blogpostid( $this->api->get_blog_id_for_output(), $media_item->ID );
1411
1412 // If we failed to get VideoPress info, but it exists in the meta data (for some reason)
1413 // then let's use that.
1414 if ( false === $info && isset( $metadata['videopress'] ) ) {
1415 $info = (object) $metadata['videopress'];
1416 }
1417
1418 // Thumbnails
1419 if ( function_exists( 'video_format_done' ) && function_exists( 'video_image_url_by_guid' ) ) {
1420 $response['thumbnails'] = array(
1421 'fmt_hd' => '',
1422 'fmt_dvd' => '',
1423 'fmt_std' => '',
1424 );
1425 foreach ( $response['thumbnails'] as $size => $thumbnail_url ) {
1426 if ( video_format_done( $info, $size ) ) {
1427 $response['thumbnails'][ $size ] = video_image_url_by_guid( $info->guid, $size );
1428 } else {
1429 unset( $response['thumbnails'][ $size ] );
1430 }
1431 }
1432 }
1433
1434 // If we didn't get VideoPress information (for some reason) then let's
1435 // not try and include it in the response.
1436 if ( isset( $info->guid ) ) {
1437 $response['videopress_guid'] = $info->guid;
1438 $response['videopress_processing_done'] = true;
1439 if ( '0000-00-00 00:00:00' === $info->finish_date_gmt ) {
1440 $response['videopress_processing_done'] = false;
1441 }
1442 }
1443 }
1444 }
1445
1446 $response['thumbnails'] = (object) $response['thumbnails'];
1447
1448 $response['meta'] = (object) array(
1449 'links' => (object) array(
1450 'self' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_item->ID ),
1451 'help' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_item->ID, 'help' ),
1452 'site' => (string) $this->links->get_site_link( $this->api->get_blog_id_for_output() ),
1453 ),
1454 );
1455
1456 // add VideoPress link to the meta
1457 if ( isset( $response['videopress_guid'] ) ) {
1458 if ( function_exists( 'video_get_info_by_blogpostid' ) ) {
1459 $response['meta']->links->videopress = (string) $this->links->get_link( '/videos/%s', $response['videopress_guid'], '' );
1460 }
1461 }
1462
1463 if ( $media_item->post_parent > 0 ) {
1464 $response['meta']->links->parent = (string) $this->links->get_post_link( $this->api->get_blog_id_for_output(), $media_item->post_parent );
1465 }
1466
1467 return (object) $response;
1468 }
1469
1470 function get_taxonomy( $taxonomy_id, $taxonomy_type, $context ) {
1471
1472 $taxonomy = get_term_by( 'slug', $taxonomy_id, $taxonomy_type );
1473 // keep updating this function
1474 if ( ! $taxonomy || is_wp_error( $taxonomy ) ) {
1475 return new WP_Error( 'unknown_taxonomy', 'Unknown taxonomy', 404 );
1476 }
1477
1478 return $this->format_taxonomy( $taxonomy, $taxonomy_type, $context );
1479 }
1480
1481 function format_taxonomy( $taxonomy, $taxonomy_type, $context ) {
1482 // Permissions
1483 switch ( $context ) {
1484 case 'edit':
1485 $tax = get_taxonomy( $taxonomy_type );
1486 if ( ! current_user_can( $tax->cap->edit_terms ) ) {
1487 return new WP_Error( 'unauthorized', 'User cannot edit taxonomy', 403 );
1488 }
1489 break;
1490 case 'display':
1491 if ( -1 == get_option( 'blog_public' ) && ! current_user_can( 'read' ) ) {
1492 return new WP_Error( 'unauthorized', 'User cannot view taxonomy', 403 );
1493 }
1494 break;
1495 default:
1496 return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 );
1497 }
1498
1499 $response = array();
1500 $response['ID'] = (int) $taxonomy->term_id;
1501 $response['name'] = (string) $taxonomy->name;
1502 $response['slug'] = (string) $taxonomy->slug;
1503 $response['description'] = (string) $taxonomy->description;
1504 $response['post_count'] = (int) $taxonomy->count;
1505 $response['feed_url'] = get_term_feed_link( $taxonomy->term_id, $taxonomy_type );
1506
1507 if ( is_taxonomy_hierarchical( $taxonomy_type ) ) {
1508 $response['parent'] = (int) $taxonomy->parent;
1509 }
1510
1511 $response['meta'] = (object) array(
1512 'links' => (object) array(
1513 'self' => (string) $this->links->get_taxonomy_link( $this->api->get_blog_id_for_output(), $taxonomy->slug, $taxonomy_type ),
1514 'help' => (string) $this->links->get_taxonomy_link( $this->api->get_blog_id_for_output(), $taxonomy->slug, $taxonomy_type, 'help' ),
1515 'site' => (string) $this->links->get_site_link( $this->api->get_blog_id_for_output() ),
1516 ),
1517 );
1518
1519 return (object) $response;
1520 }
1521
1522 /**
1523 * Returns ISO 8601 formatted datetime: 2011-12-08T01:15:36-08:00
1524 *
1525 * @param $date_gmt (string) GMT datetime string.
1526 * @param $date (string) Optional. Used to calculate the offset from GMT.
1527 *
1528 * @return string
1529 */
1530 function format_date( $date_gmt, $date = null ) {
1531 return WPCOM_JSON_API_Date::format_date( $date_gmt, $date );
1532 }
1533
1534 /**
1535 * Parses a date string and returns the local and GMT representations
1536 * of that date & time in 'YYYY-MM-DD HH:MM:SS' format without
1537 * timezones or offsets. If the parsed datetime was not localized to a
1538 * particular timezone or offset we will assume it was given in GMT
1539 * relative to now and will convert it to local time using either the
1540 * timezone set in the options table for the blog or the GMT offset.
1541 *
1542 * @param datetime string
1543 *
1544 * @return array( $local_time_string, $gmt_time_string )
1545 */
1546 function parse_date( $date_string ) {
1547 $date_string_info = date_parse( $date_string );
1548 if ( is_array( $date_string_info ) && 0 === $date_string_info['error_count'] ) {
1549 // Check if it's already localized. Can't just check is_localtime because date_parse('oppossum') returns true; WTF, PHP.
1550 if ( isset( $date_string_info['zone'] ) && true === $date_string_info['is_localtime'] ) {
1551 $dt_local = clone $dt_utc = new DateTime( $date_string );
1552 $dt_utc->setTimezone( new DateTimeZone( 'UTC' ) );
1553 return array(
1554 (string) $dt_local->format( 'Y-m-d H:i:s' ),
1555 (string) $dt_utc->format( 'Y-m-d H:i:s' ),
1556 );
1557 }
1558
1559 // It's parseable but no TZ info so assume UTC
1560 $dt_local = clone $dt_utc = new DateTime( $date_string, new DateTimeZone( 'UTC' ) );
1561 } else {
1562 // Could not parse time, use now in UTC
1563 $dt_local = clone $dt_utc = new DateTime( 'now', new DateTimeZone( 'UTC' ) );
1564 }
1565
1566 // First try to use timezone as it's daylight savings aware.
1567 $timezone_string = get_option( 'timezone_string' );
1568 if ( $timezone_string ) {
1569 $tz = timezone_open( $timezone_string );
1570 if ( $tz ) {
1571 $dt_local->setTimezone( $tz );
1572 return array(
1573 (string) $dt_local->format( 'Y-m-d H:i:s' ),
1574 (string) $dt_utc->format( 'Y-m-d H:i:s' ),
1575 );
1576 }
1577 }
1578
1579 // Fallback to GMT offset (in hours)
1580 // NOTE: TZ of $dt_local is still UTC, we simply modified the timestamp with an offset.
1581 $gmt_offset_seconds = intval( get_option( 'gmt_offset' ) * 3600 );
1582 $dt_local->modify( "+{$gmt_offset_seconds} seconds" );
1583 return array(
1584 (string) $dt_local->format( 'Y-m-d H:i:s' ),
1585 (string) $dt_utc->format( 'Y-m-d H:i:s' ),
1586 );
1587 }
1588
1589 // Load the functions.php file for the current theme to get its post formats, CPTs, etc.
1590 function load_theme_functions() {
1591 // bail if we've done this already (can happen when calling /batch endpoint)
1592 if ( defined( 'REST_API_THEME_FUNCTIONS_LOADED' ) ) {
1593 return;
1594 }
1595
1596 // VIP context loading is handled elsewhere, so bail to prevent
1597 // duplicate loading. See `switch_to_blog_and_validate_user()`
1598 if ( function_exists( 'wpcom_is_vip' ) && wpcom_is_vip() ) {
1599 return;
1600 }
1601
1602 define( 'REST_API_THEME_FUNCTIONS_LOADED', true );
1603
1604 // the theme info we care about is found either within functions.php or one of the jetpack files.
1605 $function_files = array( '/functions.php', '/inc/jetpack.compat.php', '/inc/jetpack.php', '/includes/jetpack.compat.php' );
1606
1607 $copy_dirs = array( get_template_directory() );
1608
1609 // Is this a child theme? Load the child theme's functions file.
1610 if ( get_stylesheet_directory() !== get_template_directory() && wpcom_is_child_theme() ) {
1611 foreach ( $function_files as $function_file ) {
1612 if ( file_exists( get_stylesheet_directory() . $function_file ) ) {
1613 require_once get_stylesheet_directory() . $function_file;
1614 }
1615 }
1616 $copy_dirs[] = get_stylesheet_directory();
1617 }
1618
1619 foreach ( $function_files as $function_file ) {
1620 if ( file_exists( get_template_directory() . $function_file ) ) {
1621 require_once get_template_directory() . $function_file;
1622 }
1623 }
1624
1625 // add inc/wpcom.php and/or includes/wpcom.php
1626 wpcom_load_theme_compat_file();
1627
1628 // Enable including additional directories or files in actions to be copied
1629 $copy_dirs = apply_filters( 'restapi_theme_action_copy_dirs', $copy_dirs );
1630
1631 // since the stuff we care about (CPTS, post formats, are usually on setup or init hooks, we want to load those)
1632 $this->copy_hooks( 'after_setup_theme', 'restapi_theme_after_setup_theme', $copy_dirs );
1633
1634 /**
1635 * Fires functions hooked onto `after_setup_theme` by the theme for the purpose of the REST API.
1636 *
1637 * The REST API does not load the theme when processing requests.
1638 * To enable theme-based functionality, the API will load the '/functions.php',
1639 * '/inc/jetpack.compat.php', '/inc/jetpack.php', '/includes/jetpack.compat.php files
1640 * of the theme (parent and child) and copy functions hooked onto 'after_setup_theme' within those files.
1641 *
1642 * @module json-api
1643 *
1644 * @since 3.2.0
1645 */
1646 do_action( 'restapi_theme_after_setup_theme' );
1647 $this->copy_hooks( 'init', 'restapi_theme_init', $copy_dirs );
1648
1649 /**
1650 * Fires functions hooked onto `init` by the theme for the purpose of the REST API.
1651 *
1652 * The REST API does not load the theme when processing requests.
1653 * To enable theme-based functionality, the API will load the '/functions.php',
1654 * '/inc/jetpack.compat.php', '/inc/jetpack.php', '/includes/jetpack.compat.php files
1655 * of the theme (parent and child) and copy functions hooked onto 'init' within those files.
1656 *
1657 * @module json-api
1658 *
1659 * @since 3.2.0
1660 */
1661 do_action( 'restapi_theme_init' );
1662 }
1663
1664 function copy_hooks( $from_hook, $to_hook, $base_paths ) {
1665 global $wp_filter;
1666 foreach ( $wp_filter as $hook => $actions ) {
1667
1668 if ( $from_hook != $hook ) {
1669 continue;
1670 }
1671 if ( ! has_action( $hook ) ) {
1672 continue;
1673 }
1674
1675 foreach ( $actions as $priority => $callbacks ) {
1676 foreach ( $callbacks as $callback_key => $callback_data ) {
1677 $callback = $callback_data['function'];
1678
1679 // use reflection api to determine filename where function is defined
1680 $reflection = $this->get_reflection( $callback );
1681
1682 if ( false !== $reflection ) {
1683 $file_name = $reflection->getFileName();
1684 foreach ( $base_paths as $base_path ) {
1685
1686 // only copy hooks with functions which are part of the specified files
1687 if ( 0 === strpos( $file_name, $base_path ) ) {
1688 add_action(
1689 $to_hook,
1690 $callback_data['function'],
1691 $priority,
1692 $callback_data['accepted_args']
1693 );
1694 }
1695 }
1696 }
1697 }
1698 }
1699 }
1700 }
1701
1702 function get_reflection( $callback ) {
1703 if ( is_array( $callback ) ) {
1704 list( $class, $method ) = $callback;
1705 return new ReflectionMethod( $class, $method );
1706 }
1707
1708 if ( is_string( $callback ) && strpos( $callback, '::' ) !== false ) {
1709 list( $class, $method ) = explode( '::', $callback );
1710 return new ReflectionMethod( $class, $method );
1711 }
1712
1713 if ( method_exists( $callback, "__invoke" ) ) {
1714 return new ReflectionMethod( $callback, "__invoke" );
1715 }
1716
1717 if ( is_string( $callback ) && strpos( $callback, '::' ) == false && function_exists( $callback ) ) {
1718 return new ReflectionFunction( $callback );
1719 }
1720
1721 return false;
1722 }
1723
1724 /**
1725 * Check whether a user can view or edit a post type
1726 *
1727 * @param string $post_type post type to check
1728 * @param string $context 'display' or 'edit'
1729 * @return bool
1730 */
1731 function current_user_can_access_post_type( $post_type, $context = 'display' ) {
1732 $post_type_object = get_post_type_object( $post_type );
1733 if ( ! $post_type_object ) {
1734 return false;
1735 }
1736
1737 switch ( $context ) {
1738 case 'edit':
1739 return current_user_can( $post_type_object->cap->edit_posts );
1740 case 'display':
1741 return $post_type_object->public || current_user_can( $post_type_object->cap->read_private_posts );
1742 default:
1743 return false;
1744 }
1745 }
1746
1747 function is_post_type_allowed( $post_type ) {
1748 // if the post type is empty, that's fine, WordPress will default to post
1749 if ( empty( $post_type ) ) {
1750 return true;
1751 }
1752
1753 // allow special 'any' type
1754 if ( 'any' == $post_type ) {
1755 return true;
1756 }
1757
1758 // check for allowed types
1759 if ( in_array( $post_type, $this->_get_whitelisted_post_types() ) ) {
1760 return true;
1761 }
1762
1763 if ( $post_type_object = get_post_type_object( $post_type ) ) {
1764 if ( ! empty( $post_type_object->show_in_rest ) ) {
1765 return $post_type_object->show_in_rest;
1766 }
1767 if ( ! empty( $post_type_object->publicly_queryable ) ) {
1768 return $post_type_object->publicly_queryable;
1769 }
1770 }
1771
1772 return ! empty( $post_type_object->public );
1773 }
1774
1775 /**
1776 * Gets the whitelisted post types that JP should allow access to.
1777 *
1778 * @return array Whitelisted post types.
1779 */
1780 protected function _get_whitelisted_post_types() {
1781 $allowed_types = array( 'post', 'page', 'revision' );
1782
1783 /**
1784 * Filter the post types Jetpack has access to, and can synchronize with WordPress.com.
1785 *
1786 * @module json-api
1787 *
1788 * @since 2.2.3
1789 *
1790 * @param array $allowed_types Array of whitelisted post types. Default to `array( 'post', 'page', 'revision' )`.
1791 */
1792 $allowed_types = apply_filters( 'rest_api_allowed_post_types', $allowed_types );
1793
1794 return array_unique( $allowed_types );
1795 }
1796
1797 function handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs = array(), $force_parent_id = false ) {
1798
1799 add_filter( 'upload_mimes', array( $this, 'allow_video_uploads' ) );
1800
1801 $media_ids = $errors = array();
1802 $user_can_upload_files = current_user_can( 'upload_files' ) || $this->api->is_authorized_with_upload_token();
1803 $media_attrs = array_values( $media_attrs ); // reset the keys
1804 $i = 0;
1805
1806 if ( ! empty( $media_files ) ) {
1807 $this->api->trap_wp_die( 'upload_error' );
1808 foreach ( $media_files as $media_item ) {
1809 $_FILES['.api.media.item.'] = $media_item;
1810 if ( ! $user_can_upload_files ) {
1811 $media_id = new WP_Error( 'unauthorized', 'User cannot upload media.', 403 );
1812 } else {
1813 if ( $force_parent_id ) {
1814 $parent_id = absint( $force_parent_id );
1815 } elseif ( ! empty( $media_attrs[ $i ] ) && ! empty( $media_attrs[ $i ]['parent_id'] ) ) {
1816 $parent_id = absint( $media_attrs[ $i ]['parent_id'] );
1817 } else {
1818 $parent_id = 0;
1819 }
1820 $media_id = media_handle_upload( '.api.media.item.', $parent_id );
1821 }
1822 if ( is_wp_error( $media_id ) ) {
1823 $errors[ $i ]['file'] = $media_item['name'];
1824 $errors[ $i ]['error'] = $media_id->get_error_code();
1825 $errors[ $i ]['message'] = $media_id->get_error_message();
1826 } else {
1827 $media_ids[ $i ] = $media_id;
1828 }
1829
1830 $i++;
1831 }
1832 $this->api->trap_wp_die( null );
1833 unset( $_FILES['.api.media.item.'] );
1834 }
1835
1836 if ( ! empty( $media_urls ) ) {
1837 foreach ( $media_urls as $url ) {
1838 if ( ! $user_can_upload_files ) {
1839 $media_id = new WP_Error( 'unauthorized', 'User cannot upload media.', 403 );
1840 } else {
1841 if ( $force_parent_id ) {
1842 $parent_id = absint( $force_parent_id );
1843 } elseif ( ! empty( $media_attrs[ $i ] ) && ! empty( $media_attrs[ $i ]['parent_id'] ) ) {
1844 $parent_id = absint( $media_attrs[ $i ]['parent_id'] );
1845 } else {
1846 $parent_id = 0;
1847 }
1848 $media_id = $this->handle_media_sideload( $url, $parent_id );
1849 }
1850 if ( is_wp_error( $media_id ) ) {
1851 $errors[ $i ] = array(
1852 'file' => $url,
1853 'error' => $media_id->get_error_code(),
1854 'message' => $media_id->get_error_message(),
1855 );
1856 } elseif ( ! empty( $media_id ) ) {
1857 $media_ids[ $i ] = $media_id;
1858 }
1859
1860 $i++;
1861 }
1862 }
1863
1864 if ( ! empty( $media_attrs ) ) {
1865 foreach ( $media_ids as $index => $media_id ) {
1866 if ( empty( $media_attrs[ $index ] ) ) {
1867 continue;
1868 }
1869
1870 $attrs = $media_attrs[ $index ];
1871 $insert = array();
1872
1873 // Attributes: Title, Caption, Description
1874
1875 if ( isset( $attrs['title'] ) ) {
1876 $insert['post_title'] = $attrs['title'];
1877 }
1878
1879 if ( isset( $attrs['caption'] ) ) {
1880 $insert['post_excerpt'] = $attrs['caption'];
1881 }
1882
1883 if ( isset( $attrs['description'] ) ) {
1884 $insert['post_content'] = $attrs['description'];
1885 }
1886
1887 if ( ! empty( $insert ) ) {
1888 $insert['ID'] = $media_id;
1889 wp_update_post( (object) $insert );
1890 }
1891
1892 // Attributes: Alt
1893
1894 if ( isset( $attrs['alt'] ) ) {
1895 $alt = wp_strip_all_tags( $attrs['alt'], true );
1896 update_post_meta( $media_id, '_wp_attachment_image_alt', $alt );
1897 }
1898
1899 // Attributes: Artist, Album
1900
1901 $id3_meta = array();
1902
1903 foreach ( array( 'artist', 'album' ) as $key ) {
1904 if ( isset( $attrs[ $key ] ) ) {
1905 $id3_meta[ $key ] = wp_strip_all_tags( $attrs[ $key ], true );
1906 }
1907 }
1908
1909 if ( ! empty( $id3_meta ) ) {
1910 // Before updating metadata, ensure that the item is audio
1911 $item = $this->get_media_item_v1_1( $media_id );
1912 if ( 0 === strpos( $item->mime_type, 'audio/' ) ) {
1913 wp_update_attachment_metadata( $media_id, $id3_meta );
1914 }
1915 }
1916 }
1917 }
1918
1919 return array(
1920 'media_ids' => $media_ids,
1921 'errors' => $errors,
1922 );
1923
1924 }
1925
1926 function handle_media_sideload( $url, $parent_post_id = 0, $type = 'any' ) {
1927 if ( ! function_exists( 'download_url' ) || ! function_exists( 'media_handle_sideload' ) ) {
1928 return false;
1929 }
1930
1931 // if we didn't get a URL, let's bail
1932 $parsed = @parse_url( $url );
1933 if ( empty( $parsed ) ) {
1934 return false;
1935 }
1936
1937 $tmp = download_url( $url );
1938 if ( is_wp_error( $tmp ) ) {
1939 return $tmp;
1940 }
1941
1942 // First check to see if we get a mime-type match by file, otherwise, check to
1943 // see if WordPress supports this file as an image. If neither, then it is not supported.
1944 if ( ! $this->is_file_supported_for_sideloading( $tmp ) || 'image' === $type && ! file_is_displayable_image( $tmp ) ) {
1945 @unlink( $tmp );
1946 return new WP_Error( 'invalid_input', 'Invalid file type.', 403 );
1947 }
1948
1949 // emulate a $_FILES entry
1950 $file_array = array(
1951 'name' => basename( parse_url( $url, PHP_URL_PATH ) ),
1952 'tmp_name' => $tmp,
1953 );
1954
1955 $id = media_handle_sideload( $file_array, $parent_post_id );
1956 if ( file_exists( $tmp ) ) {
1957 @unlink( $tmp );
1958 }
1959
1960 if ( is_wp_error( $id ) ) {
1961 return $id;
1962 }
1963
1964 if ( ! $id || ! is_int( $id ) ) {
1965 return false;
1966 }
1967
1968 return $id;
1969 }
1970
1971 /**
1972 * Checks that the mime type of the specified file is among those in a filterable list of mime types.
1973 *
1974 * @param string $file Path to file to get its mime type.
1975 *
1976 * @return bool
1977 */
1978 protected function is_file_supported_for_sideloading( $file ) {
1979 return jetpack_is_file_supported_for_sideloading( $file );
1980 }
1981
1982 function allow_video_uploads( $mimes ) {
1983 // if we are on Jetpack, bail - Videos are already allowed
1984 if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
1985 return $mimes;
1986 }
1987
1988 // extra check that this filter is only ever applied during REST API requests
1989 if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) {
1990 return $mimes;
1991 }
1992
1993 // bail early if they already have the upgrade..
1994 if ( get_option( 'video_upgrade' ) == '1' ) {
1995 return $mimes;
1996 }
1997
1998 // lets whitelist to only specific clients right now
1999 $clients_allowed_video_uploads = array();
2000 /**
2001 * Filter the list of whitelisted video clients.
2002 *
2003 * @module json-api
2004 *
2005 * @since 3.2.0
2006 *
2007 * @param array $clients_allowed_video_uploads Array of whitelisted Video clients.
2008 */
2009 $clients_allowed_video_uploads = apply_filters( 'rest_api_clients_allowed_video_uploads', $clients_allowed_video_uploads );
2010 if ( ! in_array( $this->api->token_details['client_id'], $clients_allowed_video_uploads ) ) {
2011 return $mimes;
2012 }
2013
2014 $mime_list = wp_get_mime_types();
2015
2016 $video_exts = explode( ' ', get_site_option( 'video_upload_filetypes', false, false ) );
2017 /**
2018 * Filter the video filetypes allowed on the site.
2019 *
2020 * @module json-api
2021 *
2022 * @since 3.2.0
2023 *
2024 * @param array $video_exts Array of video filetypes allowed on the site.
2025 */
2026 $video_exts = apply_filters( 'video_upload_filetypes', $video_exts );
2027 $video_mimes = array();
2028
2029 if ( ! empty( $video_exts ) ) {
2030 foreach ( $video_exts as $ext ) {
2031 foreach ( $mime_list as $ext_pattern => $mime ) {
2032 if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false ) {
2033 $video_mimes[ $ext_pattern ] = $mime;
2034 }
2035 }
2036 }
2037
2038 $mimes = array_merge( $mimes, $video_mimes );
2039 }
2040
2041 return $mimes;
2042 }
2043
2044 function is_current_site_multi_user() {
2045 $users = wp_cache_get( 'site_user_count', 'WPCOM_JSON_API_Endpoint' );
2046 if ( false === $users ) {
2047 $user_query = new WP_User_Query(
2048 array(
2049 'blog_id' => get_current_blog_id(),
2050 'fields' => 'ID',
2051 )
2052 );
2053 $users = (int) $user_query->get_total();
2054 wp_cache_set( 'site_user_count', $users, 'WPCOM_JSON_API_Endpoint', DAY_IN_SECONDS );
2055 }
2056 return $users > 1;
2057 }
2058
2059 function allows_cross_origin_requests() {
2060 return 'GET' == $this->method || $this->allow_cross_origin_request;
2061 }
2062
2063 function allows_unauthorized_requests( $origin, $complete_access_origins ) {
2064 return 'GET' == $this->method || ( $this->allow_unauthorized_request && in_array( $origin, $complete_access_origins ) );
2065 }
2066
2067 function get_platform() {
2068 return wpcom_get_sal_platform( $this->api->token_details );
2069 }
2070
2071 /**
2072 * Allows the endpoint to perform logic to allow it to decide whether-or-not it should force a
2073 * response from the WPCOM API, or potentially go to the Jetpack blog.
2074 *
2075 * Override this method if you want to do something different.
2076 *
2077 * @param int $blog_id
2078 * @return bool
2079 */
2080 function force_wpcom_request( $blog_id ) {
2081 return false;
2082 }
2083
2084 /**
2085 * Return endpoint response
2086 *
2087 * @param ... determined by ->$path
2088 *
2089 * @return
2090 * falsy: HTTP 500, no response body
2091 * WP_Error( $error_code, $error_message, $http_status_code ): HTTP $status_code, json_encode( array( 'error' => $error_code, 'message' => $error_message ) ) response body
2092 * $data: HTTP 200, json_encode( $data ) response body
2093 */
2094 abstract function callback( $path = '' );
2095
2096
2097 }
2098
2099 require_once dirname( __FILE__ ) . '/json-endpoints.php';
2100