forked from WP-API/WP-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.php
623 lines (531 loc) · 18.2 KB
/
plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
<?php
/**
* Plugin Name: JSON REST API
* Description: JSON-based REST API for WordPress, developed as part of GSoC 2013.
* Author: Ryan McCue
* Author URI: http://ryanmccue.info/
* Version: 1.1.1
* Plugin URI: https://github.com/rmccue/WP-API
*/
/**
* Version number for our API.
*
* @var string
*/
define( 'JSON_API_VERSION', '1.1.1' );
/**
* Include our files for the API.
*/
include_once( dirname( __FILE__ ) . '/lib/class-jsonserializable.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-datetime.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-responsehandler.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-server.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-responseinterface.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-response.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-posts.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-users.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-customposttype.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-pages.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-media.php' );
include_once( dirname( __FILE__ ) . '/lib/class-wp-json-taxonomies.php' );
/**
* Register rewrite rules for the API.
*
* @global WP $wp Current WordPress environment instance.
*/
function json_api_init() {
json_api_register_rewrites();
global $wp;
$wp->add_query_var( 'json_route' );
}
add_action( 'init', 'json_api_init' );
/**
* Add rewrite rules.
*/
function json_api_register_rewrites() {
add_rewrite_rule( '^' . json_get_url_prefix() . '/?$','index.php?json_route=/','top' );
add_rewrite_rule( '^' . json_get_url_prefix() . '(.*)?','index.php?json_route=$matches[1]','top' );
}
/**
* Determine if the rewrite rules should be flushed.
*/
function json_api_maybe_flush_rewrites() {
$version = get_option( 'json_api_plugin_version', null );
if ( empty( $version ) || $version !== JSON_API_VERSION ) {
flush_rewrite_rules();
update_option( 'json_api_plugin_version', JSON_API_VERSION );
}
}
add_action( 'init', 'json_api_maybe_flush_rewrites', 999 );
/**
* Register the default JSON API filters.
*
* @internal This will live in default-filters.php
*
* @global WP_JSON_Posts $wp_json_posts
* @global WP_JSON_Pages $wp_json_pages
* @global WP_JSON_Media $wp_json_media
* @global WP_JSON_Taxonomies $wp_json_taxonomies
*
* @param WP_JSON_ResponseHandler $server Server object.
*/
function json_api_default_filters( $server ) {
global $wp_json_posts, $wp_json_pages, $wp_json_media, $wp_json_taxonomies;
// Posts.
$wp_json_posts = new WP_JSON_Posts( $server );
add_filter( 'json_endpoints', array( $wp_json_posts, 'register_routes' ), 0 );
add_filter( 'json_prepare_taxonomy', array( $wp_json_posts, 'add_post_type_data' ), 10, 3 );
// Users.
$wp_json_users = new WP_JSON_Users( $server );
add_filter( 'json_endpoints', array( $wp_json_users, 'register_routes' ), 0 );
add_filter( 'json_prepare_post', array( $wp_json_users, 'add_post_author_data' ), 10, 3 );
add_filter( 'json_prepare_comment', array( $wp_json_users, 'add_comment_author_data' ), 10, 3 );
// Pages.
$wp_json_pages = new WP_JSON_Pages( $server );
$wp_json_pages->register_filters();
// Media.
$wp_json_media = new WP_JSON_Media( $server );
add_filter( 'json_endpoints', array( $wp_json_media, 'register_routes' ), 1 );
add_filter( 'json_prepare_post', array( $wp_json_media, 'add_thumbnail_data' ), 10, 3 );
add_filter( 'json_pre_insert_post', array( $wp_json_media, 'preinsert_check' ), 10, 3 );
add_filter( 'json_insert_post', array( $wp_json_media, 'attach_thumbnail' ), 10, 3 );
add_filter( 'json_post_type_data', array( $wp_json_media, 'type_archive_link' ), 10, 2 );
// Posts.
$wp_json_taxonomies = new WP_JSON_Taxonomies( $server );
add_filter( 'json_endpoints', array( $wp_json_taxonomies, 'register_routes' ), 2 );
add_filter( 'json_post_type_data', array( $wp_json_taxonomies, 'add_taxonomy_data' ), 10, 3 );
add_filter( 'json_prepare_post', array( $wp_json_taxonomies, 'add_term_data' ), 10, 3 );
// Deprecated reporting.
add_action( 'deprecated_function_run', 'json_handle_deprecated_function', 10, 3 );
add_filter( 'deprecated_function_trigger_error', '__return_false' );
add_action( 'deprecated_argument_run', 'json_handle_deprecated_argument', 10, 3 );
add_filter( 'deprecated_argument_trigger_error', '__return_false' );
}
add_action( 'wp_json_server_before_serve', 'json_api_default_filters', 10, 1 );
/**
* Load the JSON API.
*
* @todo Extract code that should be unit tested into isolated methods such as
* the wp_json_server_class filter and serving requests. This would also
* help for code re-use by `wp-json` endpoint. Note that we can't unit
* test any method that calls die().
*/
function json_api_loaded() {
if ( empty( $GLOBALS['wp']->query_vars['json_route'] ) )
return;
/**
* Whether this is a XML-RPC Request.
*
* @var bool
* @todo Remove me in favour of JSON_REQUEST
*/
define( 'XMLRPC_REQUEST', true );
/**
* Whether this is a JSON Request.
*
* @var bool
*/
define( 'JSON_REQUEST', true );
global $wp_json_server;
// Allow for a plugin to insert a different class to handle requests.
$wp_json_server_class = apply_filters( 'wp_json_server_class', 'WP_JSON_Server' );
$wp_json_server = new $wp_json_server_class;
/**
* Fires when preparing to serve an API request.
*
* Endpoint objects should be created and register their hooks on this
* action rather than another action to ensure they're only loaded when
* needed.
*
* @param WP_JSON_ResponseHandler $wp_json_server Response handler object.
*/
do_action( 'wp_json_server_before_serve', $wp_json_server );
// Fire off the request.
$wp_json_server->serve_request( $GLOBALS['wp']->query_vars['json_route'] );
// We're done.
die();
}
add_action( 'template_redirect', 'json_api_loaded', -100 );
/**
* Register routes and flush the rewrite rules on activation.
*
* @param bool $network_wide ?
*/
function json_api_activation( $network_wide ) {
if ( function_exists( 'is_multisite' ) && is_multisite() && $network_wide ) {
$mu_blogs = wp_get_sites();
foreach ( $mu_blogs as $mu_blog ) {
switch_to_blog( $mu_blog['blog_id'] );
json_api_register_rewrites();
update_option( 'json_api_plugin_version', null );
}
restore_current_blog();
} else {
json_api_register_rewrites();
update_option( 'json_api_plugin_version', null );
}
}
register_activation_hook( __FILE__, 'json_api_activation' );
/**
* Flush the rewrite rules on deactivation.
*
* @param bool $network_wide ?
*/
function json_api_deactivation( $network_wide ) {
if ( function_exists( 'is_multisite' ) && is_multisite() && $network_wide ) {
$mu_blogs = wp_get_sites();
foreach ( $mu_blogs as $mu_blog ) {
switch_to_blog( $mu_blog['blog_id'] );
delete_option( 'json_api_plugin_version' );
}
restore_current_blog();
} else {
delete_option( 'json_api_plugin_version' );
}
}
register_deactivation_hook( __FILE__, 'json_api_deactivation' );
/**
* Register API Javascript helpers.
*
* @see wp_register_scripts()
*/
function json_register_scripts() {
wp_register_script( 'wp-api', 'http://wp-api.github.io/client-js/build/js/wp-api.js', array( 'jquery', 'backbone', 'underscore' ), '1.1', true );
$settings = array( 'root' => esc_url_raw( get_json_url() ), 'nonce' => wp_create_nonce( 'wp_json' ) );
wp_localize_script( 'wp-api', 'WP_API_Settings', $settings );
}
add_action( 'wp_enqueue_scripts', 'json_register_scripts', -100 );
/**
* Add the API URL to the WP RSD endpoint.
*/
function json_output_rsd() {
?>
<api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo get_json_url() ?>" />
<?php
}
add_action( 'xmlrpc_rsd_apis', 'json_output_rsd' );
/**
* Output API link tag into page header.
*
* @see get_json_url()
*/
function json_output_link_wp_head() {
$api_root = get_json_url();
if ( empty( $api_root ) ) {
return;
}
echo "<link rel='https://github.com/WP-API/WP-API' href='" . esc_url( $api_root ) . "' />\n";
}
add_action( 'wp_head', 'json_output_link_wp_head', 10, 0 );
/**
* Send a Link header for the API.
*/
function json_output_link_header() {
if ( headers_sent() ) {
return;
}
$api_root = get_json_url();
if ( empty($api_root) ) {
return;
}
header( 'Link: <' . $api_root . '>; rel="https://github.com/WP-API/WP-API"', false );
}
add_action( 'template_redirect', 'json_output_link_header', 11, 0 );
/**
* Add 'show_in_json' {@see register_post_type()} argument.
*
* Adds the 'show_in_json' post type argument to {@see register_post_type()}.
* This value controls whether the post type is available via API endpoints,
* and defaults to the value of $publicly_queryable.
*
* @global array $wp_post_types Post types list.
*
* @param string $post_type Post type to register.
* @param stdClass $args Post type arguments.
*/
function json_register_post_type( $post_type, $args ) {
global $wp_post_types;
$type = &$wp_post_types[ $post_type ];
// Exception for pages.
if ( $post_type === 'page' ) {
$type->show_in_json = true;
}
// Exception for revisions.
if ( $post_type === 'revision' ) {
$type->show_in_json = true;
}
// Default to the value of $publicly_queryable.
if ( ! isset( $type->show_in_json ) ) {
$type->show_in_json = $type->publicly_queryable;
}
}
add_action( 'registered_post_type', 'json_register_post_type', 10, 2 );
/**
* Check for errors when using cookie-based authentication.
*
* WordPress' built-in cookie authentication is always active
* for logged in users. However, the API has to check nonces
* for each request to ensure users are not vulnerable to CSRF.
*
* @global mixed $wp_json_auth_cookie
*
* @param WP_Error|mixed $result Error from another authentication handler,
* null if we should handle it, or another
* value if not
* @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result,
* otherwise true.
*/
function json_cookie_check_errors( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
global $wp_json_auth_cookie;
/*
* Is cookie authentication being used? (If we get an auth
* error, but we're still logged in, another authentication
* must have been used.)
*/
if ( $wp_json_auth_cookie !== true && is_user_logged_in() ) {
return $result;
}
// Is there a nonce?
$nonce = null;
if ( isset( $_REQUEST['_wp_json_nonce'] ) ) {
$nonce = $_REQUEST['_wp_json_nonce'];
} elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
$nonce = $_SERVER['HTTP_X_WP_NONCE'];
}
if ( $nonce === null ) {
// No nonce at all, so act as if it's an unauthenticated request.
wp_set_current_user( 0 );
return true;
}
// Check the nonce.
$result = wp_verify_nonce( $nonce, 'wp_json' );
if ( ! $result ) {
return new WP_Error( 'json_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
}
return true;
}
add_filter( 'json_authentication_errors', 'json_cookie_check_errors', 100 );
/**
* Collect cookie authentication status.
*
* Collects errors from {@see wp_validate_auth_cookie} for
* use by {@see json_cookie_check_errors}.
*
* @see current_action()
* @global mixed $wp_json_auth_cookie
*/
function json_cookie_collect_status() {
global $wp_json_auth_cookie;
$status_type = current_action();
if ( $status_type !== 'auth_cookie_valid' ) {
$wp_json_auth_cookie = substr( $status_type, 12 );
return;
}
$wp_json_auth_cookie = true;
}
add_action( 'auth_cookie_malformed', 'json_cookie_collect_status' );
add_action( 'auth_cookie_expired', 'json_cookie_collect_status' );
add_action( 'auth_cookie_bad_username', 'json_cookie_collect_status' );
add_action( 'auth_cookie_bad_hash', 'json_cookie_collect_status' );
add_action( 'auth_cookie_valid', 'json_cookie_collect_status' );
/**
* Get the URL prefix for any API resource.
*
* @return string Prefix.
*/
function json_get_url_prefix() {
/**
* Filter the JSON URL prefix.
*
* @since 1.0
*
* @param string $prefix URL prefix. Default 'wp-json'.
*/
return apply_filters( 'json_url_prefix', 'wp-json' );
}
/**
* Get URL to a JSON endpoint on a site.
*
* @todo Check if this is even necessary
*
* @param int $blog_id Blog ID.
* @param string $path Optional. JSON route. Default empty.
* @param string $scheme Optional. Sanitization scheme. Default 'json'.
* @return string Full URL to the endpoint.
*/
function get_json_url( $blog_id = null, $path = '', $scheme = 'json' ) {
if ( get_option( 'permalink_structure' ) ) {
$url = get_home_url( $blog_id, json_get_url_prefix(), $scheme );
if ( ! empty( $path ) && is_string( $path ) && strpos( $path, '..' ) === false )
$url .= '/' . ltrim( $path, '/' );
} else {
$url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
if ( empty( $path ) ) {
$path = '/';
} else {
$path = '/' . ltrim( $path, '/' );
}
$url = add_query_arg( 'json_route', $path, $url );
}
/**
* Filter the JSON URL.
*
* @since 1.0
*
* @param string $url JSON URL.
* @param string $path JSON route.
* @param int $blod_ig Blog ID.
* @param string $scheme Sanitization scheme.
*/
return apply_filters( 'json_url', $url, $path, $blog_id, $scheme );
}
/**
* Get URL to a JSON endpoint.
*
* @param string $path Optional. JSON route. Default empty.
* @param string $scheme Optional. Sanitization scheme. Default 'json'.
* @return string Full URL to the endpoint.
*/
function json_url( $path = '', $scheme = 'json' ) {
return get_json_url( null, $path, $scheme );
}
/**
* Ensure a JSON response is a response object.
*
* This ensures that the response is consistent, and implements
* {@see WP_JSON_ResponseInterface}, allowing usage of
* `set_status`/`header`/etc without needing to double-check the object. Will
* also allow {@see WP_Error} to indicate error responses, so users should
* immediately check for this value.
*
* @param WP_Error|WP_JSON_ResponseInterface|mixed $response Response to check.
* @return WP_Error|WP_JSON_ResponseInterface WP_Error if present, WP_JSON_ResponseInterface
* instance otherwise.
*/
function json_ensure_response( $response ) {
if ( is_wp_error( $response ) ) {
return $response;
}
if ( $response instanceof WP_JSON_ResponseInterface ) {
return $response;
}
return new WP_JSON_Response( $response );
}
/**
* Parse an RFC3339 timestamp into a DateTime.
*
* @param string $date RFC3339 timestamp.
* @param bool $force_utc Force UTC timezone instead of using the timestamp's TZ.
* @return DateTime DateTime instance.
*/
function json_parse_date( $date, $force_utc = false ) {
// Default timezone to the server's current one.
$timezone = json_get_timezone();
if ( $force_utc ) {
$date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
$timezone = new DateTimeZone( 'UTC' );
}
// Strip millisecond precision (a full stop followed by one or more digits).
if ( strpos( $date, '.' ) !== false ) {
$date = preg_replace( '/\.\d+/', '', $date );
}
$datetime = WP_JSON_DateTime::createFromFormat( DateTime::RFC3339, $date, $timezone );
return $datetime;
}
/**
* Get a local date with its GMT equivalent, in MySQL datetime format.
*
* @param string $date RFC3339 timestamp
* @param bool $force_utc Whether a UTC timestamp should be forced.
* @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
* null on failure.
*/
function json_get_date_with_gmt( $date, $force_utc = false ) {
$datetime = json_parse_date( $date, $force_utc );
if ( empty( $datetime ) ) {
return null;
}
$datetime->setTimezone( json_get_timezone() );
$local = $datetime->format( 'Y-m-d H:i:s' );
$datetime->setTimezone( new DateTimeZone( 'UTC' ) );
$utc = $datetime->format('Y-m-d H:i:s');
return array( $local, $utc );
}
/**
* Retrieve the avatar url for a user who provided a user ID or email address.
*
* {@see get_avatar()} doesn't return just the URL, so we have to
* extract it here.
*
* @param string $email Email address.
* @return string URL for the user's avatar, empty string otherwise.
*/
function json_get_avatar_url( $email ) {
$avatar_html = get_avatar( $email );
// Strip the avatar url from the get_avatar img tag.
preg_match('/src=["|\'](.+)[\&|"|\']/U', $avatar_html, $matches);
if ( isset( $matches[1] ) && ! empty( $matches[1] ) ) {
return esc_url_raw( $matches[1] );
}
return '';
}
/**
* Get the timezone object for the site.
*
* @return DateTimeZone DateTimeZone instance.
*/
function json_get_timezone() {
static $zone = null;
if ( $zone !== null ) {
return $zone;
}
$tzstring = get_option( 'timezone_string' );
if ( ! $tzstring ) {
// Create a UTC+- zone if no timezone string exists
$current_offset = get_option( 'gmt_offset' );
if ( 0 == $current_offset ) {
$tzstring = 'UTC';
} elseif ( $current_offset < 0 ) {
$tzstring = 'Etc/GMT' . $current_offset;
} else {
$tzstring = 'Etc/GMT+' . $current_offset;
}
}
$zone = new DateTimeZone( $tzstring );
return $zone;
}
/**
* Handle {@see _deprecated_function()} errors.
*
* @param string $function Function name.
* @param string $replacement Replacement function name.
* @param string $version Version.
*/
function json_handle_deprecated_function( $function, $replacement, $version ) {
if ( ! empty( $replacement ) ) {
$string = sprintf( __('%1$s (since %2$s; use %3$s instead)'), $function, $version, $replacement );
}
else {
$string = sprintf( __('%1$s (since %2$s; no alternative available)'), $function, $version );
}
header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
}
/**
* Handle {@see _deprecated_function} errors.
*
* @param string $function Function name.
* @param string $replacement Replacement function name.
* @param string $version Version.
*/
function json_handle_deprecated_argument( $function, $message, $version ) {
if ( ! empty( $message ) ) {
$string = sprintf( __('%1$s (since %2$s; %3$s)'), $function, $version, $message );
}
else {
$string = sprintf( __('%1$s (since %2$s; no alternative available)'), $function, $version );
}
header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
}