PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 6.4
Jetpack – WP Security, Backup, Speed, & Growth v6.4
12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 14.4.2 All 500 releases
← All changes | class.json-api.php +189 -737 13.2.46.4 View file →
@@ -1,260 +1,77 @@
1 -<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2 -/**
3 - * Jetpack JSON API.
4 - *
5 - * @package automattic/jetpack
6 - */
1 +<?php
7 2
8 -use Automattic\Jetpack\Status;
3 +defined( 'WPCOM_JSON_API__DEBUG' ) or define( 'WPCOM_JSON_API__DEBUG', false );
9 4
10 -if ( ! defined( 'WPCOM_JSON_API__DEBUG' ) ) {
11 - define( 'WPCOM_JSON_API__DEBUG', false );
12 -}
5 +require_once dirname( __FILE__ ) . '/sal/class.json-api-platform.php';
13 6
14 -require_once __DIR__ . '/sal/class.json-api-platform.php';
15 -
16 -/**
17 - * Jetpack JSON API.
18 - */
19 7 class WPCOM_JSON_API {
20 - /**
21 - * Static instance.
22 - *
23 - * @todo This should be private.
24 - * @var self|null
25 - */
26 - public static $self = null;
8 + static $self = null;
27 9
28 - /**
29 - * Registered endpoints.
30 - *
31 - * @var WPCOM_JSON_API_Endpoint[]
32 - */
33 10 public $endpoints = array();
34 11
35 - /**
36 - * Endpoint being processed.
37 - *
38 - * @var WPCOM_JSON_API_Endpoint
39 - */
40 - public $endpoint = null;
41 -
42 - /**
43 - * Token details.
44 - *
45 - * @var array
46 - */
47 12 public $token_details = array();
48 13
49 - /**
50 - * Request HTTP method.
51 - *
52 - * @var string
53 - */
54 14 public $method = '';
55 -
56 - /**
57 - * Request URL.
58 - *
59 - * @var string
60 - */
61 15 public $url = '';
62 -
63 - /**
64 - * Path part of the request URL.
65 - *
66 - * @var string
67 - */
68 16 public $path = '';
69 -
70 - /**
71 - * Version extracted from the request URL.
72 - *
73 - * @var string|null
74 - */
75 17 public $version = null;
76 -
77 - /**
78 - * Parsed query data.
79 - *
80 - * @var array
81 - */
82 18 public $query = array();
83 -
84 - /**
85 - * Post body, if the request is a POST.
86 - *
87 - * @var string|null
88 - */
89 19 public $post_body = null;
90 -
91 - /**
92 - * Copy of `$_FILES` if the request is a POST.
93 - *
94 - * @var null|array
95 - */
96 20 public $files = null;
97 -
98 - /**
99 - * Content type of the request.
100 - *
101 - * @var string|null
102 - */
103 21 public $content_type = null;
104 -
105 - /**
106 - * Value of `$_SERVER['HTTP_ACCEPT']`, if any
107 - *
108 - * @var string
109 - */
110 22 public $accept = '';
111 23
112 - /**
113 - * Value of `$_SERVER['HTTPS']`, or "--UNset--" if unset.
114 - *
115 - * @var string
116 - */
117 - public $_server_https; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
118 -
119 - /**
120 - * Whether to exit after serving a response.
121 - *
122 - * @var bool
123 - */
24 + public $_server_https;
124 25 public $exit = true;
125 -
126 - /**
127 - * Public API scheme.
128 - *
129 - * @var string
130 - */
131 26 public $public_api_scheme = 'https';
132 27
133 - /**
134 - * Output status code.
135 - *
136 - * @var int
137 - */
138 28 public $output_status_code = 200;
139 29
140 - /**
141 - * Trapped error.
142 - *
143 - * @var null|array
144 - */
145 30 public $trapped_error = null;
146 -
147 - /**
148 - * Whether output has been done.
149 - *
150 - * @var bool
151 - */
152 31 public $did_output = false;
153 32
154 - /**
155 - * Extra HTTP headers.
156 - *
157 - * @var string
158 - */
159 33 public $extra_headers = array();
160 34
161 35 /**
162 - * AMP source origin.
163 - *
164 - * @var string
165 - */
166 - public $amp_source_origin = null;
167 -
168 - /**
169 - * Initialize.
170 - *
171 - * @param string|null $method As for `$this->setup_inputs()`.
172 - * @param string|null $url As for `$this->setup_inputs()`.
173 - * @param string|null $post_body As for `$this->setup_inputs()`.
174 36 * @return WPCOM_JSON_API instance
175 37 */
176 - public static function init( $method = null, $url = null, $post_body = null ) {
177 - if ( ! self::$self ) {
178 - self::$self = new static( $method, $url, $post_body );
38 + static function init( $method = null, $url = null, $post_body = null ) {
39 + if ( !self::$self ) {
40 + $class = function_exists( 'get_called_class' ) ? get_called_class() : __CLASS__; // phpcs:ignore PHPCompatibility
41 + self::$self = new $class( $method, $url, $post_body );
179 42 }
180 43 return self::$self;
181 44 }
182 45
183 - /**
184 - * Add an endpoint.
185 - *
186 - * @param WPCOM_JSON_API_Endpoint $endpoint Endpoint to add.
187 - */
188 - public function add( WPCOM_JSON_API_Endpoint $endpoint ) {
189 - // @todo Determine if anything depends on this being serialized rather than e.g. JSON.
190 - // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Legacy, possibly depended on elsewhere.
191 - $path_versions = serialize(
192 - array(
193 - $endpoint->path,
194 - $endpoint->min_version,
195 - $endpoint->max_version,
196 - )
197 - );
198 - if ( ! isset( $this->endpoints[ $path_versions ] ) ) {
199 - $this->endpoints[ $path_versions ] = array();
46 + function add( WPCOM_JSON_API_Endpoint $endpoint ) {
47 + $path_versions = serialize( array (
48 + $endpoint->path,
49 + $endpoint->min_version,
50 + $endpoint->max_version,
51 + ) );
52 + if ( !isset( $this->endpoints[$path_versions] ) ) {
53 + $this->endpoints[$path_versions] = array();
200 54 }
201 - $this->endpoints[ $path_versions ][ $endpoint->method ] = $endpoint;
55 + $this->endpoints[$path_versions][$endpoint->method] = $endpoint;
202 56 }
203 57
204 - /**
205 - * Determine if a string is truthy. If it's not a string, which can happen with
206 - * not well-formed data coming from Jetpack sites, we still consider it a truthy value.
207 - *
208 - * @param mixed $value true, 1, "1", "t", and "true" (case insensitive) are truthy, everything else isn't.
209 - * @return bool
210 - */
211 - public static function is_truthy( $value ) {
212 - if ( true === $value ) {
58 + static function is_truthy( $value ) {
59 + switch ( strtolower( (string) $value ) ) {
60 + case '1' :
61 + case 't' :
62 + case 'true' :
213 63 return true;
214 64 }
215 65
216 - if ( 1 === $value ) {
217 - return true;
218 - }
219 -
220 - if ( ! is_string( $value ) ) {
221 - return false;
222 - }
223 -
224 - switch ( strtolower( (string) $value ) ) {
225 - case '1':
226 - case 't':
227 - case 'true':
228 - return true;
229 - }
230 -
231 66 return false;
232 67 }
233 68
234 - /**
235 - * Determine if a string is falsey.
236 - *
237 - * @param mixed $value false, 0, "0", "f", and "false" (case insensitive) are falsey, everything else isn't.
238 - * @return bool
239 - */
240 - public static function is_falsy( $value ) {
241 - if ( false === $value ) {
242 - return true;
243 - }
244 -
245 - if ( 0 === $value ) {
246 - return true;
247 - }
248 -
249 - if ( ! is_string( $value ) ) {
250 - return false;
251 - }
252 -
69 + static function is_falsy( $value ) {
253 70 switch ( strtolower( (string) $value ) ) {
254 - case '0':
255 - case 'f':
256 - case 'false':
71 + case '0' :
72 + case 'f' :
73 + case 'false' :
257 74 return true;
258 75 }
259 76
260 77 return false;
@@ -259,143 +76,79 @@
259 76
260 77 return false;
261 78 }
262 79
263 - /**
264 - * Constructor.
265 - *
266 - * @todo This should be private.
267 - * @param string|null $method As for `$this->setup_inputs()`.
268 - * @param string|null $url As for `$this->setup_inputs()`.
269 - * @param string|null $post_body As for `$this->setup_inputs()`.
270 - */
271 - public function __construct( $method = null, $url = null, $post_body = null ) {
272 - $this->setup_inputs( $method, $url, $post_body );
80 + function __construct() {
81 + $args = func_get_args();
82 + call_user_func_array( array( $this, 'setup_inputs' ), $args );
273 83 }
274 84
275 - /**
276 - * Setup inputs.
277 - *
278 - * @param string|null $method Request HTTP method. Fetched from `$_SERVER` if null.
279 - * @param string|null $url URL requested. Determined from `$_SERVER` if null.
280 - * @param string|null $post_body POST body. Read from `php://input` if null and method is POST.
281 - */
282 - public function setup_inputs( $method = null, $url = null, $post_body = null ) {
283 - if ( $method === null ) {
284 - $this->method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( filter_var( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : '';
85 + function setup_inputs( $method = null, $url = null, $post_body = null ) {
86 + if ( is_null( $method ) ) {
87 + $this->method = strtoupper( $_SERVER['REQUEST_METHOD'] );
285 88 } else {
286 89 $this->method = strtoupper( $method );
287 90 }
288 - if ( $url === null ) {
289 - // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sniff misses the esc_url_raw.
290 - $this->url = esc_url_raw( set_url_scheme( 'http://' . ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ) ) );
91 + if ( is_null( $url ) ) {
92 + $this->url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
291 93 } else {
292 94 $this->url = $url;
293 95 }
294 96
295 - $parsed = wp_parse_url( $this->url );
296 - if ( ! empty( $parsed['path'] ) ) {
297 - $this->path = $parsed['path'];
298 - }
97 + $parsed = parse_url( $this->url );
98 + $this->path = $parsed['path'];
299 99
300 - if ( ! empty( $parsed['query'] ) ) {
100 + if ( !empty( $parsed['query'] ) ) {
301 101 wp_parse_str( $parsed['query'], $this->query );
302 102 }
303 103
304 - if ( ! empty( $_SERVER['HTTP_ACCEPT'] ) ) {
305 - $this->accept = filter_var( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) );
104 + if ( isset( $_SERVER['HTTP_ACCEPT'] ) && $_SERVER['HTTP_ACCEPT'] ) {
105 + $this->accept = $_SERVER['HTTP_ACCEPT'];
306 106 }
307 107
308 108 if ( 'POST' === $this->method ) {
309 - if ( $post_body === null ) {
109 + if ( is_null( $post_body ) ) {
310 110 $this->post_body = file_get_contents( 'php://input' );
311 111
312 - if ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
313 - $this->content_type = filter_var( wp_unslash( $_SERVER['HTTP_CONTENT_TYPE'] ) );
314 - } elseif ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
315 - $this->content_type = filter_var( wp_unslash( $_SERVER['CONTENT_TYPE'] ) );
316 - } elseif ( isset( $this->post_body[0] ) && '{' === $this->post_body[0] ) {
112 + if ( isset( $_SERVER['HTTP_CONTENT_TYPE'] ) && $_SERVER['HTTP_CONTENT_TYPE'] ) {
113 + $this->content_type = $_SERVER['HTTP_CONTENT_TYPE'];
114 + } elseif ( isset( $_SERVER['CONTENT_TYPE'] ) && $_SERVER['CONTENT_TYPE'] ) {
115 + $this->content_type = $_SERVER['CONTENT_TYPE'] ;
116 + } elseif ( '{' === $this->post_body[0] ) {
317 117 $this->content_type = 'application/json';
318 118 } else {
319 119 $this->content_type = 'application/x-www-form-urlencoded';
320 120 }
321 121
322 - if ( str_starts_with( strtolower( $this->content_type ), 'multipart/' ) ) {
323 - // phpcs:ignore WordPress.Security.NonceVerification.Missing
324 - $this->post_body = http_build_query( stripslashes_deep( $_POST ) );
325 - $this->files = $_FILES;
122 + if ( 0 === strpos( strtolower( $this->content_type ), 'multipart/' ) ) {
123 + $this->post_body = http_build_query( stripslashes_deep( $_POST ) );
124 + $this->files = $_FILES;
326 125 $this->content_type = 'multipart/form-data';
327 126 }
328 127 } else {
329 - $this->post_body = $post_body;
330 - $this->content_type = isset( $this->post_body[0] ) && '{' === $this->post_body[0] ? 'application/json' : 'application/x-www-form-urlencoded';
128 + $this->post_body = $post_body;
129 + $this->content_type = '{' === isset( $this->post_body[0] ) && $this->post_body[0] ? 'application/json' : 'application/x-www-form-urlencoded';
331 130 }
332 131 } else {
333 - $this->post_body = null;
132 + $this->post_body = null;
334 133 $this->content_type = null;
335 134 }
336 135
337 - $this->_server_https = array_key_exists( 'HTTPS', $_SERVER ) ? filter_var( wp_unslash( $_SERVER['HTTPS'] ) ) : '--UNset--';
136 + $this->_server_https = array_key_exists( 'HTTPS', $_SERVER ) ? $_SERVER['HTTPS'] : '--UNset--';
338 137 }
339 138
340 - /**
341 - * Initialize.
342 - *
343 - * @return null|WP_Error (although this implementation always returns null)
344 - */
345 - public function initialize() {
139 + function initialize() {
346 140 $this->token_details['blog_id'] = Jetpack_Options::get_option( 'id' );
347 - return null;
348 141 }
349 142
350 - /**
351 - * Checks if the current request is authorized with a blog token.
352 - * This method is overridden by a child class in WPCOM.
353 - *
354 - * @since 9.1.0
355 - *
356 - * @param boolean|int $site_id The site id.
357 - * @return boolean
358 - */
359 - public function is_jetpack_authorized_for_site( $site_id = false ) {
360 - if ( ! $this->token_details ) {
361 - return false;
362 - }
143 + function serve( $exit = true ) {
144 + ini_set( 'display_errors', false );
363 145
364 - $token_details = (object) $this->token_details;
365 -
366 - $site_in_token = (int) $token_details->blog_id;
367 -
368 - if ( $site_in_token < 1 ) {
369 - return false;
370 - }
371 -
372 - if ( $site_id && $site_in_token !== (int) $site_id ) {
373 - return false;
374 - }
375 -
376 - if ( (int) get_current_user_id() !== 0 ) {
377 - // If Jetpack blog token is used, no logged-in user should exist.
378 - return false;
379 - }
380 -
381 - return true;
382 - }
383 -
384 - /**
385 - * Serve.
386 - *
387 - * @param bool $exit Whether to exit.
388 - * @return string|null Content type (assuming it didn't exit), or null in certain error cases.
389 - */
390 - public function serve( $exit = true ) {
391 - ini_set( 'display_errors', false ); // phpcs:ignore WordPress.PHP.IniSet.display_errors_Blacklisted
392 -
393 146 $this->exit = (bool) $exit;
394 147
395 148 // This was causing problems with Jetpack, but is necessary for wpcom
396 149 // @see https://github.com/Automattic/jetpack/pull/2603
397 - // @see r124548-wpcom .
150 + // @see r124548-wpcom
398 151 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
399 152 add_filter( 'home_url', array( $this, 'ensure_http_scheme_of_home_url' ), 10, 3 );
400 153 }
401 154
@@ -403,9 +156,9 @@
403 156
404 157 add_filter( 'comment_edit_pre', array( $this, 'comment_edit_pre' ) );
405 158
406 159 $initialization = $this->initialize();
407 - if ( 'OPTIONS' === $this->method ) {
160 + if ( 'OPTIONS' == $this->method ) {
408 161 /**
409 162 * Fires before the page output.
410 163 * Can be used to specify custom header options.
411 164 *
@@ -421,33 +174,32 @@
421 174 $this->output_error( $initialization );
422 175 return;
423 176 }
424 177
425 - // Normalize path and extract API version.
178 + // Normalize path and extract API version
426 179 $this->path = untrailingslashit( $this->path );
427 - if ( preg_match( '#^/rest/v(\d+(\.\d+)*)#', $this->path, $matches ) ) {
428 - $this->path = substr( $this->path, strlen( $matches[0] ) );
429 - $this->version = $matches[1];
430 - }
180 + preg_match( '#^/rest/v(\d+(\.\d+)*)#', $this->path, $matches );
181 + $this->path = substr( $this->path, strlen( $matches[0] ) );
182 + $this->version = $matches[1];
431 183
432 184 $allowed_methods = array( 'GET', 'POST' );
433 - $four_oh_five = false;
185 + $four_oh_five = false;
434 186
435 - $is_help = preg_match( '#/help/?$#i', $this->path );
187 + $is_help = preg_match( '#/help/?$#i', $this->path );
436 188 $matching_endpoints = array();
437 189
438 190 if ( $is_help ) {
439 191 $origin = get_http_origin();
440 192
441 - if ( ! empty( $origin ) && 'GET' === $this->method ) {
193 + if ( !empty( $origin ) && 'GET' == $this->method ) {
442 194 header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
443 195 }
444 196
445 197 $this->path = substr( rtrim( $this->path, '/' ), 0, -5 );
446 - // Show help for all matching endpoints regardless of method.
447 - $methods = $allowed_methods;
198 + // Show help for all matching endpoints regardless of method
199 + $methods = $allowed_methods;
448 200 $find_all_matching_endpoints = true;
449 - // How deep to truncate each endpoint's path to see if it matches this help request.
201 + // How deep to truncate each endpoint's path to see if it matches this help request
450 202 $depth = substr_count( $this->path, '/' ) + 1;
451 203 if ( false !== stripos( $this->accept, 'javascript' ) || false !== stripos( $this->accept, 'json' ) ) {
452 204 $help_content_type = 'json';
453 205 } else {
@@ -452,50 +204,50 @@
452 204 $help_content_type = 'json';
453 205 } else {
454 206 $help_content_type = 'html';
455 207 }
456 - } elseif ( in_array( $this->method, $allowed_methods, true ) ) {
457 - // Only serve requested method.
458 - $methods = array( $this->method );
459 - $find_all_matching_endpoints = false;
460 208 } else {
461 - // We don't allow this requested method - find matching endpoints and send 405.
462 - $methods = $allowed_methods;
463 - $find_all_matching_endpoints = true;
464 - $four_oh_five = true;
209 + if ( in_array( $this->method, $allowed_methods ) ) {
210 + // Only serve requested method
211 + $methods = array( $this->method );
212 + $find_all_matching_endpoints = false;
213 + } else {
214 + // We don't allow this requested method - find matching endpoints and send 405
215 + $methods = $allowed_methods;
216 + $find_all_matching_endpoints = true;
217 + $four_oh_five = true;
218 + }
465 219 }
466 220
467 - // Find which endpoint to serve.
221 + // Find which endpoint to serve
468 222 $found = false;
469 223 foreach ( $this->endpoints as $endpoint_path_versions => $endpoints_by_method ) {
470 - // @todo Determine if anything depends on this being serialized rather than e.g. JSON.
471 - // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Legacy, possibly depended on elsewhere.
472 224 $endpoint_path_versions = unserialize( $endpoint_path_versions );
473 - $endpoint_path = $endpoint_path_versions[0];
474 - $endpoint_min_version = $endpoint_path_versions[1];
475 - $endpoint_max_version = $endpoint_path_versions[2];
225 + $endpoint_path = $endpoint_path_versions[0];
226 + $endpoint_min_version = $endpoint_path_versions[1];
227 + $endpoint_max_version = $endpoint_path_versions[2];
476 228
477 - // Make sure max_version is not less than min_version.
229 + // Make sure max_version is not less than min_version
478 230 if ( version_compare( $endpoint_max_version, $endpoint_min_version, '<' ) ) {
479 231 $endpoint_max_version = $endpoint_min_version;
480 232 }
481 233
482 234 foreach ( $methods as $method ) {
483 - if ( ! isset( $endpoints_by_method[ $method ] ) ) {
235 + if ( !isset( $endpoints_by_method[$method] ) ) {
484 236 continue;
485 237 }
486 238
487 - // Normalize.
239 + // Normalize
488 240 $endpoint_path = untrailingslashit( $endpoint_path );
489 241 if ( $is_help ) {
490 - // Truncate path at help depth.
491 - $endpoint_path = implode( '/', array_slice( explode( '/', $endpoint_path ), 0, $depth ) );
242 + // Truncate path at help depth
243 + $endpoint_path = join( '/', array_slice( explode( '/', $endpoint_path ), 0, $depth ) );
492 244 }
493 245
494 - // Generate regular expression from sprintf().
246 + // Generate regular expression from sprintf()
495 247 $endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path );
496 248
497 - if ( ! preg_match( "#^$endpoint_path_regex\$#", $this->path, $path_pieces ) ) {
249 + if ( !preg_match( "#^$endpoint_path_regex\$#", $this->path, $path_pieces ) ) {
498 250 // This endpoint does not match the requested path.
499 251 continue;
500 252 }
501 253
@@ -506,18 +258,18 @@
506 258
507 259 $found = true;
508 260
509 261 if ( $find_all_matching_endpoints ) {
510 - $matching_endpoints[] = array( $endpoints_by_method[ $method ], $path_pieces );
262 + $matching_endpoints[] = array( $endpoints_by_method[$method], $path_pieces );
511 263 } else {
512 - // The method parameters are now in $path_pieces.
513 - $endpoint = $endpoints_by_method[ $method ];
264 + // The method parameters are now in $path_pieces
265 + $endpoint = $endpoints_by_method[$method];
514 266 break 2;
515 267 }
516 268 }
517 269 }
518 270
519 - if ( ! $found ) {
271 + if ( !$found ) {
520 272 return $this->output( 404, '', 'text/plain' );
521 273 }
522 274
523 275 if ( $four_oh_five ) {
@@ -525,16 +277,10 @@
525 277 foreach ( $matching_endpoints as $matching_endpoint ) {
526 278 $allowed_methods[] = $matching_endpoint[0]->method;
527 279 }
528 280
529 - header( 'Allow: ' . strtoupper( implode( ',', array_unique( $allowed_methods ) ) ) );
530 - return $this->output(
531 - 405,
532 - array(
533 - 'error' => 'not_allowed',
534 - 'error_message' => 'Method not allowed',
535 - )
536 - );
281 + header( 'Allow: ' . strtoupper( join( ',', array_unique( $allowed_methods ) ) ) );
282 + return $this->output( 405, array( 'error' => 'not_allowed', 'error_message' => 'Method not allowed' ) );
537 283 }
538 284
539 285 if ( $is_help ) {
540 286 /**
@@ -548,25 +294,23 @@
548 294 $proxied = function_exists( 'wpcom_is_proxied_request' ) ? wpcom_is_proxied_request() : false;
549 295 if ( 'json' === $help_content_type ) {
550 296 $docs = array();
551 297 foreach ( $matching_endpoints as $matching_endpoint ) {
552 - if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG ) {
298 + if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG )
553 299 $docs[] = call_user_func( array( $matching_endpoint[0], 'generate_documentation' ) );
554 - }
555 300 }
556 301 return $this->output( 200, $docs );
557 302 } else {
558 303 status_header( 200 );
559 304 foreach ( $matching_endpoints as $matching_endpoint ) {
560 - if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG ) {
305 + if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG )
561 306 call_user_func( array( $matching_endpoint[0], 'document' ) );
562 - }
563 307 }
564 308 }
565 309 exit;
566 310 }
567 311
568 - if ( $endpoint->in_testing && ! WPCOM_JSON_API__DEBUG ) {
312 + if ( $endpoint->in_testing && !WPCOM_JSON_API__DEBUG ) {
569 313 return $this->output( 404, '', 'text/plain' );
570 314 }
571 315
572 316 /** This action is documented in class.json-api.php */
@@ -573,9 +317,9 @@
573 317 do_action( 'wpcom_json_api_output', $endpoint->stat );
574 318
575 319 $response = $this->process_request( $endpoint, $path_pieces );
576 320
577 - if ( ! $response && ! is_array( $response ) ) {
321 + if ( !$response && !is_array( $response ) ) {
578 322 return $this->output( 500, '', 'text/plain' );
579 323 } elseif ( is_wp_error( $response ) ) {
580 324 return $this->output_error( $response );
581 325 }
@@ -585,35 +329,20 @@
585 329
586 330 return $this->output( $output_status_code, $response, 'application/json', $this->extra_headers );
587 331 }
588 332
589 - /**
590 - * Process a request.
591 - *
592 - * @param WPCOM_JSON_API_Endpoint $endpoint Endpoint.
593 - * @param array $path_pieces Path pieces.
594 - * @return array|WP_Error Return value from the endpoint's callback.
595 - */
596 - public function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) {
333 + function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) {
597 334 $this->endpoint = $endpoint;
598 335 return call_user_func_array( array( $endpoint, 'callback' ), $path_pieces );
599 336 }
600 337
601 - /**
602 - * Output a response or error without exiting.
603 - *
604 - * @param int $status_code HTTP status code.
605 - * @param mixed $response Response data.
606 - * @param string $content_type Content type of the response.
607 - */
608 - public function output_early( $status_code, $response = null, $content_type = 'application/json' ) {
609 - $exit = $this->exit;
338 + function output_early( $status_code, $response = null, $content_type = 'application/json' ) {
339 + $exit = $this->exit;
610 340 $this->exit = false;
611 - if ( is_wp_error( $response ) ) {
341 + if ( is_wp_error( $response ) )
612 342 $this->output_error( $response );
613 - } else {
343 + else
614 344 $this->output( $status_code, $response, $content_type );
615 - }
616 345 $this->exit = $exit;
617 346 if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
618 347 $this->finish_request();
619 348 }
@@ -618,61 +347,36 @@
618 347 $this->finish_request();
619 348 }
620 349 }
621 350
622 - /**
623 - * Set output status code.
624 - *
625 - * @param int $code HTTP status code.
626 - */
627 - public function set_output_status_code( $code = 200 ) {
351 + function set_output_status_code( $code = 200 ) {
628 352 $this->output_status_code = $code;
629 353 }
630 354
631 - /**
632 - * Output a response.
633 - *
634 - * @param int $status_code HTTP status code.
635 - * @param mixed $response Response data.
636 - * @param string $content_type Content type of the response.
637 - * @param array $extra Additional HTTP headers.
638 - * @return string Content type (assuming it didn't exit).
639 - */
640 - public function output( $status_code, $response = null, $content_type = 'application/json', $extra = array() ) {
641 - $status_code = (int) $status_code;
642 -
643 - // In case output() was called before the callback returned.
355 + function output( $status_code, $response = null, $content_type = 'application/json', $extra = array() ) {
356 + // In case output() was called before the callback returned
644 357 if ( $this->did_output ) {
645 - if ( $this->exit ) {
358 + if ( $this->exit )
646 359 exit;
647 - }
648 360 return $content_type;
649 361 }
650 362 $this->did_output = true;
651 363
652 364 // 400s and 404s are allowed for all origins
653 - if ( 404 === $status_code || 400 === $status_code ) {
365 + if ( 404 == $status_code || 400 == $status_code )
654 366 header( 'Access-Control-Allow-Origin: *' );
655 - }
656 367
657 - /* Add headers for form submission from <amp-form/> */
658 - if ( $this->amp_source_origin ) {
659 - header( 'Access-Control-Allow-Origin: ' . wp_unslash( $this->amp_source_origin ) );
660 - header( 'Access-Control-Allow-Credentials: true' );
368 + if ( is_null( $response ) ) {
369 + $response = new stdClass;
661 370 }
662 371
663 - if ( $response === null ) {
664 - $response = new stdClass();
665 - }
666 -
667 - if ( 'text/plain' === $content_type ||
668 - 'text/html' === $content_type ) {
372 + if ( 'text/plain' === $content_type ) {
669 373 status_header( (int) $status_code );
670 - header( 'Content-Type: ' . $content_type );
671 - foreach ( $extra as $key => $value ) {
374 + header( 'Content-Type: text/plain' );
375 + foreach( $extra as $key => $value ) {
672 376 header( "$key: $value" );
673 377 }
674 - echo $response; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
378 + echo $response;
675 379 if ( $this->exit ) {
676 380 exit;
677 381 }
678 382
@@ -683,26 +387,23 @@
683 387
684 388 if ( isset( $this->query['http_envelope'] ) && self::is_truthy( $this->query['http_envelope'] ) ) {
685 389 $headers = array(
686 390 array(
687 - 'name' => 'Content-Type',
391 + 'name' => 'Content-Type',
688 392 'value' => $content_type,
689 - ),
393 + )
690 394 );
691 395
692 - foreach ( $extra as $key => $value ) {
693 - $headers[] = array(
694 - 'name' => $key,
695 - 'value' => $value,
696 - );
396 + foreach( $extra as $key => $value ) {
397 + $headers[] = array( 'name' => $key, 'value' => $value );
697 398 }
698 399
699 - $response = array(
700 - 'code' => (int) $status_code,
400 + $response = array(
401 + 'code' => (int) $status_code,
701 402 'headers' => $headers,
702 - 'body' => $response,
403 + 'body' => $response,
703 404 );
704 - $status_code = 200;
405 + $status_code = 200;
705 406 $content_type = 'application/json';
706 407 }
707 408
708 409 status_header( (int) $status_code );
@@ -715,15 +416,15 @@
715 416
716 417 if ( $callback ) {
717 418 // Mitigate Rosetta Flash [1] by setting the Content-Type-Options: nosniff header
718 419 // and by prepending the JSONP response with a JS comment.
719 - // [1] <https://blog.miki.it/2014/7/8/abusing-jsonp-with-rosetta-flash/index.html>.
720 - echo "/**/$callback("; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is JSONP output, not HTML.
420 + // [1] http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
421 + echo "/**/$callback(";
721 422
722 423 }
723 - echo $this->json_encode( $response ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is JSON or JSONP output, not HTML.
424 + echo $this->json_encode( $response );
724 425 if ( $callback ) {
725 - echo ');';
426 + echo ");";
726 427 }
727 428
728 429 if ( $this->exit ) {
729 430 exit;
@@ -731,23 +432,17 @@
731 432
732 433 return $content_type;
733 434 }
734 435
735 - /**
736 - * Serialize an error.
737 - *
738 - * @param WP_Error $error Error.
739 - * @return array with 'status_code' and 'errors' data.
740 - */
741 - public static function serializable_error( $error ) {
436 + public static function serializable_error ( $error ) {
742 437
743 438 $status_code = $error->get_error_data();
744 439
745 - if ( is_array( $status_code ) && isset( $status_code['status_code'] ) ) {
440 + if ( is_array( $status_code ) ) {
746 441 $status_code = $status_code['status_code'];
747 442 }
748 443
749 - if ( ! $status_code ) {
444 + if ( !$status_code ) {
750 445 $status_code = 400;
751 446 }
752 447 $response = array(
753 448 'error' => $error->get_error_code(),
@@ -753,41 +448,27 @@
753 448 'error' => $error->get_error_code(),
754 449 'message' => $error->get_error_message(),
755 450 );
756 451
757 - $additional_data = $error->get_error_data( 'additional_data' );
758 - if ( $additional_data ) {
452 + if ( $additional_data = $error->get_error_data( 'additional_data' ) ) {
759 453 $response['data'] = $additional_data;
760 454 }
761 455
762 456 return array(
763 457 'status_code' => $status_code,
764 - 'errors' => $response,
458 + 'errors' => $response
765 459 );
766 460 }
767 461
768 - /**
769 - * Output an error.
770 - *
771 - * @param WP_Error $error Error.
772 - * @return string Content type (assuming it didn't exit).
773 - */
774 - public function output_error( $error ) {
775 - $error_response = static::serializable_error( $error );
462 + function output_error( $error ) {
463 + $error_response = $this->serializable_error( $error );
776 464
777 - return $this->output( $error_response['status_code'], $error_response['errors'] );
465 + return $this->output( $error_response[ 'status_code'], $error_response['errors'] );
778 466 }
779 467
780 - /**
781 - * Filter fields in a response.
782 - *
783 - * @param array|object $response Response.
784 - * @return array|object Filtered response.
785 - */
786 - public function filter_fields( $response ) {
787 - if ( empty( $this->query['fields'] ) || ( is_array( $response ) && ! empty( $response['error'] ) ) || ! empty( $this->endpoint->custom_fields_filtering ) ) {
468 + function filter_fields( $response ) {
469 + if ( empty( $this->query['fields'] ) || ( is_array( $response ) && ! empty( $response['error'] ) ) || ! empty( $this->endpoint->custom_fields_filtering ) )
788 470 return $response;
789 - }
790 471
791 472 $fields = array_map( 'trim', explode( ',', $this->query['fields'] ) );
792 473
793 474 if ( is_object( $response ) ) {
@@ -815,16 +496,14 @@
815 496 'users',
816 497 );
817 498
818 499 foreach ( $keys_to_filter as $key_to_filter ) {
819 - if ( ! isset( $response[ $key_to_filter ] ) || $has_filtered ) {
500 + if ( ! isset( $response[ $key_to_filter ] ) || $has_filtered )
820 501 continue;
821 - }
822 502
823 503 foreach ( $response[ $key_to_filter ] as $key => $values ) {
824 504 if ( is_object( $values ) ) {
825 505 if ( is_object( $response[ $key_to_filter ] ) ) {
826 - // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.Found -- False positive.
827 506 $response[ $key_to_filter ]->$key = (object) array_intersect_key( ( (array) $values ), array_flip( $fields ) );
828 507 } elseif ( is_array( $response[ $key_to_filter ] ) ) {
829 508 $response[ $key_to_filter ][ $key ] = (object) array_intersect_key( ( (array) $values ), array_flip( $fields ) );
830 509 }
@@ -839,9 +518,9 @@
839 518
840 519 if ( ! $has_filtered ) {
841 520 if ( is_object( $response ) ) {
842 521 $response = (object) array_intersect_key( (array) $response, array_flip( $fields ) );
843 - } elseif ( is_array( $response ) ) {
522 + } else if ( is_array( $response ) ) {
844 523 $response = array_intersect_key( $response, array_flip( $fields ) );
845 524 }
846 525 }
847 526
@@ -847,19 +526,9 @@
847 526
848 527 return $response;
849 528 }
850 529
851 - /**
852 - * Filter for `home_url`.
853 - *
854 - * If `$original_scheme` is null, turns an https URL to http.
855 - *
856 - * @param string $url The complete home URL including scheme and path.
857 - * @param string $path Path relative to the home URL. Blank string if no path is specified.
858 - * @param string|null $original_scheme Scheme to give the home URL context. Accepts 'http', 'https', 'relative', 'rest', or null.
859 - * @return string URL.
860 - */
861 - public function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) {
530 + function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) {
862 531 if ( $original_scheme ) {
863 532 return $url;
864 533 }
865 534
@@ -865,78 +534,36 @@
865 534
866 535 return preg_replace( '#^https:#', 'http:', $url );
867 536 }
868 537
869 - /**
870 - * Decode HTML special characters in comment content.
871 - *
872 - * @param string $comment_content Comment content.
873 - * @return string
874 - */
875 - public function comment_edit_pre( $comment_content ) {
538 + function comment_edit_pre( $comment_content ) {
876 539 return htmlspecialchars_decode( $comment_content, ENT_QUOTES );
877 540 }
878 541
879 - /**
880 - * JSON encode.
881 - *
882 - * @param mixed $data Data.
883 - * @return string|false
884 - */
885 - public function json_encode( $data ) {
886 - return wp_json_encode( $data );
542 + function json_encode( $data ) {
543 + return json_encode( $data );
887 544 }
888 545
889 - /**
890 - * Test if a string ends with a string.
891 - *
892 - * @param string $haystack String to check.
893 - * @param string $needle Suffix to check.
894 - * @return bool
895 - */
896 - public function ends_with( $haystack, $needle ) {
897 - return substr( $haystack, -strlen( $needle ) ) === $needle;
546 + function ends_with( $haystack, $needle ) {
547 + return $needle === substr( $haystack, -strlen( $needle ) );
898 548 }
899 549
900 - /**
901 - * Returns the site's blog_id in the WP.com ecosystem
902 - *
903 - * @return int
904 - */
905 - public function get_blog_id_for_output() {
550 + // Returns the site's blog_id in the WP.com ecosystem
551 + function get_blog_id_for_output() {
906 552 return $this->token_details['blog_id'];
907 553 }
908 554
909 - /**
910 - * Returns the site's local blog_id.
911 - *
912 - * @param int $blog_id Blog ID.
913 - * @return int
914 - */
915 - public function get_blog_id( $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
555 + // Returns the site's local blog_id
556 + function get_blog_id( $blog_id ) {
916 557 return $GLOBALS['blog_id'];
917 558 }
918 559
919 - /**
920 - * Switch to blog and validate user.
921 - *
922 - * @param int $blog_id Blog ID.
923 - * @param bool $verify_token_for_blog Whether to verify the token.
924 - * @return int Blog ID.
925 - */
926 - public function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
560 + function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) {
927 561 if ( $this->is_restricted_blog( $blog_id ) ) {
928 562 return new WP_Error( 'unauthorized', 'User cannot access this restricted blog', 403 );
929 563 }
930 - /**
931 - * If this is a private site we check for 2 things:
932 - * 1. In case of user based authentication, we need to check if the logged-in user has the 'read' capability.
933 - * 2. In case of site based authentication, make sure the endpoint accepts it.
934 - */
935 - if ( ( new Status() )->is_private_site() &&
936 - ! current_user_can( 'read' ) &&
937 - ! $this->endpoint->accepts_site_based_authentication()
938 - ) {
564 +
565 + if ( -1 == get_option( 'blog_public' ) && !current_user_can( 'read' ) ) {
939 566 return new WP_Error( 'unauthorized', 'User cannot access this private blog.', 403 );
940 567 }
941 568
942 569 return $blog_id;
@@ -941,15 +568,10 @@
941 568
942 569 return $blog_id;
943 570 }
944 571
945 - /**
946 - * Returns true if the specified blog ID is a restricted blog
947 - *
948 - * @param int $blog_id Blog ID.
949 - * @return bool
950 - */
951 - public function is_restricted_blog( $blog_id ) {
572 + // Returns true if the specified blog ID is a restricted blog
573 + function is_restricted_blog( $blog_id ) {
952 574 /**
953 575 * Filters all REST API access and return a 403 unauthorized response for all Restricted blog IDs.
954 576 *
955 577 * @module json-api
@@ -958,73 +580,32 @@
958 580 *
959 581 * @param array $array Array of Blog IDs.
960 582 */
961 583 $restricted_blog_ids = apply_filters( 'wpcom_json_api_restricted_blog_ids', array() );
962 - return true === in_array( $blog_id, $restricted_blog_ids ); // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- I don't trust filters to return the right types.
584 + return true === in_array( $blog_id, $restricted_blog_ids );
963 585 }
964 586
965 - /**
966 - * Post like count.
967 - *
968 - * @param int $blog_id Blog ID.
969 - * @param int $post_id Post ID.
970 - * @return int
971 - */
972 - public function post_like_count( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
587 + function post_like_count( $blog_id, $post_id ) {
973 588 return 0;
974 589 }
975 590
976 - /**
977 - * Is liked?
978 - *
979 - * @param int $blog_id Blog ID.
980 - * @param int $post_id Post ID.
981 - * @return bool
982 - */
983 - public function is_liked( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
591 + function is_liked( $blog_id, $post_id ) {
984 592 return false;
985 593 }
986 594
987 - /**
988 - * Is reblogged?
989 - *
990 - * @param int $blog_id Blog ID.
991 - * @param int $post_id Post ID.
992 - * @return bool
993 - */
994 - public function is_reblogged( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
595 + function is_reblogged( $blog_id, $post_id ) {
995 596 return false;
996 597 }
997 598
998 - /**
999 - * Is following?
1000 - *
1001 - * @param int $blog_id Blog ID.
1002 - * @return bool
1003 - */
1004 - public function is_following( $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
599 + function is_following( $blog_id ) {
1005 600 return false;
1006 601 }
1007 602
1008 - /**
1009 - * Add global ID.
1010 - *
1011 - * @param int $blog_id Blog ID.
1012 - * @param int $post_id Post ID.
1013 - * @return string
1014 - */
1015 - public function add_global_ID( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable, WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
603 + function add_global_ID( $blog_id, $post_id ) {
1016 604 return '';
1017 605 }
1018 606
1019 - /**
1020 - * Get avatar URL.
1021 - *
1022 - * @param string $email Email.
1023 - * @param array $avatar_size Args for `get_avatar_url()`.
1024 - * @return string|false
1025 - */
1026 - public function get_avatar_url( $email, $avatar_size = null ) {
607 + function get_avatar_url( $email, $avatar_size = null ) {
1027 608 if ( function_exists( 'wpcom_get_avatar_url' ) ) {
1028 609 return null === $avatar_size
1029 610 ? wpcom_get_avatar_url( $email )
1030 611 : wpcom_get_avatar_url( $email, $avatar_size );
@@ -1035,125 +616,19 @@
1035 616 }
1036 617 }
1037 618
1038 619 /**
1039 - * Counts the number of comments on a site, including certain comment types.
1040 - *
1041 - * @param int $post_id Post ID.
1042 - * @return array Array of counts, matching the output of https://developer.wordpress.org/reference/functions/get_comment_count/.
1043 - */
1044 - public function wp_count_comments( $post_id ) {
1045 - global $wpdb;
1046 - if ( 0 !== $post_id ) {
1047 - return wp_count_comments( $post_id );
1048 - }
1049 -
1050 - $counts = array(
1051 - 'total_comments' => 0,
1052 - 'all' => 0,
1053 - );
1054 -
1055 - /**
1056 - * Exclude certain comment types from comment counts in the REST API.
1057 - *
1058 - * @since 6.9.0
1059 - * @deprecated 11.1
1060 - * @module json-api
1061 - *
1062 - * @param array Array of comment types to exclude (default: 'order_note', 'webhook_delivery', 'review', 'action_log')
1063 - */
1064 - $exclude = apply_filters_deprecated( 'jetpack_api_exclude_comment_types_count', array( 'order_note', 'webhook_delivery', 'review', 'action_log' ), 'jetpack-11.1', 'jetpack_api_include_comment_types_count' ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1065 -
1066 - /**
1067 - * Include certain comment types in comment counts in the REST API.
1068 - * Note: the default array of comment types includes an empty string,
1069 - * to support comments posted before WP 5.5, that used an empty string as comment type.
1070 - *
1071 - * @since 11.1
1072 - * @module json-api
1073 - *
1074 - * @param array Array of comment types to include (default: 'comment', 'pingback', 'trackback')
1075 - */
1076 - $include = apply_filters(
1077 - 'jetpack_api_include_comment_types_count',
1078 - array( 'comment', 'pingback', 'trackback', '' )
1079 - );
1080 -
1081 - if ( empty( $include ) ) {
1082 - return wp_count_comments( $post_id );
1083 - }
1084 -
1085 - array_walk( $include, 'esc_sql' );
1086 - $where = sprintf(
1087 - "WHERE comment_type IN ( '%s' )",
1088 - implode( "','", $include )
1089 - );
1090 -
1091 - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- `$where` is built with escaping just above.
1092 - $count = $wpdb->get_results(
1093 - "SELECT comment_approved, COUNT(*) AS num_comments
1094 - FROM $wpdb->comments
1095 - {$where}
1096 - GROUP BY comment_approved
1097 - "
1098 - );
1099 - // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1100 -
1101 - $approved = array(
1102 - '0' => 'moderated',
1103 - '1' => 'approved',
1104 - 'spam' => 'spam',
1105 - 'trash' => 'trash',
1106 - 'post-trashed' => 'post-trashed',
1107 - );
1108 -
1109 - // <https://developer.wordpress.org/reference/functions/get_comment_count/#source>
1110 - foreach ( $count as $row ) {
1111 - if ( ! in_array( $row->comment_approved, array( 'post-trashed', 'trash', 'spam' ), true ) ) {
1112 - $counts['all'] += $row->num_comments;
1113 - $counts['total_comments'] += $row->num_comments;
1114 - } elseif ( ! in_array( $row->comment_approved, array( 'post-trashed', 'trash' ), true ) ) {
1115 - $counts['total_comments'] += $row->num_comments;
1116 - }
1117 - if ( isset( $approved[ $row->comment_approved ] ) ) {
1118 - $counts[ $approved[ $row->comment_approved ] ] = $row->num_comments;
1119 - }
1120 - }
1121 -
1122 - foreach ( $approved as $key ) {
1123 - if ( empty( $counts[ $key ] ) ) {
1124 - $counts[ $key ] = 0;
1125 - }
1126 - }
1127 -
1128 - $counts = (object) $counts;
1129 -
1130 - return $counts;
1131 - }
1132 -
1133 - /**
1134 - * Traps `wp_die()` calls and outputs a JSON response instead.
620 + * traps `wp_die()` calls and outputs a JSON response instead.
1135 621 * The result is always output, never returned.
1136 622 *
1137 623 * @param string|null $error_code Call with string to start the trapping. Call with null to stop.
1138 624 * @param int $http_status HTTP status code, 400 by default.
1139 625 */
1140 - public function trap_wp_die( $error_code = null, $http_status = 400 ) {
1141 - // Determine the filter name; based on the conditionals inside the wp_die function.
1142 - if ( wp_is_json_request() ) {
1143 - $die_handler = 'wp_die_json_handler';
1144 - } elseif ( wp_is_jsonp_request() ) {
1145 - $die_handler = 'wp_die_jsonp_handler';
1146 - } elseif ( wp_is_xml_request() ) {
1147 - $die_handler = 'wp_die_xml_handler';
1148 - } else {
1149 - $die_handler = 'wp_die_handler';
1150 - }
1151 -
1152 - if ( $error_code === null ) {
626 + function trap_wp_die( $error_code = null, $http_status = 400 ) {
627 + if ( is_null( $error_code ) ) {
1153 628 $this->trapped_error = null;
1154 - // Stop trapping.
1155 - remove_filter( $die_handler, array( $this, 'wp_die_handler_callback' ) );
629 + // Stop trapping
630 + remove_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) );
1156 631 return;
1157 632 }
1158 633
1159 634 // If API called via PHP, bail: don't do our custom wp_die(). Do the normal wp_die().
@@ -1160,10 +635,12 @@
1160 635 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1161 636 if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) {
1162 637 return;
1163 638 }
1164 - } elseif ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
1165 - return;
639 + } else {
640 + if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
641 + return;
642 + }
1166 643 }
1167 644
1168 645 $this->trapped_error = array(
1169 646 'status' => $http_status,
@@ -1169,39 +646,24 @@
1169 646 'status' => $http_status,
1170 647 'code' => $error_code,
1171 648 'message' => '',
1172 649 );
1173 - // Start trapping.
1174 - add_filter( $die_handler, array( $this, 'wp_die_handler_callback' ) );
650 + // Start trapping
651 + add_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) );
1175 652 }
1176 653
1177 - /**
1178 - * Filter function for `wp_die_handler` and similar filters.
1179 - *
1180 - * @return callable
1181 - */
1182 - public function wp_die_handler_callback() {
654 + function wp_die_handler_callback() {
1183 655 return array( $this, 'wp_die_handler' );
1184 656 }
1185 657
1186 - /**
1187 - * Handler for `wp_die` calls.
1188 - *
1189 - * @param string|WP_Error $message As for `wp_die()`.
1190 - * @param string|int $title As for `wp_die()`.
1191 - * @param string|array|int $args As for `wp_die()`.
1192 - */
1193 - public function wp_die_handler( $message, $title = '', $args = array() ) {
658 + function wp_die_handler( $message, $title = '', $args = array() ) {
1194 659 // Allow wp_die calls to override HTTP status code...
1195 - $args = wp_parse_args(
1196 - $args,
1197 - array(
1198 - 'response' => $this->trapped_error['status'],
1199 - )
1200 - );
660 + $args = wp_parse_args( $args, array(
661 + 'response' => $this->trapped_error['status'],
662 + ) );
1201 663
1202 - // ... unless it's 500
1203 - if ( 500 !== (int) $args['response'] ) {
664 + // ... unless it's 500 ( see http://wp.me/pMz3w-5VV )
665 + if ( (int) $args['response'] !== 500 ) {
1204 666 $this->trapped_error['status'] = $args['response'];
1205 667 }
1206 668
1207 669 if ( $title ) {
@@ -1210,12 +672,12 @@
1210 672
1211 673 $this->trapped_error['message'] = wp_kses( $message, array() );
1212 674
1213 675 switch ( $this->trapped_error['code'] ) {
1214 - case 'comment_failure':
676 + case 'comment_failure' :
1215 677 if ( did_action( 'comment_duplicate_trigger' ) ) {
1216 678 $this->trapped_error['code'] = 'comment_duplicate';
1217 - } elseif ( did_action( 'comment_flood_trigger' ) ) {
679 + } else if ( did_action( 'comment_flood_trigger' ) ) {
1218 680 $this->trapped_error['code'] = 'comment_flood';
1219 681 }
1220 682 break;
1221 683 }
@@ -1220,32 +682,22 @@
1220 682 break;
1221 683 }
1222 684
1223 685 // We still want to exit so that code execution stops where it should.
1224 - // Attach the JSON output to the WordPress shutdown handler.
686 + // Attach the JSON output to the WordPress shutdown handler
1225 687 add_action( 'shutdown', array( $this, 'output_trapped_error' ), 0 );
1226 688 exit;
1227 689 }
1228 690
1229 - /**
1230 - * Output the trapped error.
1231 - */
1232 - public function output_trapped_error() {
691 + function output_trapped_error() {
1233 692 $this->exit = false; // We're already exiting once. Don't do it twice.
1234 - $this->output(
1235 - $this->trapped_error['status'],
1236 - (object) array(
1237 - 'error' => $this->trapped_error['code'],
1238 - 'message' => $this->trapped_error['message'],
1239 - )
1240 - );
693 + $this->output( $this->trapped_error['status'], (object) array(
694 + 'error' => $this->trapped_error['code'],
695 + 'message' => $this->trapped_error['message'],
696 + ) );
1241 697 }
1242 698
1243 - /**
1244 - * Finish the request.
1245 - */
1246 - public function finish_request() {
1247 - if ( function_exists( 'fastcgi_finish_request' ) ) {
699 + function finish_request() {
700 + if ( function_exists( 'fastcgi_finish_request' ) )
1248 701 return fastcgi_finish_request();
1249 - }
1250 702 }
1251 703 }