PageRenderTime 40ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/jetpack/class.json-api.php

https://gitlab.com/hunt9310/ras
PHP | 693 lines | 509 code | 121 blank | 63 comment | 118 complexity | dc37a0ec7f6dbe1b451e1f790e10bb07 MD5 | raw file
  1. <?php
  2. defined( 'WPCOM_JSON_API__DEBUG' ) or define( 'WPCOM_JSON_API__DEBUG', false );
  3. require_once dirname( __FILE__ ) . '/sal/class.json-api-platform.php';
  4. class WPCOM_JSON_API {
  5. static $self = null;
  6. public $endpoints = array();
  7. public $token_details = array();
  8. public $method = '';
  9. public $url = '';
  10. public $path = '';
  11. public $version = null;
  12. public $query = array();
  13. public $post_body = null;
  14. public $files = null;
  15. public $content_type = null;
  16. public $accept = '';
  17. public $_server_https;
  18. public $exit = true;
  19. public $public_api_scheme = 'https';
  20. public $output_status_code = 200;
  21. public $trapped_error = null;
  22. public $did_output = false;
  23. /**
  24. * @return WPCOM_JSON_API instance
  25. */
  26. static function init( $method = null, $url = null, $post_body = null ) {
  27. if ( !self::$self ) {
  28. $class = function_exists( 'get_called_class' ) ? get_called_class() : __CLASS__;
  29. self::$self = new $class( $method, $url, $post_body );
  30. }
  31. return self::$self;
  32. }
  33. function add( WPCOM_JSON_API_Endpoint $endpoint ) {
  34. $path_versions = serialize( array (
  35. $endpoint->path,
  36. $endpoint->min_version,
  37. $endpoint->max_version,
  38. ) );
  39. if ( !isset( $this->endpoints[$path_versions] ) ) {
  40. $this->endpoints[$path_versions] = array();
  41. }
  42. $this->endpoints[$path_versions][$endpoint->method] = $endpoint;
  43. }
  44. static function is_truthy( $value ) {
  45. switch ( strtolower( (string) $value ) ) {
  46. case '1' :
  47. case 't' :
  48. case 'true' :
  49. return true;
  50. }
  51. return false;
  52. }
  53. static function is_falsy( $value ) {
  54. switch ( strtolower( (string) $value ) ) {
  55. case '0' :
  56. case 'f' :
  57. case 'false' :
  58. return true;
  59. }
  60. return false;
  61. }
  62. function __construct() {
  63. $args = func_get_args();
  64. call_user_func_array( array( $this, 'setup_inputs' ), $args );
  65. }
  66. function setup_inputs( $method = null, $url = null, $post_body = null ) {
  67. if ( is_null( $method ) ) {
  68. $this->method = strtoupper( $_SERVER['REQUEST_METHOD'] );
  69. } else {
  70. $this->method = strtoupper( $method );
  71. }
  72. if ( is_null( $url ) ) {
  73. $this->url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  74. } else {
  75. $this->url = $url;
  76. }
  77. $parsed = parse_url( $this->url );
  78. $this->path = $parsed['path'];
  79. if ( !empty( $parsed['query'] ) ) {
  80. wp_parse_str( $parsed['query'], $this->query );
  81. }
  82. if ( isset( $_SERVER['HTTP_ACCEPT'] ) && $_SERVER['HTTP_ACCEPT'] ) {
  83. $this->accept = $_SERVER['HTTP_ACCEPT'];
  84. }
  85. if ( 'POST' === $this->method ) {
  86. if ( is_null( $post_body ) ) {
  87. $this->post_body = file_get_contents( 'php://input' );
  88. if ( isset( $_SERVER['HTTP_CONTENT_TYPE'] ) && $_SERVER['HTTP_CONTENT_TYPE'] ) {
  89. $this->content_type = $_SERVER['HTTP_CONTENT_TYPE'];
  90. } elseif ( isset( $_SERVER['CONTENT_TYPE'] ) && $_SERVER['CONTENT_TYPE'] ) {
  91. $this->content_type = $_SERVER['CONTENT_TYPE'] ;
  92. } elseif ( '{' === $this->post_body[0] ) {
  93. $this->content_type = 'application/json';
  94. } else {
  95. $this->content_type = 'application/x-www-form-urlencoded';
  96. }
  97. if ( 0 === strpos( strtolower( $this->content_type ), 'multipart/' ) ) {
  98. $this->post_body = http_build_query( stripslashes_deep( $_POST ) );
  99. $this->files = $_FILES;
  100. $this->content_type = 'multipart/form-data';
  101. }
  102. } else {
  103. $this->post_body = $post_body;
  104. $this->content_type = '{' === isset( $this->post_body[0] ) && $this->post_body[0] ? 'application/json' : 'application/x-www-form-urlencoded';
  105. }
  106. } else {
  107. $this->post_body = null;
  108. $this->content_type = null;
  109. }
  110. $this->_server_https = array_key_exists( 'HTTPS', $_SERVER ) ? $_SERVER['HTTPS'] : '--UNset--';
  111. }
  112. function initialize() {
  113. $this->token_details['blog_id'] = Jetpack_Options::get_option( 'id' );
  114. }
  115. function serve( $exit = true ) {
  116. ini_set( 'display_errors', false );
  117. $this->exit = (bool) $exit;
  118. // This was causing problems with Jetpack, but is necessary for wpcom
  119. // @see https://github.com/Automattic/jetpack/pull/2603
  120. // @see r124548-wpcom
  121. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  122. add_filter( 'home_url', array( $this, 'ensure_http_scheme_of_home_url' ), 10, 3 );
  123. }
  124. add_filter( 'user_can_richedit', '__return_true' );
  125. add_filter( 'comment_edit_pre', array( $this, 'comment_edit_pre' ) );
  126. $initialization = $this->initialize();
  127. if ( 'OPTIONS' == $this->method ) {
  128. /**
  129. * Fires before the page output.
  130. * Can be used to specify custom header options.
  131. *
  132. * @module json-api
  133. *
  134. * @since 3.1.0
  135. */
  136. do_action( 'wpcom_json_api_options' );
  137. return $this->output( 200, '', 'plain/text' );
  138. }
  139. if ( is_wp_error( $initialization ) ) {
  140. $this->output_error( $initialization );
  141. return;
  142. }
  143. // Normalize path and extract API version
  144. $this->path = untrailingslashit( $this->path );
  145. preg_match( '#^/rest/v(\d+(\.\d+)*)#', $this->path, $matches );
  146. $this->path = substr( $this->path, strlen( $matches[0] ) );
  147. $this->version = $matches[1];
  148. $allowed_methods = array( 'GET', 'POST' );
  149. $four_oh_five = false;
  150. $is_help = preg_match( '#/help/?$#i', $this->path );
  151. $matching_endpoints = array();
  152. if ( $is_help ) {
  153. $origin = get_http_origin();
  154. if ( !empty( $origin ) && 'GET' == $this->method ) {
  155. header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
  156. }
  157. $this->path = substr( rtrim( $this->path, '/' ), 0, -5 );
  158. // Show help for all matching endpoints regardless of method
  159. $methods = $allowed_methods;
  160. $find_all_matching_endpoints = true;
  161. // How deep to truncate each endpoint's path to see if it matches this help request
  162. $depth = substr_count( $this->path, '/' ) + 1;
  163. if ( false !== stripos( $this->accept, 'javascript' ) || false !== stripos( $this->accept, 'json' ) ) {
  164. $help_content_type = 'json';
  165. } else {
  166. $help_content_type = 'html';
  167. }
  168. } else {
  169. if ( in_array( $this->method, $allowed_methods ) ) {
  170. // Only serve requested method
  171. $methods = array( $this->method );
  172. $find_all_matching_endpoints = false;
  173. } else {
  174. // We don't allow this requested method - find matching endpoints and send 405
  175. $methods = $allowed_methods;
  176. $find_all_matching_endpoints = true;
  177. $four_oh_five = true;
  178. }
  179. }
  180. // Find which endpoint to serve
  181. $found = false;
  182. foreach ( $this->endpoints as $endpoint_path_versions => $endpoints_by_method ) {
  183. $endpoint_path_versions = unserialize( $endpoint_path_versions );
  184. $endpoint_path = $endpoint_path_versions[0];
  185. $endpoint_min_version = $endpoint_path_versions[1];
  186. $endpoint_max_version = $endpoint_path_versions[2];
  187. // Make sure max_version is not less than min_version
  188. if ( version_compare( $endpoint_max_version, $endpoint_min_version, '<' ) ) {
  189. $endpoint_max_version = $endpoint_min_version;
  190. }
  191. foreach ( $methods as $method ) {
  192. if ( !isset( $endpoints_by_method[$method] ) ) {
  193. continue;
  194. }
  195. // Normalize
  196. $endpoint_path = untrailingslashit( $endpoint_path );
  197. if ( $is_help ) {
  198. // Truncate path at help depth
  199. $endpoint_path = join( '/', array_slice( explode( '/', $endpoint_path ), 0, $depth ) );
  200. }
  201. // Generate regular expression from sprintf()
  202. $endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path );
  203. if ( !preg_match( "#^$endpoint_path_regex\$#", $this->path, $path_pieces ) ) {
  204. // This endpoint does not match the requested path.
  205. continue;
  206. }
  207. if ( version_compare( $this->version, $endpoint_min_version, '<' ) || version_compare( $this->version, $endpoint_max_version, '>' ) ) {
  208. // This endpoint does not match the requested version.
  209. continue;
  210. }
  211. $found = true;
  212. if ( $find_all_matching_endpoints ) {
  213. $matching_endpoints[] = array( $endpoints_by_method[$method], $path_pieces );
  214. } else {
  215. // The method parameters are now in $path_pieces
  216. $endpoint = $endpoints_by_method[$method];
  217. break 2;
  218. }
  219. }
  220. }
  221. if ( !$found ) {
  222. return $this->output( 404, '', 'text/plain' );
  223. }
  224. if ( $four_oh_five ) {
  225. $allowed_methods = array();
  226. foreach ( $matching_endpoints as $matching_endpoint ) {
  227. $allowed_methods[] = $matching_endpoint[0]->method;
  228. }
  229. header( 'Allow: ' . strtoupper( join( ',', array_unique( $allowed_methods ) ) ) );
  230. return $this->output( 405, array( 'error' => 'not_allowed', 'error_message' => 'Method not allowed' ) );
  231. }
  232. if ( $is_help ) {
  233. /**
  234. * Fires before the API output.
  235. *
  236. * @since 1.9.0
  237. *
  238. * @param string help.
  239. */
  240. do_action( 'wpcom_json_api_output', 'help' );
  241. if ( 'json' === $help_content_type ) {
  242. $docs = array();
  243. foreach ( $matching_endpoints as $matching_endpoint ) {
  244. if ( $matching_endpoint[0]->is_publicly_documentable() || WPCOM_JSON_API__DEBUG )
  245. $docs[] = call_user_func( array( $matching_endpoint[0], 'generate_documentation' ) );
  246. }
  247. return $this->output( 200, $docs );
  248. } else {
  249. status_header( 200 );
  250. foreach ( $matching_endpoints as $matching_endpoint ) {
  251. if ( $matching_endpoint[0]->is_publicly_documentable() || WPCOM_JSON_API__DEBUG )
  252. call_user_func( array( $matching_endpoint[0], 'document' ) );
  253. }
  254. }
  255. exit;
  256. }
  257. if ( $endpoint->in_testing && !WPCOM_JSON_API__DEBUG ) {
  258. return $this->output( 404, '', 'text/plain' );
  259. }
  260. /** This action is documented in class.json-api.php */
  261. do_action( 'wpcom_json_api_output', $endpoint->stat );
  262. $response = $this->process_request( $endpoint, $path_pieces );
  263. if ( !$response && !is_array( $response ) ) {
  264. return $this->output( 500, '', 'text/plain' );
  265. } elseif ( is_wp_error( $response ) ) {
  266. return $this->output_error( $response );
  267. }
  268. $output_status_code = $this->output_status_code;
  269. $this->set_output_status_code();
  270. return $this->output( $output_status_code, $response );
  271. }
  272. function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) {
  273. $this->endpoint = $endpoint;
  274. return call_user_func_array( array( $endpoint, 'callback' ), $path_pieces );
  275. }
  276. function output_early( $status_code, $response = null, $content_type = 'application/json' ) {
  277. $exit = $this->exit;
  278. $this->exit = false;
  279. if ( is_wp_error( $response ) )
  280. $this->output_error( $response );
  281. else
  282. $this->output( $status_code, $response, $content_type );
  283. $this->exit = $exit;
  284. if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
  285. $this->finish_request();
  286. }
  287. }
  288. function set_output_status_code( $code = 200 ) {
  289. $this->output_status_code = $code;
  290. }
  291. function output( $status_code, $response = null, $content_type = 'application/json' ) {
  292. // In case output() was called before the callback returned
  293. if ( $this->did_output ) {
  294. if ( $this->exit )
  295. exit;
  296. return $content_type;
  297. }
  298. $this->did_output = true;
  299. // 400s and 404s are allowed for all origins
  300. if ( 404 == $status_code || 400 == $status_code )
  301. header( 'Access-Control-Allow-Origin: *' );
  302. if ( is_null( $response ) ) {
  303. $response = new stdClass;
  304. }
  305. if ( 'text/plain' === $content_type ) {
  306. status_header( (int) $status_code );
  307. header( 'Content-Type: text/plain' );
  308. echo $response;
  309. if ( $this->exit ) {
  310. exit;
  311. }
  312. return $content_type;
  313. }
  314. $response = $this->filter_fields( $response );
  315. if ( isset( $this->query['http_envelope'] ) && self::is_truthy( $this->query['http_envelope'] ) ) {
  316. $response = array(
  317. 'code' => (int) $status_code,
  318. 'headers' => array(
  319. array(
  320. 'name' => 'Content-Type',
  321. 'value' => $content_type,
  322. ),
  323. ),
  324. 'body' => $response,
  325. );
  326. $status_code = 200;
  327. $content_type = 'application/json';
  328. }
  329. status_header( (int) $status_code );
  330. header( "Content-Type: $content_type" );
  331. if ( isset( $this->query['callback'] ) && is_string( $this->query['callback'] ) ) {
  332. $callback = preg_replace( '/[^a-z0-9_.]/i', '', $this->query['callback'] );
  333. } else {
  334. $callback = false;
  335. }
  336. if ( $callback ) {
  337. // Mitigate Rosetta Flash [1] by setting the Content-Type-Options: nosniff header
  338. // and by prepending the JSONP response with a JS comment.
  339. // [1] http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  340. echo "/**/$callback(";
  341. }
  342. echo $this->json_encode( $response );
  343. if ( $callback ) {
  344. echo ");";
  345. }
  346. if ( $this->exit ) {
  347. exit;
  348. }
  349. return $content_type;
  350. }
  351. public static function serializable_error ( $error ) {
  352. $status_code = $error->get_error_data();
  353. if ( is_array( $status_code ) )
  354. $status_code = $status_code['status_code'];
  355. if ( !$status_code ) {
  356. $status_code = 400;
  357. }
  358. $response = array(
  359. 'error' => $error->get_error_code(),
  360. 'message' => $error->get_error_message(),
  361. );
  362. return array(
  363. 'status_code' => $status_code,
  364. 'errors' => $response
  365. );
  366. }
  367. function output_error( $error ) {
  368. if ( function_exists( 'bump_stats_extra' ) ) {
  369. $client_id = ! empty( $this->token_details['client_id'] ) ? $this->token_details['client_id'] : 0;
  370. bump_stats_extra( 'rest-api-errors', $client_id );
  371. }
  372. $error_response = $this->serializable_error( $error );
  373. return $this->output( $error_response[ 'status_code'], $error_response['errors'] );
  374. }
  375. function filter_fields( $response ) {
  376. if ( empty( $this->query['fields'] ) || ( is_array( $response ) && ! empty( $response['error'] ) ) || ! empty( $this->endpoint->custom_fields_filtering ) )
  377. return $response;
  378. $fields = array_map( 'trim', explode( ',', $this->query['fields'] ) );
  379. if ( is_object( $response ) ) {
  380. $response = (array) $response;
  381. }
  382. $has_filtered = false;
  383. if ( is_array( $response ) && empty( $response['ID'] ) ) {
  384. $keys_to_filter = array(
  385. 'categories',
  386. 'comments',
  387. 'connections',
  388. 'domains',
  389. 'groups',
  390. 'likes',
  391. 'media',
  392. 'notes',
  393. 'posts',
  394. 'services',
  395. 'sites',
  396. 'suggestions',
  397. 'tags',
  398. 'themes',
  399. 'topics',
  400. 'users',
  401. );
  402. foreach ( $keys_to_filter as $key_to_filter ) {
  403. if ( ! isset( $response[ $key_to_filter ] ) || $has_filtered )
  404. continue;
  405. foreach ( $response[ $key_to_filter ] as $key => $values ) {
  406. if ( is_object( $values ) ) {
  407. $response[ $key_to_filter ][ $key ] = (object) array_intersect_key( (array) $values, array_flip( $fields ) );
  408. } elseif ( is_array( $values ) ) {
  409. $response[ $key_to_filter ][ $key ] = array_intersect_key( $values, array_flip( $fields ) );
  410. }
  411. }
  412. $has_filtered = true;
  413. }
  414. }
  415. if ( ! $has_filtered ) {
  416. if ( is_object( $response ) ) {
  417. $response = (object) array_intersect_key( (array) $response, array_flip( $fields ) );
  418. } else if ( is_array( $response ) ) {
  419. $response = array_intersect_key( $response, array_flip( $fields ) );
  420. }
  421. }
  422. return $response;
  423. }
  424. function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) {
  425. if ( $original_scheme ) {
  426. return $url;
  427. }
  428. return preg_replace( '#^https:#', 'http:', $url );
  429. }
  430. function comment_edit_pre( $comment_content ) {
  431. return htmlspecialchars_decode( $comment_content, ENT_QUOTES );
  432. }
  433. function json_encode( $data ) {
  434. return json_encode( $data );
  435. }
  436. function ends_with( $haystack, $needle ) {
  437. return $needle === substr( $haystack, -strlen( $needle ) );
  438. }
  439. // Returns the site's blog_id in the WP.com ecosystem
  440. function get_blog_id_for_output() {
  441. return $this->token_details['blog_id'];
  442. }
  443. // Returns the site's local blog_id
  444. function get_blog_id( $blog_id ) {
  445. return $GLOBALS['blog_id'];
  446. }
  447. function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) {
  448. if ( $this->is_restricted_blog( $blog_id ) ) {
  449. return new WP_Error( 'unauthorized', 'User cannot access this restricted blog', 403 );
  450. }
  451. if ( -1 == get_option( 'blog_public' ) && !current_user_can( 'read' ) ) {
  452. return new WP_Error( 'unauthorized', 'User cannot access this private blog.', 403 );
  453. }
  454. return $blog_id;
  455. }
  456. // Returns true if the specified blog ID is a restricted blog
  457. function is_restricted_blog( $blog_id ) {
  458. /**
  459. * Filters all REST API access and return a 403 unauthorized response for all Restricted blog IDs.
  460. *
  461. * @module json-api
  462. *
  463. * @since 3.4.0
  464. *
  465. * @param array $array Array of Blog IDs.
  466. */
  467. $restricted_blog_ids = apply_filters( 'wpcom_json_api_restricted_blog_ids', array() );
  468. return true === in_array( $blog_id, $restricted_blog_ids );
  469. }
  470. function post_like_count( $blog_id, $post_id ) {
  471. return 0;
  472. }
  473. function is_liked( $blog_id, $post_id ) {
  474. return false;
  475. }
  476. function is_reblogged( $blog_id, $post_id ) {
  477. return false;
  478. }
  479. function is_following( $blog_id ) {
  480. return false;
  481. }
  482. function add_global_ID( $blog_id, $post_id ) {
  483. return '';
  484. }
  485. function get_avatar_url( $email, $avatar_size = 96 ) {
  486. add_filter( 'pre_option_show_avatars', '__return_true', 999 );
  487. $_SERVER['HTTPS'] = 'off';
  488. $avatar_img_element = get_avatar( $email, $avatar_size, '' );
  489. if ( !$avatar_img_element || is_wp_error( $avatar_img_element ) ) {
  490. $return = '';
  491. } elseif ( !preg_match( '#src=([\'"])?(.*?)(?(1)\\1|\s)#', $avatar_img_element, $matches ) ) {
  492. $return = '';
  493. } else {
  494. $return = esc_url_raw( htmlspecialchars_decode( $matches[2] ) );
  495. }
  496. remove_filter( 'pre_option_show_avatars', '__return_true', 999 );
  497. if ( '--UNset--' === $this->_server_https ) {
  498. unset( $_SERVER['HTTPS'] );
  499. } else {
  500. $_SERVER['HTTPS'] = $this->_server_https;
  501. }
  502. return $return;
  503. }
  504. /**
  505. * Traps `wp_die()` calls and outputs a JSON response instead.
  506. * The result is always output, never returned.
  507. *
  508. * @param string|null $error_code. Call with string to start the trapping. Call with null to stop.
  509. */
  510. function trap_wp_die( $error_code = null ) {
  511. // Stop trapping
  512. if ( is_null( $error_code ) ) {
  513. $this->trapped_error = null;
  514. remove_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) );
  515. return;
  516. }
  517. // If API called via PHP, bail: don't do our custom wp_die(). Do the normal wp_die().
  518. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  519. if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) {
  520. return;
  521. }
  522. } else {
  523. if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
  524. return;
  525. }
  526. }
  527. // Start trapping
  528. $this->trapped_error = array(
  529. 'status' => 500,
  530. 'code' => $error_code,
  531. 'message' => '',
  532. );
  533. add_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) );
  534. }
  535. function wp_die_handler_callback() {
  536. return array( $this, 'wp_die_handler' );
  537. }
  538. function wp_die_handler( $message, $title = '', $args = array() ) {
  539. $args = wp_parse_args( $args, array(
  540. 'response' => 500,
  541. ) );
  542. if ( $title ) {
  543. $message = "$title: $message";
  544. }
  545. switch ( $this->trapped_error['code'] ) {
  546. case 'comment_failure' :
  547. if ( did_action( 'comment_duplicate_trigger' ) ) {
  548. $this->trapped_error['code'] = 'comment_duplicate';
  549. } else if ( did_action( 'comment_flood_trigger' ) ) {
  550. $this->trapped_error['code'] = 'comment_flood';
  551. }
  552. break;
  553. }
  554. $this->trapped_error['status'] = $args['response'];
  555. $this->trapped_error['message'] = wp_kses( $message, array() );
  556. // We still want to exit so that code execution stops where it should.
  557. // Attach the JSON output to WordPress' shutdown handler
  558. add_action( 'shutdown', array( $this, 'output_trapped_error' ), 0 );
  559. exit;
  560. }
  561. function output_trapped_error() {
  562. $this->exit = false; // We're already exiting once. Don't do it twice.
  563. $this->output( $this->trapped_error['status'], (object) array(
  564. 'error' => $this->trapped_error['code'],
  565. 'message' => $this->trapped_error['message'],
  566. ) );
  567. }
  568. function finish_request() {
  569. if ( function_exists( 'fastcgi_finish_request' ) )
  570. return fastcgi_finish_request();
  571. }
  572. }