PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php

https://gitlab.com/campus-academy/krowkaramel
PHP | 387 lines | 217 code | 55 blank | 115 comment | 16 complexity | 2960f4de31aa51baa044143ba1b1375a MD5 | raw file
  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. $links = $handler->prepare_item_links( $item_id );
  183. $links['collection'] = array(
  184. 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
  185. );
  186. $response->add_links( $links );
  187. return $response;
  188. }
  189. /**
  190. * Retrieves the item schema, conforming to JSON Schema.
  191. *
  192. * @since 5.0.0
  193. *
  194. * @return array Item schema data.
  195. */
  196. public function get_item_schema() {
  197. if ( $this->schema ) {
  198. return $this->add_additional_fields_schema( $this->schema );
  199. }
  200. $types = array();
  201. $subtypes = array();
  202. foreach ( $this->search_handlers as $search_handler ) {
  203. $types[] = $search_handler->get_type();
  204. $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() );
  205. }
  206. $types = array_unique( $types );
  207. $subtypes = array_unique( $subtypes );
  208. $schema = array(
  209. '$schema' => 'http://json-schema.org/draft-04/schema#',
  210. 'title' => 'search-result',
  211. 'type' => 'object',
  212. 'properties' => array(
  213. self::PROP_ID => array(
  214. 'description' => __( 'Unique identifier for the object.' ),
  215. 'type' => array( 'integer', 'string' ),
  216. 'context' => array( 'view', 'embed' ),
  217. 'readonly' => true,
  218. ),
  219. self::PROP_TITLE => array(
  220. 'description' => __( 'The title for the object.' ),
  221. 'type' => 'string',
  222. 'context' => array( 'view', 'embed' ),
  223. 'readonly' => true,
  224. ),
  225. self::PROP_URL => array(
  226. 'description' => __( 'URL to the object.' ),
  227. 'type' => 'string',
  228. 'format' => 'uri',
  229. 'context' => array( 'view', 'embed' ),
  230. 'readonly' => true,
  231. ),
  232. self::PROP_TYPE => array(
  233. 'description' => __( 'Object type.' ),
  234. 'type' => 'string',
  235. 'enum' => $types,
  236. 'context' => array( 'view', 'embed' ),
  237. 'readonly' => true,
  238. ),
  239. self::PROP_SUBTYPE => array(
  240. 'description' => __( 'Object subtype.' ),
  241. 'type' => 'string',
  242. 'enum' => $subtypes,
  243. 'context' => array( 'view', 'embed' ),
  244. 'readonly' => true,
  245. ),
  246. ),
  247. );
  248. $this->schema = $schema;
  249. return $this->add_additional_fields_schema( $this->schema );
  250. }
  251. /**
  252. * Retrieves the query params for the search results collection.
  253. *
  254. * @since 5.0.0
  255. *
  256. * @return array Collection parameters.
  257. */
  258. public function get_collection_params() {
  259. $types = array();
  260. $subtypes = array();
  261. foreach ( $this->search_handlers as $search_handler ) {
  262. $types[] = $search_handler->get_type();
  263. $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() );
  264. }
  265. $types = array_unique( $types );
  266. $subtypes = array_unique( $subtypes );
  267. $query_params = parent::get_collection_params();
  268. $query_params['context']['default'] = 'view';
  269. $query_params[ self::PROP_TYPE ] = array(
  270. 'default' => $types[0],
  271. 'description' => __( 'Limit results to items of an object type.' ),
  272. 'type' => 'string',
  273. 'enum' => $types,
  274. );
  275. $query_params[ self::PROP_SUBTYPE ] = array(
  276. 'default' => self::TYPE_ANY,
  277. 'description' => __( 'Limit results to items of one or more object subtypes.' ),
  278. 'type' => 'array',
  279. 'items' => array(
  280. 'enum' => array_merge( $subtypes, array( self::TYPE_ANY ) ),
  281. 'type' => 'string',
  282. ),
  283. 'sanitize_callback' => array( $this, 'sanitize_subtypes' ),
  284. );
  285. return $query_params;
  286. }
  287. /**
  288. * Sanitizes the list of subtypes, to ensure only subtypes of the passed type are included.
  289. *
  290. * @since 5.0.0
  291. *
  292. * @param string|array $subtypes One or more subtypes.
  293. * @param WP_REST_Request $request Full details about the request.
  294. * @param string $parameter Parameter name.
  295. * @return array|WP_Error List of valid subtypes, or WP_Error object on failure.
  296. */
  297. public function sanitize_subtypes( $subtypes, $request, $parameter ) {
  298. $subtypes = wp_parse_slug_list( $subtypes );
  299. $subtypes = rest_parse_request_arg( $subtypes, $request, $parameter );
  300. if ( is_wp_error( $subtypes ) ) {
  301. return $subtypes;
  302. }
  303. // 'any' overrides any other subtype.
  304. if ( in_array( self::TYPE_ANY, $subtypes, true ) ) {
  305. return array( self::TYPE_ANY );
  306. }
  307. $handler = $this->get_search_handler( $request );
  308. if ( is_wp_error( $handler ) ) {
  309. return $handler;
  310. }
  311. return array_intersect( $subtypes, $handler->get_subtypes() );
  312. }
  313. /**
  314. * Gets the search handler to handle the current request.
  315. *
  316. * @since 5.0.0
  317. *
  318. * @param WP_REST_Request $request Full details about the request.
  319. * @return WP_REST_Search_Handler|WP_Error Search handler for the request type, or WP_Error object on failure.
  320. */
  321. protected function get_search_handler( $request ) {
  322. $type = $request->get_param( self::PROP_TYPE );
  323. if ( ! $type || ! isset( $this->search_handlers[ $type ] ) ) {
  324. return new WP_Error(
  325. 'rest_search_invalid_type',
  326. __( 'Invalid type parameter.' ),
  327. array( 'status' => 400 )
  328. );
  329. }
  330. return $this->search_handlers[ $type ];
  331. }
  332. }