PageRenderTime 378ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

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

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