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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 array
  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. /* translators: %s: PHP class name. */
  62. _doing_it_wrong( __METHOD__, sprintf( __( 'REST search handlers must extend the %s class.' ), 'WP_REST_Search_Handler' ), '5.0.0' );
  63. continue;
  64. }
  65. $this->search_handlers[ $search_handler->get_type() ] = $search_handler;
  66. }
  67. }
  68. /**
  69. * Registers the routes for the objects of the controller.
  70. *
  71. * @since 5.0.0
  72. *
  73. * @see register_rest_route()
  74. */
  75. public function register_routes() {
  76. register_rest_route(
  77. $this->namespace,
  78. '/' . $this->rest_base,
  79. array(
  80. array(
  81. 'methods' => WP_REST_Server::READABLE,
  82. 'callback' => array( $this, 'get_items' ),
  83. 'permission_callback' => array( $this, 'get_items_permission_check' ),
  84. 'args' => $this->get_collection_params(),
  85. ),
  86. 'schema' => array( $this, 'get_public_item_schema' ),
  87. )
  88. );
  89. }
  90. /**
  91. * Checks if a given request has access to search content.
  92. *
  93. * @since 5.0.0
  94. *
  95. * @param WP_REST_Request $request Full details about the request.
  96. * @return true|WP_Error True if the request has search access, WP_Error object otherwise.
  97. */
  98. public function get_items_permission_check( $request ) {
  99. return true;
  100. }
  101. /**
  102. * Retrieves a collection of search results.
  103. *
  104. * @since 5.0.0
  105. *
  106. * @param WP_REST_Request $request Full details about the request.
  107. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  108. */
  109. public function get_items( $request ) {
  110. $handler = $this->get_search_handler( $request );
  111. if ( is_wp_error( $handler ) ) {
  112. return $handler;
  113. }
  114. $result = $handler->search_items( $request );
  115. 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 ] ) ) {
  116. return new WP_Error( 'rest_search_handler_error', __( 'Internal search handler error.' ), array( 'status' => 500 ) );
  117. }
  118. $ids = array_map( 'absint', $result[ WP_REST_Search_Handler::RESULT_IDS ] );
  119. $results = array();
  120. foreach ( $ids as $id ) {
  121. $data = $this->prepare_item_for_response( $id, $request );
  122. $results[] = $this->prepare_response_for_collection( $data );
  123. }
  124. $total = (int) $result[ WP_REST_Search_Handler::RESULT_TOTAL ];
  125. $page = (int) $request['page'];
  126. $per_page = (int) $request['per_page'];
  127. $max_pages = ceil( $total / $per_page );
  128. if ( $page > $max_pages && $total > 0 ) {
  129. return new WP_Error( 'rest_search_invalid_page_number', __( 'The page number requested is larger than the number of pages available.' ), array( 'status' => 400 ) );
  130. }
  131. $response = rest_ensure_response( $results );
  132. $response->header( 'X-WP-Total', $total );
  133. $response->header( 'X-WP-TotalPages', $max_pages );
  134. $request_params = $request->get_query_params();
  135. $base = add_query_arg( urlencode_deep( $request_params ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
  136. if ( $page > 1 ) {
  137. $prev_link = add_query_arg( 'page', $page - 1, $base );
  138. $response->link_header( 'prev', $prev_link );
  139. }
  140. if ( $page < $max_pages ) {
  141. $next_link = add_query_arg( 'page', $page + 1, $base );
  142. $response->link_header( 'next', $next_link );
  143. }
  144. return $response;
  145. }
  146. /**
  147. * Prepares a single search result for response.
  148. *
  149. * @since 5.0.0
  150. *
  151. * @param int $id ID of the item to prepare.
  152. * @param WP_REST_Request $request Request object.
  153. * @return WP_REST_Response Response object.
  154. */
  155. public function prepare_item_for_response( $id, $request ) {
  156. $handler = $this->get_search_handler( $request );
  157. if ( is_wp_error( $handler ) ) {
  158. return new WP_REST_Response();
  159. }
  160. $fields = $this->get_fields_for_response( $request );
  161. $data = $handler->prepare_item( $id, $fields );
  162. $data = $this->add_additional_fields_to_object( $data, $request );
  163. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  164. $data = $this->filter_response_by_context( $data, $context );
  165. $response = rest_ensure_response( $data );
  166. $links = $handler->prepare_item_links( $id );
  167. $links['collection'] = array(
  168. 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
  169. );
  170. $response->add_links( $links );
  171. return $response;
  172. }
  173. /**
  174. * Retrieves the item schema, conforming to JSON Schema.
  175. *
  176. * @since 5.0.0
  177. *
  178. * @return array Item schema data.
  179. */
  180. public function get_item_schema() {
  181. if ( $this->schema ) {
  182. return $this->add_additional_fields_schema( $this->schema );
  183. }
  184. $types = array();
  185. $subtypes = array();
  186. foreach ( $this->search_handlers as $search_handler ) {
  187. $types[] = $search_handler->get_type();
  188. $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() );
  189. }
  190. $types = array_unique( $types );
  191. $subtypes = array_unique( $subtypes );
  192. $schema = array(
  193. '$schema' => 'http://json-schema.org/draft-04/schema#',
  194. 'title' => 'search-result',
  195. 'type' => 'object',
  196. 'properties' => array(
  197. self::PROP_ID => array(
  198. 'description' => __( 'Unique identifier for the object.' ),
  199. 'type' => 'integer',
  200. 'context' => array( 'view', 'embed' ),
  201. 'readonly' => true,
  202. ),
  203. self::PROP_TITLE => array(
  204. 'description' => __( 'The title for the object.' ),
  205. 'type' => 'string',
  206. 'context' => array( 'view', 'embed' ),
  207. 'readonly' => true,
  208. ),
  209. self::PROP_URL => array(
  210. 'description' => __( 'URL to the object.' ),
  211. 'type' => 'string',
  212. 'format' => 'uri',
  213. 'context' => array( 'view', 'embed' ),
  214. 'readonly' => true,
  215. ),
  216. self::PROP_TYPE => array(
  217. 'description' => __( 'Object type.' ),
  218. 'type' => 'string',
  219. 'enum' => $types,
  220. 'context' => array( 'view', 'embed' ),
  221. 'readonly' => true,
  222. ),
  223. self::PROP_SUBTYPE => array(
  224. 'description' => __( 'Object subtype.' ),
  225. 'type' => 'string',
  226. 'enum' => $subtypes,
  227. 'context' => array( 'view', 'embed' ),
  228. 'readonly' => true,
  229. ),
  230. ),
  231. );
  232. $this->schema = $schema;
  233. return $this->add_additional_fields_schema( $this->schema );
  234. }
  235. /**
  236. * Retrieves the query params for the search results collection.
  237. *
  238. * @since 5.0.0
  239. *
  240. * @return array Collection parameters.
  241. */
  242. public function get_collection_params() {
  243. $types = array();
  244. $subtypes = array();
  245. foreach ( $this->search_handlers as $search_handler ) {
  246. $types[] = $search_handler->get_type();
  247. $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() );
  248. }
  249. $types = array_unique( $types );
  250. $subtypes = array_unique( $subtypes );
  251. $query_params = parent::get_collection_params();
  252. $query_params['context']['default'] = 'view';
  253. $query_params[ self::PROP_TYPE ] = array(
  254. 'default' => $types[0],
  255. 'description' => __( 'Limit results to items of an object type.' ),
  256. 'type' => 'string',
  257. 'enum' => $types,
  258. );
  259. $query_params[ self::PROP_SUBTYPE ] = array(
  260. 'default' => self::TYPE_ANY,
  261. 'description' => __( 'Limit results to items of one or more object subtypes.' ),
  262. 'type' => 'array',
  263. 'items' => array(
  264. 'enum' => array_merge( $subtypes, array( self::TYPE_ANY ) ),
  265. 'type' => 'string',
  266. ),
  267. 'sanitize_callback' => array( $this, 'sanitize_subtypes' ),
  268. );
  269. return $query_params;
  270. }
  271. /**
  272. * Sanitizes the list of subtypes, to ensure only subtypes of the passed type are included.
  273. *
  274. * @since 5.0.0
  275. *
  276. * @param string|array $subtypes One or more subtypes.
  277. * @param WP_REST_Request $request Full details about the request.
  278. * @param string $parameter Parameter name.
  279. * @return array|WP_Error List of valid subtypes, or WP_Error object on failure.
  280. */
  281. public function sanitize_subtypes( $subtypes, $request, $parameter ) {
  282. $subtypes = wp_parse_slug_list( $subtypes );
  283. $subtypes = rest_parse_request_arg( $subtypes, $request, $parameter );
  284. if ( is_wp_error( $subtypes ) ) {
  285. return $subtypes;
  286. }
  287. // 'any' overrides any other subtype.
  288. if ( in_array( self::TYPE_ANY, $subtypes, true ) ) {
  289. return array( self::TYPE_ANY );
  290. }
  291. $handler = $this->get_search_handler( $request );
  292. if ( is_wp_error( $handler ) ) {
  293. return $handler;
  294. }
  295. return array_intersect( $subtypes, $handler->get_subtypes() );
  296. }
  297. /**
  298. * Gets the search handler to handle the current request.
  299. *
  300. * @since 5.0.0
  301. *
  302. * @param WP_REST_Request $request Full details about the request.
  303. * @return WP_REST_Search_Handler|WP_Error Search handler for the request type, or WP_Error object on failure.
  304. */
  305. protected function get_search_handler( $request ) {
  306. $type = $request->get_param( self::PROP_TYPE );
  307. if ( ! $type || ! isset( $this->search_handlers[ $type ] ) ) {
  308. return new WP_Error( 'rest_search_invalid_type', __( 'Invalid type parameter.' ), array( 'status' => 400 ) );
  309. }
  310. return $this->search_handlers[ $type ];
  311. }
  312. }