PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/mshmsh5000/wp-demo
PHP | 447 lines | 342 code | 81 blank | 24 comment | 74 complexity | bc686c162a17c82647ee574d5a2c37bd MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, LGPL-2.1, GPL-2.0
  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 $query = array();
  11. var $post_body = null;
  12. var $files = null;
  13. var $content_type = null;
  14. var $accept = '';
  15. var $_server_https;
  16. var $exit = true;
  17. var $public_api_scheme = 'https';
  18. var $trapped_error = null;
  19. static function init( $method = null, $url = null, $post_body = null ) {
  20. if ( !self::$self ) {
  21. $class = function_exists( 'get_called_class' ) ? get_called_class() : __CLASS__;
  22. self::$self = new $class( $method, $url, $post_body );
  23. }
  24. return self::$self;
  25. }
  26. function add( WPCOM_JSON_API_Endpoint $endpoint ) {
  27. if ( !isset( $this->endpoints[$endpoint->path] ) ) {
  28. $this->endpoints[$endpoint->path] = array();
  29. }
  30. $this->endpoints[$endpoint->path][$endpoint->method] = $endpoint;
  31. }
  32. static function is_truthy( $value ) {
  33. switch ( strtolower( (string) $value ) ) {
  34. case '1' :
  35. case 't' :
  36. case 'true' :
  37. return true;
  38. }
  39. return false;
  40. }
  41. function __construct() {
  42. $args = func_get_args();
  43. call_user_func_array( array( $this, 'setup_inputs' ), $args );
  44. }
  45. function setup_inputs( $method = null, $url = null, $post_body = null ) {
  46. if ( is_null( $method ) ) {
  47. $this->method = strtoupper( $_SERVER['REQUEST_METHOD'] );
  48. } else {
  49. $this->method = strtoupper( $method );
  50. }
  51. if ( is_null( $url ) ) {
  52. $this->url = ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  53. } else {
  54. $this->url = $url;
  55. }
  56. $parsed = parse_url( $this->url );
  57. $this->path = $parsed['path'];
  58. if ( !empty( $parsed['query'] ) ) {
  59. wp_parse_str( $parsed['query'], $this->query );
  60. }
  61. if ( isset( $_SERVER['HTTP_ACCEPT'] ) && $_SERVER['HTTP_ACCEPT'] ) {
  62. $this->accept = $_SERVER['HTTP_ACCEPT'];
  63. }
  64. if ( 'POST' === $this->method ) {
  65. if ( is_null( $post_body ) ) {
  66. $this->post_body = file_get_contents( 'php://input' );
  67. if ( isset( $_SERVER['HTTP_CONTENT_TYPE'] ) && $_SERVER['HTTP_CONTENT_TYPE'] ) {
  68. $this->content_type = $_SERVER['HTTP_CONTENT_TYPE'];
  69. } elseif ( isset( $_SERVER['CONTENT_TYPE'] ) && $_SERVER['CONTENT_TYPE'] ) {
  70. $this->content_type = $_SERVER['CONTENT_TYPE'] ;
  71. } elseif ( '{' === $this->post_body[0] ) {
  72. $this->content_type = 'application/json';
  73. } else {
  74. $this->content_type = 'application/x-www-form-urlencoded';
  75. }
  76. if ( 0 === strpos( strtolower( $this->content_type ), 'multipart/' ) ) {
  77. $this->post_body = http_build_query( stripslashes_deep( $_POST ) );
  78. $this->files = $_FILES;
  79. $this->content_type = 'multipart/form-data';
  80. }
  81. } else {
  82. $this->post_body = $post_body;
  83. $this->content_type = '{' === $this->post_body[0] ? 'application/json' : 'application/x-www-form-urlencoded';
  84. }
  85. } else {
  86. $this->post_body = null;
  87. $this->content_type = null;
  88. }
  89. $this->_server_https = array_key_exists( 'HTTPS', $_SERVER ) ? $_SERVER['HTTPS'] : '--UNset--';
  90. }
  91. function initialize() {
  92. $this->token_details['blog_id'] = Jetpack::get_option( 'id' );
  93. }
  94. function serve( $exit = true ) {
  95. $this->exit = (bool) $exit;
  96. add_filter( 'home_url', array( $this, 'ensure_http_scheme_of_home_url' ), 10, 3 );
  97. add_filter( 'user_can_richedit', '__return_true' );
  98. add_filter( 'comment_edit_pre', array( $this, 'comment_edit_pre' ) );
  99. $this->initialize();
  100. // Normalize path
  101. $this->path = untrailingslashit( $this->path );
  102. $this->path = preg_replace( '#^/rest/v1#', '', $this->path );
  103. $allowed_methods = array( 'GET', 'POST' );
  104. $four_oh_five = false;
  105. $is_help = preg_match( '#/help/?$#i', $this->path );
  106. $matching_endpoints = array();
  107. if ( $is_help ) {
  108. $this->path = substr( rtrim( $this->path, '/' ), 0, -5 );
  109. // Show help for all matching endpoints regardless of method
  110. $methods = $allowed_methods;
  111. $find_all_matching_endpoints = true;
  112. // How deep to truncate each endpoint's path to see if it matches this help request
  113. $depth = substr_count( $this->path, '/' ) + 1;
  114. if ( false !== stripos( $this->accept, 'javascript' ) || false !== stripos( $this->accept, 'json' ) ) {
  115. $help_content_type = 'json';
  116. } else {
  117. $help_content_type = 'html';
  118. }
  119. } else {
  120. if ( in_array( $this->method, $allowed_methods ) ) {
  121. // Only serve requested method
  122. $methods = array( $this->method );
  123. $find_all_matching_endpoints = false;
  124. } else {
  125. // We don't allow this requested method - find matching endpoints and send 405
  126. $methods = $allowed_methods;
  127. $find_all_matching_endpoints = true;
  128. $four_oh_five = true;
  129. }
  130. }
  131. // Find which endpoint to serve
  132. $found = false;
  133. foreach ( $this->endpoints as $endpoint_path => $endpoints_by_method ) {
  134. foreach ( $methods as $method ) {
  135. if ( !isset( $endpoints_by_method[$method] ) ) {
  136. continue;
  137. }
  138. // Normalize
  139. $endpoint_path = untrailingslashit( $endpoint_path );
  140. if ( $is_help ) {
  141. // Truncate path at help depth
  142. $endpoint_path = join( '/', array_slice( explode( '/', $endpoint_path ), 0, $depth ) );
  143. }
  144. // Generate regular expression from sprintf()
  145. $endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path );
  146. if ( !preg_match( "#^$endpoint_path_regex\$#", $this->path, $path_pieces ) ) {
  147. // This endpoint does not match the requested path.
  148. continue;
  149. }
  150. $found = true;
  151. if ( $find_all_matching_endpoints ) {
  152. $matching_endpoints[] = array( $endpoints_by_method[$method], $path_pieces );
  153. } else {
  154. // The method parameters are now in $path_pieces
  155. $endpoint = $endpoints_by_method[$method];
  156. break 2;
  157. }
  158. }
  159. }
  160. if ( !$found ) {
  161. return $this->output( 404, '', 'text/plain' );
  162. }
  163. if ( $four_oh_five ) {
  164. $allowed_methods = array();
  165. foreach ( $matching_endpoints as $matching_endpoint ) {
  166. $allowed_methods[] = $matching_endpoint[0]->method;
  167. }
  168. header( 'Allow: ' . strtoupper( join( ',', array_unique( $allowed_methods ) ) ) );
  169. return $this->output( 405, array( 'error' => 'not_allowed', 'error_message' => 'Method not allowed' ) );
  170. }
  171. if ( $is_help ) {
  172. do_action( 'wpcom_json_api_output', 'help' );
  173. if ( 'json' === $help_content_type ) {
  174. $docs = array();
  175. foreach ( $matching_endpoints as $matching_endpoint ) {
  176. if ( !$matching_endpoint[0]->in_testing || WPCOM_JSON_API__DEBUG )
  177. $docs[] = call_user_func( array( $matching_endpoint[0], 'generate_documentation' ) );
  178. }
  179. return $this->output( 200, $docs );
  180. } else {
  181. status_header( 200 );
  182. foreach ( $matching_endpoints as $matching_endpoint ) {
  183. if ( !$matching_endpoint[0]->in_testing || WPCOM_JSON_API__DEBUG )
  184. call_user_func( array( $matching_endpoint[0], 'document' ) );
  185. }
  186. }
  187. exit;
  188. }
  189. if ( $endpoint->in_testing && !WPCOM_JSON_API__DEBUG ) {
  190. return $this->output( 404, '', 'text/plain' );
  191. }
  192. do_action( 'wpcom_json_api_output', $endpoint->stat );
  193. $response = $this->process_request( $endpoint, $path_pieces );
  194. if ( !$response ) {
  195. return $this->output( 500, '', 'text/plain' );
  196. } elseif ( is_wp_error( $response ) ) {
  197. $status_code = $response->get_error_data();
  198. if ( is_array( $status_code ) )
  199. $status_code = $status_code['status_code'];
  200. if ( !$status_code ) {
  201. $status_code = 400;
  202. }
  203. $response = array(
  204. 'error' => $response->get_error_code(),
  205. 'message' => $response->get_error_message(),
  206. );
  207. return $this->output( $status_code, $response );
  208. }
  209. return $this->output( 200, $response );
  210. }
  211. function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) {
  212. return call_user_func_array( array( $endpoint, 'callback' ), $path_pieces );
  213. }
  214. function output( $status_code, $response = null, $content_type = 'application/json' ) {
  215. if ( is_null( $response ) ) {
  216. $response = new stdClass;
  217. }
  218. if ( 'text/plain' === $content_type ) {
  219. status_header( (int) $status_code );
  220. header( 'Content-Type: text/plain' );
  221. echo $response;
  222. if ( $this->exit ) {
  223. exit;
  224. }
  225. return $content_type;
  226. }
  227. if ( isset( $this->query['http_envelope'] ) && self::is_truthy( $this->query['http_envelope'] ) ) {
  228. $response = array(
  229. 'code' => (int) $status_code,
  230. 'headers' => array(
  231. array(
  232. 'name' => 'Content-Type',
  233. 'value' => $content_type,
  234. ),
  235. ),
  236. 'body' => $response,
  237. );
  238. $status_code = 200;
  239. $content_type = 'application/json';
  240. }
  241. status_header( (int) $status_code );
  242. header( "Content-Type: $content_type" );
  243. if ( isset( $this->query['callback'] ) && is_string( $this->query['callback'] ) ) {
  244. $callback = preg_replace( '/[^a-z0-9_.]/i', '', $this->query['callback'] );
  245. } else {
  246. $callback = false;
  247. }
  248. if ( $callback ) {
  249. echo "$callback(";
  250. }
  251. echo $this->json_encode( $response );
  252. if ( $callback ) {
  253. echo ");";
  254. }
  255. if ( $this->exit ) {
  256. exit;
  257. }
  258. return $content_type;
  259. }
  260. function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) {
  261. if ( $original_scheme ) {
  262. return $url;
  263. }
  264. return preg_replace( '#^https:#', 'http:', $url );
  265. }
  266. function comment_edit_pre( $comment_content ) {
  267. return htmlspecialchars_decode( $comment_content, ENT_QUOTES );
  268. }
  269. function json_encode( $data ) {
  270. return json_encode( $data );
  271. }
  272. function ends_with( $haystack, $needle ) {
  273. return $needle === substr( $haystack, -strlen( $needle ) );
  274. }
  275. // Returns the site's blog_id in the WP.com ecosystem
  276. function get_blog_id_for_output() {
  277. return $this->token_details['blog_id'];
  278. }
  279. // Returns the site's local blog_id
  280. function get_blog_id( $blog_id ) {
  281. return $GLOBALS['blog_id'];
  282. }
  283. function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) {
  284. if ( -1 == get_option( 'blog_public' ) && !current_user_can( 'read' ) ) {
  285. return new WP_Error( 'unauthorized', 'User cannot access this private blog.', 403 );
  286. }
  287. return $blog_id;
  288. }
  289. function post_like_count( $blog_id, $post_id ) {
  290. return 0;
  291. }
  292. function get_avatar_url( $email ) {
  293. add_filter( 'pre_option_show_avatars', '__return_true', 999 );
  294. $_SERVER['HTTPS'] = 'off';
  295. $avatar_img_element = get_avatar( $email, 96, '' );
  296. if ( !$avatar_img_element || is_wp_error( $avatar_img_element ) ) {
  297. $return = '';
  298. } elseif ( !preg_match( '#src=([\'"])?(.*?)(?(1)\\1|\s)#', $avatar_img_element, $matches ) ) {
  299. $return = '';
  300. } else {
  301. $return = esc_url_raw( htmlspecialchars_decode( $matches[2] ) );
  302. }
  303. remove_filter( 'pre_option_show_avatars', '__return_true', 999 );
  304. if ( '--UNset--' === $this->_server_https ) {
  305. unset( $_SERVER['HTTPS'] );
  306. } else {
  307. $_SERVER['HTTPS'] = $this->_server_https;
  308. }
  309. return $return;
  310. }
  311. /**
  312. * Traps `wp_die()` calls and outputs a JSON response instead.
  313. * The result is always output, never returned.
  314. *
  315. * @param string|null $error_code. Call with string to start the trapping. Call with null to stop.
  316. */
  317. function trap_wp_die( $error_code = null ) {
  318. // Stop trapping
  319. if ( is_null( $error_code ) ) {
  320. $this->trapped_error = null;
  321. remove_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) );
  322. return;
  323. }
  324. // If API called via PHP, bail: don't do our custom wp_die(). Do the normal wp_die().
  325. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  326. if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) {
  327. return;
  328. }
  329. } else {
  330. if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
  331. return;
  332. }
  333. }
  334. // Start trapping
  335. $this->trapped_error = array(
  336. 'status' => 500,
  337. 'code' => $error_code,
  338. 'message' => '',
  339. );
  340. add_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) );
  341. }
  342. function wp_die_handler_callback() {
  343. return array( $this, 'wp_die_handler' );
  344. }
  345. function wp_die_handler( $message, $title = '', $args = array() ) {
  346. $args = wp_parse_args( $args, array(
  347. 'response' => 500,
  348. ) );
  349. if ( $title ) {
  350. $message = "$title: $message";
  351. }
  352. $this->trapped_error['status'] = $args['response'];
  353. $this->trapped_error['message'] = wp_kses( $message, array() );
  354. // We still want to exit so that code execution stops where it should.
  355. // Attach the JSON output to WordPress' shutdown handler
  356. add_action( 'shutdown', array( $this, 'output_trapped_error' ), 0 );
  357. exit;
  358. }
  359. function output_trapped_error() {
  360. $this->exit = false; // We're already exiting once. Don't do it twice.
  361. $this->output( $this->trapped_error['status'], (object) array(
  362. 'error' => $this->trapped_error['code'],
  363. 'message' => $this->trapped_error['message'],
  364. ) );
  365. }
  366. }