class-wp-rest-search-controller.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. /**
  3. * REST API: WP_REST_Search_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 5.0.0
  8. */
  9. /**
  10. * Core class to search through all WordPress content via the REST API.
  11. *
  12. * @since 5.0.0
  13. *
  14. * @see WP_REST_Controller
  15. */
  16. class WP_REST_Search_Controller extends WP_REST_Controller {
  17. /**
  18. * ID property name.
  19. */
  20. const PROP_ID = 'id';
  21. /**
  22. * Title property name.
  23. */
  24. const PROP_TITLE = 'title';
  25. /**
  26. * URL property name.
  27. */
  28. const PROP_URL = 'url';
  29. /**
  30. * Type property name.
  31. */
  32. const PROP_TYPE = 'type';
  33. /**
  34. * Subtype property name.
  35. */
  36. const PROP_SUBTYPE = 'subtype';
  37. /**
  38. * Identifier for the 'any' type.
  39. */
  40. const TYPE_ANY = 'any';
  41. /**
  42. * Search handlers used by the controller.
  43. *
  44. * @since 5.0.0
  45. * @var WP_REST_Search_Handler[]
  46. */
  47. protected $search_handlers = array();
  48. /**
  49. * Constructor.
  50. *
  51. * @since 5.0.0
  52. *
  53. * @param array $search_handlers List of search handlers to use in the controller. Each search
  54. * handler instance must extend the `WP_REST_Search_Handler` class.
  55. */
  56. public function __construct( array $search_handlers ) {
  57. $this->namespace = 'wp/v2';
  58. $this->rest_base = 'search';
  59. foreach ( $search_handlers as $search_handler ) {
  60. if ( ! $search_handler instanceof WP_REST_Search_Handler ) {
  61. _doing_it_wrong(
  62. __METHOD__,
  63. /* translators: %s: PHP class name. */
  64. sprintf( __( 'REST search handlers must extend the %s class.' ), 'WP_REST_Search_Handler' ),
  65. '5.0.0'
  66. );
  67. continue;
  68. }
  69. $this->search_handlers[ $search_handler->get_type() ] = $search_handler;
  70. }
  71. }
  72. /**
  73. * Registers the routes for the search controller.
  74. *
  75. * @since 5.0.0
  76. *
  77. * @see register_rest_route()
  78. */
  79. public function register_routes() {
  80. register_rest_route(
  81. $this->namespace,
  82. '/' . $this->rest_base,
  83. array(
  84. array(
  85. 'methods' => WP_REST_Server::READABLE,
  86. 'callback' => array( $this, 'get_items' ),
  87. 'permission_callback' => array( $this, 'get_items_permission_check' ),
  88. 'args' => $this->get_collection_params(),
  89. ),
  90. 'schema' => array( $this, 'get_public_item_schema' ),
  91. )
  92. );
  93. }
  94. /**
  95. * Checks if a given request has access to search content.
  96. *
  97. * @since 5.0.0
  98. *
  99. * @param WP_REST_Request $request Full details about the request.
  100. * @return true|WP_Error True if the request has search access, WP_Error object otherwise.
  101. */
  102. public function get_items_permission_check( $request ) {
  103. return true;
  104. }
  105. /**
  106. * Retrieves a collection of search results.
  107. *
  108. * @since 5.0.0
  109. *
  110. * @param WP_REST_Request $request Full details about the request.
  111. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  112. */
  113. public function get_items( $request ) {
  114. $handler = $this->get_search_handler( $request );
  115. if ( is_wp_error( $handler ) ) {
  116. return $handler;
  117. }
  118. $result = $handler->search_items( $request );
  119. if ( ! isset( $result[ WP_REST_Search_Handler::RESULT_IDS ] ) || ! is_array( $result[ WP_REST_Search_Handler::RESULT_IDS ] ) || ! isset( $result[ WP_REST_Search_Handler::RESULT_TOTAL ] ) ) {
  120. return new WP_Error(
  121. 'rest_search_handler_error',
  122. __( 'Internal search handler error.' ),
  123. array( 'status' => 500 )
  124. );
  125. }
  126. $ids = $result[ WP_REST_Search_Handler::RESULT_IDS ];
  127. $results = array();
  128. foreach ( $ids as $id ) {
  129. $data = $this->prepare_item_for_response( $id, $request );
  130. $results[] = $this->prepare_response_for_collection( $data );
  131. }
  132. $total = (int) $result[ WP_REST_Search_Handler::RESULT_TOTAL ];
  133. $page = (int) $request['page'];
  134. $per_page = (int) $request['per_page'];
  135. $max_pages = ceil( $total / $per_page );
  136. if ( $page > $max_pages && $total > 0 ) {
  137. return new WP_Error(
  138. 'rest_search_invalid_page_number',
  139. __( 'The page number requested is larger than the number of pages available.' ),
  140. array( 'status' => 400 )
  141. );
  142. }
  143. $response = rest_ensure_response( $results );
  144. $response->header( 'X-WP-Total', $total );
  145. $response->header( 'X-WP-TotalPages', $max_pages );
  146. $request_params = $request->get_query_params();
  147. $base = add_query_arg( urlencode_deep( $request_params ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
  148. if ( $page > 1 ) {
  149. $prev_link = add_query_arg( 'page', $page - 1, $base );
  150. $response->link_header( 'prev', $prev_link );
  151. }
  152. if ( $page < $max_pages ) {
  153. $next_link = add_query_arg( 'page', $page + 1, $base );
  154. $response->link_header( 'next', $next_link );
  155. }
  156. return $response;
  157. }
  158. /**
  159. * Prepares a single search result for response.
  160. *
  161. * @since 5.0.0
  162. * @since 5.6.0 The `$id` parameter can accept a string.
  163. * @since 5.9.0 Renamed `$id` to `$item` to match parent class for PHP 8 named parameter support.
  164. *
  165. * @param int|string $item ID of the item to prepare.
  166. * @param WP_REST_Request $request Request object.
  167. * @return WP_REST_Response Response object.
  168. */
  169. public function prepare_item_for_response( $item, $request ) {
  170. // Restores the more descriptive, specific name for use within this method.
  171. $item_id = $item;
  172. $handler = $this->get_search_handler( $request );
  173. if ( is_wp_error( $handler ) ) {
  174. return new WP_REST_Response();
  175. }
  176. $fields = $this->get_fields_for_response( $request );
  177. $data = $handler->prepare_item( $item_id, $fields );
  178. $data = $this->add_additional_fields_to_object( $data, $request );
  179. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  180. $data = $this->filter_response_by_context( $data, $context );
  181. $response = rest_ensure_response( $data );
  182. if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
  183. $links = $handler->prepare_item_links( $item_id );
  184. $links['collection'] = array(
  185. 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
  186. );
  187. $response->add_links( $links );
  188. }
  189. return $response;
  190. }
  191. /**
  192. * Retrieves the item schema, conforming to JSON Schema.
  193. *
  194. * @since 5.0.0
  195. *
  196. * @return array Item schema data.
  197. */
  198. public function get_item_schema() {
  199. if ( $this->schema ) {
  200. return $this->add_additional_fields_schema( $this->schema );
  201. }
  202. $types = array();
  203. $subtypes = array();
  204. foreach ( $this->search_handlers as $search_handler ) {
  205. $types[] = $search_handler->get_type();
  206. $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() );
  207. }
  208. $types = array_unique( $types );
  209. $subtypes = array_unique( $subtypes );
  210. $schema = array(
  211. '$schema' => 'http://json-schema.org/draft-04/schema#',
  212. 'title' => 'search-result',
  213. 'type' => 'object',
  214. 'properties' => array(
  215. self::PROP_ID => array(
  216. 'description' => __( 'Unique identifier for the object.' ),
  217. 'type' => array( 'integer', 'string' ),
  218. 'context' => array( 'view', 'embed' ),
  219. 'readonly' => true,
  220. ),
  221. self::PROP_TITLE => array(
  222. 'description' => __( 'The title for the object.' ),
  223. 'type' => 'string',
  224. 'context' => array( 'view', 'embed' ),
  225. 'readonly' => true,
  226. ),
  227. self::PROP_URL => array(
  228. 'description' => __( 'URL to the object.' ),
  229. 'type' => 'string',
  230. 'format' => 'uri',
  231. 'context' => array( 'view', 'embed' ),
  232. 'readonly' => true,
  233. ),
  234. self::PROP_TYPE => array(
  235. 'description' => __( 'Object type.' ),
  236. 'type' => 'string',
  237. 'enum' => $types,
  238. 'context' => array( 'view', 'embed' ),
  239. 'readonly' => true,
  240. ),
  241. self::PROP_SUBTYPE => array(
  242. 'description' => __( 'Object subtype.' ),
  243. 'type' => 'string',
  244. 'enum' => $subtypes,
  245. 'context' => array( 'view', 'embed' ),
  246. 'readonly' => true,
  247. ),
  248. ),
  249. );
  250. $this->schema = $schema;
  251. return $this->add_additional_fields_schema( $this->schema );
  252. }
  253. /**
  254. * Retrieves the query params for the search results collection.
  255. *
  256. * @since 5.0.0
  257. *
  258. * @return array Collection parameters.
  259. */
  260. public function get_collection_params() {
  261. $types = array();
  262. $subtypes = array();
  263. foreach ( $this->search_handlers as $search_handler ) {
  264. $types[] = $search_handler->get_type();
  265. $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() );
  266. }
  267. $types = array_unique( $types );
  268. $subtypes = array_unique( $subtypes );
  269. $query_params = parent::get_collection_params();
  270. $query_params['context']['default'] = 'view';
  271. $query_params[ self::PROP_TYPE ] = array(
  272. 'default' => $types[0],
  273. 'description' => __( 'Limit results to items of an object type.' ),
  274. 'type' => 'string',
  275. 'enum' => $types,
  276. );
  277. $query_params[ self::PROP_SUBTYPE ] = array(
  278. 'default' => self::TYPE_ANY,
  279. 'description' => __( 'Limit results to items of one or more object subtypes.' ),
  280. 'type' => 'array',
  281. 'items' => array(
  282. 'enum' => array_merge( $subtypes, array( self::TYPE_ANY ) ),
  283. 'type' => 'string',
  284. ),
  285. 'sanitize_callback' => array( $this, 'sanitize_subtypes' ),
  286. );
  287. $query_params['exclude'] = array(
  288. 'description' => __( 'Ensure result set excludes specific IDs.' ),
  289. 'type' => 'array',
  290. 'items' => array(
  291. 'type' => 'integer',
  292. ),
  293. 'default' => array(),
  294. );
  295. $query_params['include'] = array(
  296. 'description' => __( 'Limit result set to specific IDs.' ),
  297. 'type' => 'array',
  298. 'items' => array(
  299. 'type' => 'integer',
  300. ),
  301. 'default' => array(),
  302. );
  303. return $query_params;
  304. }
  305. /**
  306. * Sanitizes the list of subtypes, to ensure only subtypes of the passed type are included.
  307. *
  308. * @since 5.0.0
  309. *
  310. * @param string|array $subtypes One or more subtypes.
  311. * @param WP_REST_Request $request Full details about the request.
  312. * @param string $parameter Parameter name.
  313. * @return array|WP_Error List of valid subtypes, or WP_Error object on failure.
  314. */
  315. public function sanitize_subtypes( $subtypes, $request, $parameter ) {
  316. $subtypes = wp_parse_slug_list( $subtypes );
  317. $subtypes = rest_parse_request_arg( $subtypes, $request, $parameter );
  318. if ( is_wp_error( $subtypes ) ) {
  319. return $subtypes;
  320. }
  321. // 'any' overrides any other subtype.
  322. if ( in_array( self::TYPE_ANY, $subtypes, true ) ) {
  323. return array( self::TYPE_ANY );
  324. }
  325. $handler = $this->get_search_handler( $request );
  326. if ( is_wp_error( $handler ) ) {
  327. return $handler;
  328. }
  329. return array_intersect( $subtypes, $handler->get_subtypes() );
  330. }
  331. /**
  332. * Gets the search handler to handle the current request.
  333. *
  334. * @since 5.0.0
  335. *
  336. * @param WP_REST_Request $request Full details about the request.
  337. * @return WP_REST_Search_Handler|WP_Error Search handler for the request type, or WP_Error object on failure.
  338. */
  339. protected function get_search_handler( $request ) {
  340. $type = $request->get_param( self::PROP_TYPE );
  341. if ( ! $type || ! isset( $this->search_handlers[ $type ] ) ) {
  342. return new WP_Error(
  343. 'rest_search_invalid_type',
  344. __( 'Invalid type parameter.' ),
  345. array( 'status' => 400 )
  346. );
  347. }
  348. return $this->search_handlers[ $type ];
  349. }
  350. }