]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php
WordPress 4.7.2-scripts
[autoinstalls/wordpress.git] / wp-includes / rest-api / endpoints / class-wp-rest-terms-controller.php
1 <?php
2 /**
3  * REST API: WP_REST_Terms_Controller class
4  *
5  * @package WordPress
6  * @subpackage REST_API
7  * @since 4.7.0
8  */
9
10 /**
11  * Core class used to managed terms associated with a taxonomy via the REST API.
12  *
13  * @since 4.7.0
14  *
15  * @see WP_REST_Controller
16  */
17 class WP_REST_Terms_Controller extends WP_REST_Controller {
18
19         /**
20          * Taxonomy key.
21          *
22          * @since 4.7.0
23          * @access protected
24          * @var string
25          */
26         protected $taxonomy;
27
28         /**
29          * Instance of a term meta fields object.
30          *
31          * @since 4.7.0
32          * @access protected
33          * @var WP_REST_Term_Meta_Fields
34          */
35         protected $meta;
36
37         /**
38          * Column to have the terms be sorted by.
39          *
40          * @since 4.7.0
41          * @access protected
42          * @var string
43          */
44         protected $sort_column;
45
46         /**
47          * Number of terms that were found.
48          *
49          * @since 4.7.0
50          * @access protected
51          * @var int
52          */
53         protected $total_terms;
54
55         /**
56          * Constructor.
57          *
58          * @since 4.7.0
59          * @access public
60          *
61          * @param string $taxonomy Taxonomy key.
62          */
63         public function __construct( $taxonomy ) {
64                 $this->taxonomy = $taxonomy;
65                 $this->namespace = 'wp/v2';
66                 $tax_obj = get_taxonomy( $taxonomy );
67                 $this->rest_base = ! empty( $tax_obj->rest_base ) ? $tax_obj->rest_base : $tax_obj->name;
68
69                 $this->meta = new WP_REST_Term_Meta_Fields( $taxonomy );
70         }
71
72         /**
73          * Registers the routes for the objects of the controller.
74          *
75          * @since 4.7.0
76          * @access public
77          *
78          * @see register_rest_route()
79          */
80         public function register_routes() {
81
82                 register_rest_route( $this->namespace, '/' . $this->rest_base, array(
83                         array(
84                                 'methods'             => WP_REST_Server::READABLE,
85                                 'callback'            => array( $this, 'get_items' ),
86                                 'permission_callback' => array( $this, 'get_items_permissions_check' ),
87                                 'args'                => $this->get_collection_params(),
88                         ),
89                         array(
90                                 'methods'             => WP_REST_Server::CREATABLE,
91                                 'callback'            => array( $this, 'create_item' ),
92                                 'permission_callback' => array( $this, 'create_item_permissions_check' ),
93                                 'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
94                         ),
95                         'schema' => array( $this, 'get_public_item_schema' ),
96                 ) );
97
98                 register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
99                         'args' => array(
100                                 'id' => array(
101                                         'description' => __( 'Unique identifier for the term.' ),
102                                         'type'        => 'integer',
103                                 ),
104                         ),
105                         array(
106                                 'methods'             => WP_REST_Server::READABLE,
107                                 'callback'            => array( $this, 'get_item' ),
108                                 'permission_callback' => array( $this, 'get_item_permissions_check' ),
109                                 'args'                => array(
110                                         'context' => $this->get_context_param( array( 'default' => 'view' ) ),
111                                 ),
112                         ),
113                         array(
114                                 'methods'             => WP_REST_Server::EDITABLE,
115                                 'callback'            => array( $this, 'update_item' ),
116                                 'permission_callback' => array( $this, 'update_item_permissions_check' ),
117                                 'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
118                         ),
119                         array(
120                                 'methods'             => WP_REST_Server::DELETABLE,
121                                 'callback'            => array( $this, 'delete_item' ),
122                                 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
123                                 'args'                => array(
124                                         'force' => array(
125                                                 'type'        => 'boolean',
126                                                 'default'     => false,
127                                                 'description' => __( 'Required to be true, as terms do not support trashing.' ),
128                                         ),
129                                 ),
130                         ),
131                         'schema' => array( $this, 'get_public_item_schema' ),
132                 ) );
133         }
134
135         /**
136          * Checks if a request has access to read terms in the specified taxonomy.
137          *
138          * @since 4.7.0
139          * @access public
140          *
141          * @param WP_REST_Request $request Full details about the request.
142          * @return bool|WP_Error True if the request has read access, otherwise false or WP_Error object.
143          */
144         public function get_items_permissions_check( $request ) {
145                 $tax_obj = get_taxonomy( $this->taxonomy );
146                 if ( ! $tax_obj || ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
147                         return false;
148                 }
149                 if ( 'edit' === $request['context'] && ! current_user_can( $tax_obj->cap->edit_terms ) ) {
150                         return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit terms in this taxonomy.' ), array( 'status' => rest_authorization_required_code() ) );
151                 }
152                 return true;
153         }
154
155         /**
156          * Retrieves terms associated with a taxonomy.
157          *
158          * @since 4.7.0
159          * @access public
160          *
161          * @param WP_REST_Request $request Full details about the request.
162          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
163          */
164         public function get_items( $request ) {
165
166                 // Retrieve the list of registered collection query parameters.
167                 $registered = $this->get_collection_params();
168
169                 /*
170                  * This array defines mappings between public API query parameters whose
171                  * values are accepted as-passed, and their internal WP_Query parameter
172                  * name equivalents (some are the same). Only values which are also
173                  * present in $registered will be set.
174                  */
175                 $parameter_mappings = array(
176                         'exclude'    => 'exclude',
177                         'include'    => 'include',
178                         'order'      => 'order',
179                         'orderby'    => 'orderby',
180                         'post'       => 'post',
181                         'hide_empty' => 'hide_empty',
182                         'per_page'   => 'number',
183                         'search'     => 'search',
184                         'slug'       => 'slug',
185                 );
186
187                 $prepared_args = array();
188
189                 /*
190                  * For each known parameter which is both registered and present in the request,
191                  * set the parameter's value on the query $prepared_args.
192                  */
193                 foreach ( $parameter_mappings as $api_param => $wp_param ) {
194                         if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
195                                 $prepared_args[ $wp_param ] = $request[ $api_param ];
196                         }
197                 }
198
199                 if ( isset( $registered['offset'] ) && ! empty( $request['offset'] ) ) {
200                         $prepared_args['offset'] = $request['offset'];
201                 } else {
202                         $prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number'];
203                 }
204
205                 $taxonomy_obj = get_taxonomy( $this->taxonomy );
206
207                 if ( $taxonomy_obj->hierarchical && isset( $registered['parent'], $request['parent'] ) ) {
208                         if ( 0 === $request['parent'] ) {
209                                 // Only query top-level terms.
210                                 $prepared_args['parent'] = 0;
211                         } else {
212                                 if ( $request['parent'] ) {
213                                         $prepared_args['parent'] = $request['parent'];
214                                 }
215                         }
216                 }
217
218                 /**
219                  * Filters the query arguments before passing them to get_terms().
220                  *
221                  * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
222                  *
223                  * Enables adding extra arguments or setting defaults for a terms
224                  * collection request.
225                  *
226                  * @since 4.7.0
227                  *
228                  * @link https://developer.wordpress.org/reference/functions/get_terms/
229                  *
230                  * @param array           $prepared_args Array of arguments to be
231                  *                                       passed to get_terms().
232                  * @param WP_REST_Request $request       The current request.
233                  */
234                 $prepared_args = apply_filters( "rest_{$this->taxonomy}_query", $prepared_args, $request );
235
236                 if ( ! empty( $prepared_args['post'] )  ) {
237                         $query_result = wp_get_object_terms( $prepared_args['post'], $this->taxonomy, $prepared_args );
238
239                         // Used when calling wp_count_terms() below.
240                         $prepared_args['object_ids'] = $prepared_args['post'];
241                 } else {
242                         $query_result = get_terms( $this->taxonomy, $prepared_args );
243                 }
244
245                 $count_args = $prepared_args;
246
247                 unset( $count_args['number'], $count_args['offset'] );
248
249                 $total_terms = wp_count_terms( $this->taxonomy, $count_args );
250
251                 // wp_count_terms can return a falsy value when the term has no children.
252                 if ( ! $total_terms ) {
253                         $total_terms = 0;
254                 }
255
256                 $response = array();
257
258                 foreach ( $query_result as $term ) {
259                         $data = $this->prepare_item_for_response( $term, $request );
260                         $response[] = $this->prepare_response_for_collection( $data );
261                 }
262
263                 $response = rest_ensure_response( $response );
264
265                 // Store pagination values for headers.
266                 $per_page = (int) $prepared_args['number'];
267                 $page     = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 );
268
269                 $response->header( 'X-WP-Total', (int) $total_terms );
270
271                 $max_pages = ceil( $total_terms / $per_page );
272
273                 $response->header( 'X-WP-TotalPages', (int) $max_pages );
274
275                 $base = add_query_arg( $request->get_query_params(), rest_url( $this->namespace . '/' . $this->rest_base ) );
276                 if ( $page > 1 ) {
277                         $prev_page = $page - 1;
278
279                         if ( $prev_page > $max_pages ) {
280                                 $prev_page = $max_pages;
281                         }
282
283                         $prev_link = add_query_arg( 'page', $prev_page, $base );
284                         $response->link_header( 'prev', $prev_link );
285                 }
286                 if ( $max_pages > $page ) {
287                         $next_page = $page + 1;
288                         $next_link = add_query_arg( 'page', $next_page, $base );
289
290                         $response->link_header( 'next', $next_link );
291                 }
292
293                 return $response;
294         }
295
296         /**
297          * Get the term, if the ID is valid.
298          *
299          * @since 4.7.2
300          *
301          * @param int $id Supplied ID.
302          * @return WP_Term|WP_Error Term object if ID is valid, WP_Error otherwise.
303          */
304         protected function get_term( $id ) {
305                 $error = new WP_Error( 'rest_term_invalid', __( 'Term does not exist.' ), array( 'status' => 404 ) );
306
307                 if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
308                         return $error;
309                 }
310
311                 if ( (int) $id <= 0 ) {
312                         return $error;
313                 }
314
315                 $term = get_term( (int) $id, $this->taxonomy );
316                 if ( empty( $term ) || $term->taxonomy !== $this->taxonomy ) {
317                         return $error;
318                 }
319
320                 return $term;
321         }
322
323         /**
324          * Checks if a request has access to read or edit the specified term.
325          *
326          * @since 4.7.0
327          * @access public
328          *
329          * @param WP_REST_Request $request Full details about the request.
330          * @return bool|WP_Error True if the request has read access for the item, otherwise false or WP_Error object.
331          */
332         public function get_item_permissions_check( $request ) {
333                 $term = $this->get_term( $request['id'] );
334                 if ( is_wp_error( $term ) ) {
335                         return $term;
336                 }
337
338                 if ( 'edit' === $request['context'] && ! current_user_can( 'edit_term', $term->term_id ) ) {
339                         return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this term.' ), array( 'status' => rest_authorization_required_code() ) );
340                 }
341                 return true;
342         }
343
344         /**
345          * Gets a single term from a taxonomy.
346          *
347          * @since 4.7.0
348          * @access public
349          *
350          * @param WP_REST_Request $request Full details about the request.
351          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
352          */
353         public function get_item( $request ) {
354                 $term = $this->get_term( $request['id'] );
355
356                 if ( is_wp_error( $term ) ) {
357                         return $term;
358                 }
359
360                 $response = $this->prepare_item_for_response( $term, $request );
361
362                 return rest_ensure_response( $response );
363         }
364
365         /**
366          * Checks if a request has access to create a term.
367          *
368          * @since 4.7.0
369          * @access public
370          *
371          * @param WP_REST_Request $request Full details about the request.
372          * @return bool|WP_Error True if the request has access to create items, false or WP_Error object otherwise.
373          */
374         public function create_item_permissions_check( $request ) {
375
376                 if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
377                         return false;
378                 }
379
380                 $taxonomy_obj = get_taxonomy( $this->taxonomy );
381                 if ( ! current_user_can( $taxonomy_obj->cap->edit_terms ) ) {
382                         return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create new terms.' ), array( 'status' => rest_authorization_required_code() ) );
383                 }
384
385                 return true;
386         }
387
388         /**
389          * Creates a single term in a taxonomy.
390          *
391          * @since 4.7.0
392          * @access public
393          *
394          * @param WP_REST_Request $request Full details about the request.
395          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
396          */
397         public function create_item( $request ) {
398                 if ( isset( $request['parent'] ) ) {
399                         if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
400                                 return new WP_Error( 'rest_taxonomy_not_hierarchical', __( 'Can not set parent term, taxonomy is not hierarchical.' ), array( 'status' => 400 ) );
401                         }
402
403                         $parent = get_term( (int) $request['parent'], $this->taxonomy );
404
405                         if ( ! $parent ) {
406                                 return new WP_Error( 'rest_term_invalid', __( "Parent term doesn't exist." ), array( 'status' => 400 ) );
407                         }
408                 }
409
410                 $prepared_term = $this->prepare_item_for_database( $request );
411
412                 $term = wp_insert_term( wp_slash( $prepared_term->name ), $this->taxonomy, wp_slash( (array) $prepared_term ) );
413                 if ( is_wp_error( $term ) ) {
414                         /*
415                          * If we're going to inform the client that the term already exists,
416                          * give them the identifier for future use.
417                          */
418                         if ( $term_id = $term->get_error_data( 'term_exists' ) ) {
419                                 $existing_term = get_term( $term_id, $this->taxonomy );
420                                 $term->add_data( $existing_term->term_id, 'term_exists' );
421                         }
422
423                         return $term;
424                 }
425
426                 $term = get_term( $term['term_id'], $this->taxonomy );
427
428                 /**
429                  * Fires after a single term is created or updated via the REST API.
430                  *
431                  * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
432                  *
433                  * @since 4.7.0
434                  *
435                  * @param WP_Term         $term     Inserted or updated term object.
436                  * @param WP_REST_Request $request  Request object.
437                  * @param bool            $creating True when creating a term, false when updating.
438                  */
439                 do_action( "rest_insert_{$this->taxonomy}", $term, $request, true );
440
441                 $schema = $this->get_item_schema();
442                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
443                         $meta_update = $this->meta->update_value( $request['meta'], (int) $request['id'] );
444
445                         if ( is_wp_error( $meta_update ) ) {
446                                 return $meta_update;
447                         }
448                 }
449
450                 $fields_update = $this->update_additional_fields_for_object( $term, $request );
451
452                 if ( is_wp_error( $fields_update ) ) {
453                         return $fields_update;
454                 }
455
456                 $request->set_param( 'context', 'view' );
457
458                 $response = $this->prepare_item_for_response( $term, $request );
459                 $response = rest_ensure_response( $response );
460
461                 $response->set_status( 201 );
462                 $response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . $term->term_id ) );
463
464                 return $response;
465         }
466
467         /**
468          * Checks if a request has access to update the specified term.
469          *
470          * @since 4.7.0
471          * @access public
472          *
473          * @param WP_REST_Request $request Full details about the request.
474          * @return bool|WP_Error True if the request has access to update the item, false or WP_Error object otherwise.
475          */
476         public function update_item_permissions_check( $request ) {
477                 $term = $this->get_term( $request['id'] );
478                 if ( is_wp_error( $term ) ) {
479                         return $term;
480                 }
481
482                 if ( ! current_user_can( 'edit_term', $term->term_id ) ) {
483                         return new WP_Error( 'rest_cannot_update', __( 'Sorry, you are not allowed to edit this term.' ), array( 'status' => rest_authorization_required_code() ) );
484                 }
485
486                 return true;
487         }
488
489         /**
490          * Updates a single term from a taxonomy.
491          *
492          * @since 4.7.0
493          * @access public
494          *
495          * @param WP_REST_Request $request Full details about the request.
496          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
497          */
498         public function update_item( $request ) {
499                 $term = $this->get_term( $request['id'] );
500                 if ( is_wp_error( $term ) ) {
501                         return $term;
502                 }
503
504                 if ( isset( $request['parent'] ) ) {
505                         if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
506                                 return new WP_Error( 'rest_taxonomy_not_hierarchical', __( 'Can not set parent term, taxonomy is not hierarchical.' ), array( 'status' => 400 ) );
507                         }
508
509                         $parent = get_term( (int) $request['parent'], $this->taxonomy );
510
511                         if ( ! $parent ) {
512                                 return new WP_Error( 'rest_term_invalid', __( "Parent term doesn't exist." ), array( 'status' => 400 ) );
513                         }
514                 }
515
516                 $prepared_term = $this->prepare_item_for_database( $request );
517
518                 // Only update the term if we haz something to update.
519                 if ( ! empty( $prepared_term ) ) {
520                         $update = wp_update_term( $term->term_id, $term->taxonomy, wp_slash( (array) $prepared_term ) );
521
522                         if ( is_wp_error( $update ) ) {
523                                 return $update;
524                         }
525                 }
526
527                 $term = get_term( $term->term_id, $this->taxonomy );
528
529                 /* This action is documented in lib/endpoints/class-wp-rest-terms-controller.php */
530                 do_action( "rest_insert_{$this->taxonomy}", $term, $request, false );
531
532                 $schema = $this->get_item_schema();
533                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
534                         $meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
535
536                         if ( is_wp_error( $meta_update ) ) {
537                                 return $meta_update;
538                         }
539                 }
540
541                 $fields_update = $this->update_additional_fields_for_object( $term, $request );
542
543                 if ( is_wp_error( $fields_update ) ) {
544                         return $fields_update;
545                 }
546
547                 $request->set_param( 'context', 'view' );
548
549                 $response = $this->prepare_item_for_response( $term, $request );
550
551                 return rest_ensure_response( $response );
552         }
553
554         /**
555          * Checks if a request has access to delete the specified term.
556          *
557          * @since 4.7.0
558          * @access public
559          *
560          * @param WP_REST_Request $request Full details about the request.
561          * @return bool|WP_Error True if the request has access to delete the item, otherwise false or WP_Error object.
562          */
563         public function delete_item_permissions_check( $request ) {
564                 $term = $this->get_term( $request['id'] );
565                 if ( is_wp_error( $term ) ) {
566                         return $term;
567                 }
568
569                 if ( ! current_user_can( 'delete_term', $term->term_id ) ) {
570                         return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this term.' ), array( 'status' => rest_authorization_required_code() ) );
571                 }
572
573                 return true;
574         }
575
576         /**
577          * Deletes a single term from a taxonomy.
578          *
579          * @since 4.7.0
580          * @access public
581          *
582          * @param WP_REST_Request $request Full details about the request.
583          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
584          */
585         public function delete_item( $request ) {
586                 $term = $this->get_term( $request['id'] );
587                 if ( is_wp_error( $term ) ) {
588                         return $term;
589                 }
590
591                 $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
592
593                 // We don't support trashing for terms.
594                 if ( ! $force ) {
595                         return new WP_Error( 'rest_trash_not_supported', __( 'Terms do not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
596                 }
597
598                 $request->set_param( 'context', 'view' );
599
600                 $previous = $this->prepare_item_for_response( $term, $request );
601
602                 $retval = wp_delete_term( $term->term_id, $term->taxonomy );
603
604                 if ( ! $retval ) {
605                         return new WP_Error( 'rest_cannot_delete', __( 'The term cannot be deleted.' ), array( 'status' => 500 ) );
606                 }
607
608                 $response = new WP_REST_Response();
609                 $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
610
611                 /**
612                  * Fires after a single term is deleted via the REST API.
613                  *
614                  * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
615                  *
616                  * @since 4.7.0
617                  *
618                  * @param WP_Term          $term     The deleted term.
619                  * @param WP_REST_Response $response The response data.
620                  * @param WP_REST_Request  $request  The request sent to the API.
621                  */
622                 do_action( "rest_delete_{$this->taxonomy}", $term, $response, $request );
623
624                 return $response;
625         }
626
627         /**
628          * Prepares a single term for create or update.
629          *
630          * @since 4.7.0
631          * @access public
632          *
633          * @param WP_REST_Request $request Request object.
634          * @return object $prepared_term Term object.
635          */
636         public function prepare_item_for_database( $request ) {
637                 $prepared_term = new stdClass;
638
639                 $schema = $this->get_item_schema();
640                 if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
641                         $prepared_term->name = $request['name'];
642                 }
643
644                 if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
645                         $prepared_term->slug = $request['slug'];
646                 }
647
648                 if ( isset( $request['taxonomy'] ) && ! empty( $schema['properties']['taxonomy'] ) ) {
649                         $prepared_term->taxonomy = $request['taxonomy'];
650                 }
651
652                 if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
653                         $prepared_term->description = $request['description'];
654                 }
655
656                 if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
657                         $parent_term_id = 0;
658                         $parent_term    = get_term( (int) $request['parent'], $this->taxonomy );
659
660                         if ( $parent_term ) {
661                                 $parent_term_id = $parent_term->term_id;
662                         }
663
664                         $prepared_term->parent = $parent_term_id;
665                 }
666
667                 /**
668                  * Filters term data before inserting term via the REST API.
669                  *
670                  * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
671                  *
672                  * @since 4.7.0
673                  *
674                  * @param object          $prepared_term Term object.
675                  * @param WP_REST_Request $request       Request object.
676                  */
677                 return apply_filters( "rest_pre_insert_{$this->taxonomy}", $prepared_term, $request );
678         }
679
680         /**
681          * Prepares a single term output for response.
682          *
683          * @since 4.7.0
684          * @access public
685          *
686          * @param obj             $item    Term object.
687          * @param WP_REST_Request $request Request object.
688          * @return WP_REST_Response $response Response object.
689          */
690         public function prepare_item_for_response( $item, $request ) {
691
692                 $schema = $this->get_item_schema();
693                 $data   = array();
694
695                 if ( ! empty( $schema['properties']['id'] ) ) {
696                         $data['id'] = (int) $item->term_id;
697                 }
698
699                 if ( ! empty( $schema['properties']['count'] ) ) {
700                         $data['count'] = (int) $item->count;
701                 }
702
703                 if ( ! empty( $schema['properties']['description'] ) ) {
704                         $data['description'] = $item->description;
705                 }
706
707                 if ( ! empty( $schema['properties']['link'] ) ) {
708                         $data['link'] = get_term_link( $item );
709                 }
710
711                 if ( ! empty( $schema['properties']['name'] ) ) {
712                         $data['name'] = $item->name;
713                 }
714
715                 if ( ! empty( $schema['properties']['slug'] ) ) {
716                         $data['slug'] = $item->slug;
717                 }
718
719                 if ( ! empty( $schema['properties']['taxonomy'] ) ) {
720                         $data['taxonomy'] = $item->taxonomy;
721                 }
722
723                 if ( ! empty( $schema['properties']['parent'] ) ) {
724                         $data['parent'] = (int) $item->parent;
725                 }
726
727                 if ( ! empty( $schema['properties']['meta'] ) ) {
728                         $data['meta'] = $this->meta->get_value( $item->term_id, $request );
729                 }
730
731                 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
732                 $data    = $this->add_additional_fields_to_object( $data, $request );
733                 $data    = $this->filter_response_by_context( $data, $context );
734
735                 $response = rest_ensure_response( $data );
736
737                 $response->add_links( $this->prepare_links( $item ) );
738
739                 /**
740                  * Filters a term item returned from the API.
741                  *
742                  * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
743                  *
744                  * Allows modification of the term data right before it is returned.
745                  *
746                  * @since 4.7.0
747                  *
748                  * @param WP_REST_Response  $response  The response object.
749                  * @param object            $item      The original term object.
750                  * @param WP_REST_Request   $request   Request used to generate the response.
751                  */
752                 return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $item, $request );
753         }
754
755         /**
756          * Prepares links for the request.
757          *
758          * @since 4.7.0
759          * @access protected
760          *
761          * @param object $term Term object.
762          * @return array Links for the given term.
763          */
764         protected function prepare_links( $term ) {
765                 $base = $this->namespace . '/' . $this->rest_base;
766                 $links = array(
767                         'self'       => array(
768                                 'href' => rest_url( trailingslashit( $base ) . $term->term_id ),
769                         ),
770                         'collection' => array(
771                                 'href' => rest_url( $base ),
772                         ),
773                         'about'      => array(
774                                 'href' => rest_url( sprintf( 'wp/v2/taxonomies/%s', $this->taxonomy ) ),
775                         ),
776                 );
777
778                 if ( $term->parent ) {
779                         $parent_term = get_term( (int) $term->parent, $term->taxonomy );
780
781                         if ( $parent_term ) {
782                                 $links['up'] = array(
783                                         'href'       => rest_url( trailingslashit( $base ) . $parent_term->term_id ),
784                                         'embeddable' => true,
785                                 );
786                         }
787                 }
788
789                 $taxonomy_obj = get_taxonomy( $term->taxonomy );
790
791                 if ( empty( $taxonomy_obj->object_type ) ) {
792                         return $links;
793                 }
794
795                 $post_type_links = array();
796
797                 foreach ( $taxonomy_obj->object_type as $type ) {
798                         $post_type_object = get_post_type_object( $type );
799
800                         if ( empty( $post_type_object->show_in_rest ) ) {
801                                 continue;
802                         }
803
804                         $rest_base = ! empty( $post_type_object->rest_base ) ? $post_type_object->rest_base : $post_type_object->name;
805                         $post_type_links[] = array(
806                                 'href' => add_query_arg( $this->rest_base, $term->term_id, rest_url( sprintf( 'wp/v2/%s', $rest_base ) ) ),
807                         );
808                 }
809
810                 if ( ! empty( $post_type_links ) ) {
811                         $links['https://api.w.org/post_type'] = $post_type_links;
812                 }
813
814                 return $links;
815         }
816
817         /**
818          * Retrieves the term's schema, conforming to JSON Schema.
819          *
820          * @since 4.7.0
821          * @access public
822          *
823          * @return array Item schema data.
824          */
825         public function get_item_schema() {
826                 $schema = array(
827                         '$schema'    => 'http://json-schema.org/schema#',
828                         'title'      => 'post_tag' === $this->taxonomy ? 'tag' : $this->taxonomy,
829                         'type'       => 'object',
830                         'properties' => array(
831                                 'id'          => array(
832                                         'description'  => __( 'Unique identifier for the term.' ),
833                                         'type'         => 'integer',
834                                         'context'      => array( 'view', 'embed', 'edit' ),
835                                         'readonly'     => true,
836                                 ),
837                                 'count'       => array(
838                                         'description'  => __( 'Number of published posts for the term.' ),
839                                         'type'         => 'integer',
840                                         'context'      => array( 'view', 'edit' ),
841                                         'readonly'     => true,
842                                 ),
843                                 'description' => array(
844                                         'description'  => __( 'HTML description of the term.' ),
845                                         'type'         => 'string',
846                                         'context'      => array( 'view', 'edit' ),
847                                 ),
848                                 'link'        => array(
849                                         'description'  => __( 'URL of the term.' ),
850                                         'type'         => 'string',
851                                         'format'       => 'uri',
852                                         'context'      => array( 'view', 'embed', 'edit' ),
853                                         'readonly'     => true,
854                                 ),
855                                 'name'        => array(
856                                         'description'  => __( 'HTML title for the term.' ),
857                                         'type'         => 'string',
858                                         'context'      => array( 'view', 'embed', 'edit' ),
859                                         'arg_options'  => array(
860                                                 'sanitize_callback' => 'sanitize_text_field',
861                                         ),
862                                         'required'     => true,
863                                 ),
864                                 'slug'        => array(
865                                         'description'  => __( 'An alphanumeric identifier for the term unique to its type.' ),
866                                         'type'         => 'string',
867                                         'context'      => array( 'view', 'embed', 'edit' ),
868                                         'arg_options'  => array(
869                                                 'sanitize_callback' => array( $this, 'sanitize_slug' ),
870                                         ),
871                                 ),
872                                 'taxonomy'    => array(
873                                         'description'  => __( 'Type attribution for the term.' ),
874                                         'type'         => 'string',
875                                         'enum'         => array_keys( get_taxonomies() ),
876                                         'context'      => array( 'view', 'embed', 'edit' ),
877                                         'readonly'     => true,
878                                 ),
879                         ),
880                 );
881
882                 $taxonomy = get_taxonomy( $this->taxonomy );
883
884                 if ( $taxonomy->hierarchical ) {
885                         $schema['properties']['parent'] = array(
886                                 'description'  => __( 'The parent term ID.' ),
887                                 'type'         => 'integer',
888                                 'context'      => array( 'view', 'edit' ),
889                         );
890                 }
891
892                 $schema['properties']['meta'] = $this->meta->get_field_schema();
893
894                 return $this->add_additional_fields_schema( $schema );
895         }
896
897         /**
898          * Retrieves the query params for collections.
899          *
900          * @since 4.7.0
901          * @access public
902          *
903          * @return array Collection parameters.
904          */
905         public function get_collection_params() {
906                 $query_params = parent::get_collection_params();
907                 $taxonomy = get_taxonomy( $this->taxonomy );
908
909                 $query_params['context']['default'] = 'view';
910
911                 $query_params['exclude'] = array(
912                         'description'       => __( 'Ensure result set excludes specific IDs.' ),
913                         'type'              => 'array',
914                         'items'             => array(
915                                 'type'          => 'integer',
916                         ),
917                         'default'           => array(),
918                 );
919
920                 $query_params['include'] = array(
921                         'description'       => __( 'Limit result set to specific IDs.' ),
922                         'type'              => 'array',
923                         'items'             => array(
924                                 'type'          => 'integer',
925                         ),
926                         'default'           => array(),
927                 );
928
929                 if ( ! $taxonomy->hierarchical ) {
930                         $query_params['offset'] = array(
931                                 'description'       => __( 'Offset the result set by a specific number of items.' ),
932                                 'type'              => 'integer',
933                         );
934                 }
935
936                 $query_params['order'] = array(
937                         'description'       => __( 'Order sort attribute ascending or descending.' ),
938                         'type'              => 'string',
939                         'default'           => 'asc',
940                         'enum'              => array(
941                                 'asc',
942                                 'desc',
943                         ),
944                 );
945
946                 $query_params['orderby'] = array(
947                         'description'       => __( 'Sort collection by term attribute.' ),
948                         'type'              => 'string',
949                         'default'           => 'name',
950                         'enum'              => array(
951                                 'id',
952                                 'include',
953                                 'name',
954                                 'slug',
955                                 'term_group',
956                                 'description',
957                                 'count',
958                         ),
959                 );
960
961                 $query_params['hide_empty'] = array(
962                         'description'       => __( 'Whether to hide terms not assigned to any posts.' ),
963                         'type'              => 'boolean',
964                         'default'           => false,
965                 );
966
967                 if ( $taxonomy->hierarchical ) {
968                         $query_params['parent'] = array(
969                                 'description'       => __( 'Limit result set to terms assigned to a specific parent.' ),
970                                 'type'              => 'integer',
971                         );
972                 }
973
974                 $query_params['post'] = array(
975                         'description'       => __( 'Limit result set to terms assigned to a specific post.' ),
976                         'type'              => 'integer',
977                         'default'           => null,
978                 );
979
980                 $query_params['slug'] = array(
981                         'description'       => __( 'Limit result set to terms with a specific slug.' ),
982                         'type'              => 'string',
983                 );
984
985                 /**
986                  * Filter collection parameters for the terms controller.
987                  *
988                  * The dynamic part of the filter `$this->taxonomy` refers to the taxonomy
989                  * slug for the controller.
990                  *
991                  * This filter registers the collection parameter, but does not map the
992                  * collection parameter to an internal WP_Term_Query parameter.  Use the
993                  * `rest_{$this->taxonomy}_query` filter to set WP_Term_Query parameters.
994                  *
995                  * @since 4.7.0
996                  *
997                  * @param array       $query_params JSON Schema-formatted collection parameters.
998                  * @param WP_Taxonomy $taxonomy     Taxonomy object.
999                  */
1000                 return apply_filters( "rest_{$this->taxonomy}_collection_params", $query_params, $taxonomy );
1001         }
1002
1003         /**
1004          * Checks that the taxonomy is valid.
1005          *
1006          * @since 4.7.0
1007          * @access protected
1008          *
1009          * @param string $taxonomy Taxonomy to check.
1010          * @return bool Whether the taxonomy is allowed for REST management.
1011          */
1012         protected function check_is_taxonomy_allowed( $taxonomy ) {
1013                 $taxonomy_obj = get_taxonomy( $taxonomy );
1014                 if ( $taxonomy_obj && ! empty( $taxonomy_obj->show_in_rest ) ) {
1015                         return true;
1016                 }
1017                 return false;
1018         }
1019 }