class-wp-rest-controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. <?php
  2. /**
  3. * REST API: WP_REST_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core base controller for managing and interacting with REST API items.
  11. *
  12. * @since 4.7.0
  13. */
  14. abstract class WP_REST_Controller {
  15. /**
  16. * The namespace of this controller's route.
  17. *
  18. * @since 4.7.0
  19. * @var string
  20. */
  21. protected $namespace;
  22. /**
  23. * The base of this controller's route.
  24. *
  25. * @since 4.7.0
  26. * @var string
  27. */
  28. protected $rest_base;
  29. /**
  30. * Registers the routes for the objects of the controller.
  31. *
  32. * @since 4.7.0
  33. */
  34. public function register_routes() {
  35. /* translators: %s: register_routes() */
  36. _doing_it_wrong( 'WP_REST_Controller::register_routes', sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ), '4.7' );
  37. }
  38. /**
  39. * Checks if a given request has access to get items.
  40. *
  41. * @since 4.7.0
  42. *
  43. * @param WP_REST_Request $request Full data about the request.
  44. * @return WP_Error|bool True if the request has read access, WP_Error object otherwise.
  45. */
  46. public function get_items_permissions_check( $request ) {
  47. /* translators: %s: method name */
  48. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  49. }
  50. /**
  51. * Retrieves a collection of items.
  52. *
  53. * @since 4.7.0
  54. *
  55. * @param WP_REST_Request $request Full data about the request.
  56. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
  57. */
  58. public function get_items( $request ) {
  59. /* translators: %s: method name */
  60. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  61. }
  62. /**
  63. * Checks if a given request has access to get a specific item.
  64. *
  65. * @since 4.7.0
  66. *
  67. * @param WP_REST_Request $request Full data about the request.
  68. * @return WP_Error|bool True if the request has read access for the item, WP_Error object otherwise.
  69. */
  70. public function get_item_permissions_check( $request ) {
  71. /* translators: %s: method name */
  72. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  73. }
  74. /**
  75. * Retrieves one item from the collection.
  76. *
  77. * @since 4.7.0
  78. *
  79. * @param WP_REST_Request $request Full data about the request.
  80. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
  81. */
  82. public function get_item( $request ) {
  83. /* translators: %s: method name */
  84. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  85. }
  86. /**
  87. * Checks if a given request has access to create items.
  88. *
  89. * @since 4.7.0
  90. *
  91. * @param WP_REST_Request $request Full data about the request.
  92. * @return WP_Error|bool True if the request has access to create items, WP_Error object otherwise.
  93. */
  94. public function create_item_permissions_check( $request ) {
  95. /* translators: %s: method name */
  96. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  97. }
  98. /**
  99. * Creates one item from the collection.
  100. *
  101. * @since 4.7.0
  102. *
  103. * @param WP_REST_Request $request Full data about the request.
  104. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
  105. */
  106. public function create_item( $request ) {
  107. /* translators: %s: method name */
  108. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  109. }
  110. /**
  111. * Checks if a given request has access to update a specific item.
  112. *
  113. * @since 4.7.0
  114. *
  115. * @param WP_REST_Request $request Full data about the request.
  116. * @return WP_Error|bool True if the request has access to update the item, WP_Error object otherwise.
  117. */
  118. public function update_item_permissions_check( $request ) {
  119. /* translators: %s: method name */
  120. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  121. }
  122. /**
  123. * Updates one item from the collection.
  124. *
  125. * @since 4.7.0
  126. *
  127. * @param WP_REST_Request $request Full data about the request.
  128. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
  129. */
  130. public function update_item( $request ) {
  131. /* translators: %s: method name */
  132. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  133. }
  134. /**
  135. * Checks if a given request has access to delete a specific item.
  136. *
  137. * @since 4.7.0
  138. *
  139. * @param WP_REST_Request $request Full data about the request.
  140. * @return WP_Error|bool True if the request has access to delete the item, WP_Error object otherwise.
  141. */
  142. public function delete_item_permissions_check( $request ) {
  143. /* translators: %s: method name */
  144. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  145. }
  146. /**
  147. * Deletes one item from the collection.
  148. *
  149. * @since 4.7.0
  150. *
  151. * @param WP_REST_Request $request Full data about the request.
  152. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
  153. */
  154. public function delete_item( $request ) {
  155. /* translators: %s: method name */
  156. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  157. }
  158. /**
  159. * Prepares one item for create or update operation.
  160. *
  161. * @since 4.7.0
  162. *
  163. * @param WP_REST_Request $request Request object.
  164. * @return WP_Error|object The prepared item, or WP_Error object on failure.
  165. */
  166. protected function prepare_item_for_database( $request ) {
  167. /* translators: %s: method name */
  168. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  169. }
  170. /**
  171. * Prepares the item for the REST response.
  172. *
  173. * @since 4.7.0
  174. *
  175. * @param mixed $item WordPress representation of the item.
  176. * @param WP_REST_Request $request Request object.
  177. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
  178. */
  179. public function prepare_item_for_response( $item, $request ) {
  180. /* translators: %s: method name */
  181. return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
  182. }
  183. /**
  184. * Prepares a response for insertion into a collection.
  185. *
  186. * @since 4.7.0
  187. *
  188. * @param WP_REST_Response $response Response object.
  189. * @return array|mixed Response data, ready for insertion into collection data.
  190. */
  191. public function prepare_response_for_collection( $response ) {
  192. if ( ! ( $response instanceof WP_REST_Response ) ) {
  193. return $response;
  194. }
  195. $data = (array) $response->get_data();
  196. $server = rest_get_server();
  197. if ( method_exists( $server, 'get_compact_response_links' ) ) {
  198. $links = call_user_func( array( $server, 'get_compact_response_links' ), $response );
  199. } else {
  200. $links = call_user_func( array( $server, 'get_response_links' ), $response );
  201. }
  202. if ( ! empty( $links ) ) {
  203. $data['_links'] = $links;
  204. }
  205. return $data;
  206. }
  207. /**
  208. * Filters a response based on the context defined in the schema.
  209. *
  210. * @since 4.7.0
  211. *
  212. * @param array $data Response data to fiter.
  213. * @param string $context Context defined in the schema.
  214. * @return array Filtered response.
  215. */
  216. public function filter_response_by_context( $data, $context ) {
  217. $schema = $this->get_item_schema();
  218. foreach ( $data as $key => $value ) {
  219. if ( empty( $schema['properties'][ $key ] ) || empty( $schema['properties'][ $key ]['context'] ) ) {
  220. continue;
  221. }
  222. if ( ! in_array( $context, $schema['properties'][ $key ]['context'], true ) ) {
  223. unset( $data[ $key ] );
  224. continue;
  225. }
  226. if ( 'object' === $schema['properties'][ $key ]['type'] && ! empty( $schema['properties'][ $key ]['properties'] ) ) {
  227. foreach ( $schema['properties'][ $key ]['properties'] as $attribute => $details ) {
  228. if ( empty( $details['context'] ) ) {
  229. continue;
  230. }
  231. if ( ! in_array( $context, $details['context'], true ) ) {
  232. if ( isset( $data[ $key ][ $attribute ] ) ) {
  233. unset( $data[ $key ][ $attribute ] );
  234. }
  235. }
  236. }
  237. }
  238. }
  239. return $data;
  240. }
  241. /**
  242. * Retrieves the item's schema, conforming to JSON Schema.
  243. *
  244. * @since 4.7.0
  245. *
  246. * @return array Item schema data.
  247. */
  248. public function get_item_schema() {
  249. return $this->add_additional_fields_schema( array() );
  250. }
  251. /**
  252. * Retrieves the item's schema for display / public consumption purposes.
  253. *
  254. * @since 4.7.0
  255. *
  256. * @return array Public item schema data.
  257. */
  258. public function get_public_item_schema() {
  259. $schema = $this->get_item_schema();
  260. foreach ( $schema['properties'] as &$property ) {
  261. unset( $property['arg_options'] );
  262. }
  263. return $schema;
  264. }
  265. /**
  266. * Retrieves the query params for the collections.
  267. *
  268. * @since 4.7.0
  269. *
  270. * @return array Query parameters for the collection.
  271. */
  272. public function get_collection_params() {
  273. return array(
  274. 'context' => $this->get_context_param(),
  275. 'page' => array(
  276. 'description' => __( 'Current page of the collection.' ),
  277. 'type' => 'integer',
  278. 'default' => 1,
  279. 'sanitize_callback' => 'absint',
  280. 'validate_callback' => 'rest_validate_request_arg',
  281. 'minimum' => 1,
  282. ),
  283. 'per_page' => array(
  284. 'description' => __( 'Maximum number of items to be returned in result set.' ),
  285. 'type' => 'integer',
  286. 'default' => 10,
  287. 'minimum' => 1,
  288. 'maximum' => 100,
  289. 'sanitize_callback' => 'absint',
  290. 'validate_callback' => 'rest_validate_request_arg',
  291. ),
  292. 'search' => array(
  293. 'description' => __( 'Limit results to those matching a string.' ),
  294. 'type' => 'string',
  295. 'sanitize_callback' => 'sanitize_text_field',
  296. 'validate_callback' => 'rest_validate_request_arg',
  297. ),
  298. );
  299. }
  300. /**
  301. * Retrieves the magical context param.
  302. *
  303. * Ensures consistent descriptions between endpoints, and populates enum from schema.
  304. *
  305. * @since 4.7.0
  306. *
  307. * @param array $args Optional. Additional arguments for context parameter. Default empty array.
  308. * @return array Context parameter details.
  309. */
  310. public function get_context_param( $args = array() ) {
  311. $param_details = array(
  312. 'description' => __( 'Scope under which the request is made; determines fields present in response.' ),
  313. 'type' => 'string',
  314. 'sanitize_callback' => 'sanitize_key',
  315. 'validate_callback' => 'rest_validate_request_arg',
  316. );
  317. $schema = $this->get_item_schema();
  318. if ( empty( $schema['properties'] ) ) {
  319. return array_merge( $param_details, $args );
  320. }
  321. $contexts = array();
  322. foreach ( $schema['properties'] as $attributes ) {
  323. if ( ! empty( $attributes['context'] ) ) {
  324. $contexts = array_merge( $contexts, $attributes['context'] );
  325. }
  326. }
  327. if ( ! empty( $contexts ) ) {
  328. $param_details['enum'] = array_unique( $contexts );
  329. rsort( $param_details['enum'] );
  330. }
  331. return array_merge( $param_details, $args );
  332. }
  333. /**
  334. * Adds the values from additional fields to a data object.
  335. *
  336. * @since 4.7.0
  337. *
  338. * @param array $object Data object.
  339. * @param WP_REST_Request $request Full details about the request.
  340. * @return array Modified data object with additional fields.
  341. */
  342. protected function add_additional_fields_to_object( $object, $request ) {
  343. $additional_fields = $this->get_additional_fields();
  344. foreach ( $additional_fields as $field_name => $field_options ) {
  345. if ( ! $field_options['get_callback'] ) {
  346. continue;
  347. }
  348. $object[ $field_name ] = call_user_func( $field_options['get_callback'], $object, $field_name, $request, $this->get_object_type() );
  349. }
  350. return $object;
  351. }
  352. /**
  353. * Updates the values of additional fields added to a data object.
  354. *
  355. * @since 4.7.0
  356. *
  357. * @param array $object Data Object.
  358. * @param WP_REST_Request $request Full details about the request.
  359. * @return bool|WP_Error True on success, WP_Error object if a field cannot be updated.
  360. */
  361. protected function update_additional_fields_for_object( $object, $request ) {
  362. $additional_fields = $this->get_additional_fields();
  363. foreach ( $additional_fields as $field_name => $field_options ) {
  364. if ( ! $field_options['update_callback'] ) {
  365. continue;
  366. }
  367. // Don't run the update callbacks if the data wasn't passed in the request.
  368. if ( ! isset( $request[ $field_name ] ) ) {
  369. continue;
  370. }
  371. $result = call_user_func( $field_options['update_callback'], $request[ $field_name ], $object, $field_name, $request, $this->get_object_type() );
  372. if ( is_wp_error( $result ) ) {
  373. return $result;
  374. }
  375. }
  376. return true;
  377. }
  378. /**
  379. * Adds the schema from additional fields to a schema array.
  380. *
  381. * The type of object is inferred from the passed schema.
  382. *
  383. * @since 4.7.0
  384. *
  385. * @param array $schema Schema array.
  386. * @return array Modified Schema array.
  387. */
  388. protected function add_additional_fields_schema( $schema ) {
  389. if ( empty( $schema['title'] ) ) {
  390. return $schema;
  391. }
  392. // Can't use $this->get_object_type otherwise we cause an inf loop.
  393. $object_type = $schema['title'];
  394. $additional_fields = $this->get_additional_fields( $object_type );
  395. foreach ( $additional_fields as $field_name => $field_options ) {
  396. if ( ! $field_options['schema'] ) {
  397. continue;
  398. }
  399. $schema['properties'][ $field_name ] = $field_options['schema'];
  400. }
  401. return $schema;
  402. }
  403. /**
  404. * Retrieves all of the registered additional fields for a given object-type.
  405. *
  406. * @since 4.7.0
  407. *
  408. * @param string $object_type Optional. The object type.
  409. * @return array Registered additional fields (if any), empty array if none or if the object type could
  410. * not be inferred.
  411. */
  412. protected function get_additional_fields( $object_type = null ) {
  413. if ( ! $object_type ) {
  414. $object_type = $this->get_object_type();
  415. }
  416. if ( ! $object_type ) {
  417. return array();
  418. }
  419. global $wp_rest_additional_fields;
  420. if ( ! $wp_rest_additional_fields || ! isset( $wp_rest_additional_fields[ $object_type ] ) ) {
  421. return array();
  422. }
  423. return $wp_rest_additional_fields[ $object_type ];
  424. }
  425. /**
  426. * Retrieves the object type this controller is responsible for managing.
  427. *
  428. * @since 4.7.0
  429. *
  430. * @return string Object type for the controller.
  431. */
  432. protected function get_object_type() {
  433. $schema = $this->get_item_schema();
  434. if ( ! $schema || ! isset( $schema['title'] ) ) {
  435. return null;
  436. }
  437. return $schema['title'];
  438. }
  439. /**
  440. * Gets an array of fields to be included on the response.
  441. *
  442. * Included fields are based on item schema and `_fields=` request argument.
  443. *
  444. * @since 4.9.6
  445. *
  446. * @param WP_REST_Request $request Full details about the request.
  447. * @return array Fields to be included in the response.
  448. */
  449. public function get_fields_for_response( $request ) {
  450. $schema = $this->get_item_schema();
  451. $fields = isset( $schema['properties'] ) ? array_keys( $schema['properties'] ) : array();
  452. if ( ! isset( $request['_fields'] ) ) {
  453. return $fields;
  454. }
  455. $requested_fields = is_array( $request['_fields'] ) ? $request['_fields'] : preg_split( '/[\s,]+/', $request['_fields'] );
  456. if ( 0 === count( $requested_fields ) ) {
  457. return $fields;
  458. }
  459. // Trim off outside whitespace from the comma delimited list.
  460. $requested_fields = array_map( 'trim', $requested_fields );
  461. // Always persist 'id', because it can be needed for add_additional_fields_to_object().
  462. if ( in_array( 'id', $fields, true ) ) {
  463. $requested_fields[] = 'id';
  464. }
  465. return array_intersect( $fields, $requested_fields );
  466. }
  467. /**
  468. * Retrieves an array of endpoint arguments from the item schema for the controller.
  469. *
  470. * @since 4.7.0
  471. *
  472. * @param string $method Optional. HTTP method of the request. The arguments for `CREATABLE` requests are
  473. * checked for required values and may fall-back to a given default, this is not done
  474. * on `EDITABLE` requests. Default WP_REST_Server::CREATABLE.
  475. * @return array Endpoint arguments.
  476. */
  477. public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) {
  478. $schema = $this->get_item_schema();
  479. $schema_properties = ! empty( $schema['properties'] ) ? $schema['properties'] : array();
  480. $endpoint_args = array();
  481. foreach ( $schema_properties as $field_id => $params ) {
  482. // Arguments specified as `readonly` are not allowed to be set.
  483. if ( ! empty( $params['readonly'] ) ) {
  484. continue;
  485. }
  486. $endpoint_args[ $field_id ] = array(
  487. 'validate_callback' => 'rest_validate_request_arg',
  488. 'sanitize_callback' => 'rest_sanitize_request_arg',
  489. );
  490. if ( isset( $params['description'] ) ) {
  491. $endpoint_args[ $field_id ]['description'] = $params['description'];
  492. }
  493. if ( WP_REST_Server::CREATABLE === $method && isset( $params['default'] ) ) {
  494. $endpoint_args[ $field_id ]['default'] = $params['default'];
  495. }
  496. if ( WP_REST_Server::CREATABLE === $method && ! empty( $params['required'] ) ) {
  497. $endpoint_args[ $field_id ]['required'] = true;
  498. }
  499. foreach ( array( 'type', 'format', 'enum', 'items', 'properties', 'additionalProperties' ) as $schema_prop ) {
  500. if ( isset( $params[ $schema_prop ] ) ) {
  501. $endpoint_args[ $field_id ][ $schema_prop ] = $params[ $schema_prop ];
  502. }
  503. }
  504. // Merge in any options provided by the schema property.
  505. if ( isset( $params['arg_options'] ) ) {
  506. // Only use required / default from arg_options on CREATABLE endpoints.
  507. if ( WP_REST_Server::CREATABLE !== $method ) {
  508. $params['arg_options'] = array_diff_key( $params['arg_options'], array( 'required' => '', 'default' => '' ) );
  509. }
  510. $endpoint_args[ $field_id ] = array_merge( $endpoint_args[ $field_id ], $params['arg_options'] );
  511. }
  512. }
  513. return $endpoint_args;
  514. }
  515. /**
  516. * Sanitizes the slug value.
  517. *
  518. * @since 4.7.0
  519. *
  520. * @internal We can't use sanitize_title() directly, as the second
  521. * parameter is the fallback title, which would end up being set to the
  522. * request object.
  523. *
  524. * @see https://github.com/WP-API/WP-API/issues/1585
  525. *
  526. * @todo Remove this in favour of https://core.trac.wordpress.org/ticket/34659
  527. *
  528. * @param string $slug Slug value passed in request.
  529. * @return string Sanitized value for the slug.
  530. */
  531. public function sanitize_slug( $slug ) {
  532. return sanitize_title( $slug );
  533. }
  534. }