WPCOM_JSON_API_Endpoint

The Jetpack by WordPress.com WPCOM JSON API Endpoint class.

Defined (1)

The class is defined in the following location(s).

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