class-wp-rest-menu-items-controller.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. <?php
  2. /**
  3. * REST API: WP_REST_Menu_Items_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 5.9.0
  8. */
  9. /**
  10. * Core class to access nav items via the REST API.
  11. *
  12. * @since 5.9.0
  13. *
  14. * @see WP_REST_Posts_Controller
  15. */
  16. class WP_REST_Menu_Items_Controller extends WP_REST_Posts_Controller {
  17. /**
  18. * Gets the nav menu item, if the ID is valid.
  19. *
  20. * @since 5.9.0
  21. *
  22. * @param int $id Supplied ID.
  23. * @return object|WP_Error Post object if ID is valid, WP_Error otherwise.
  24. */
  25. protected function get_nav_menu_item( $id ) {
  26. $post = $this->get_post( $id );
  27. if ( is_wp_error( $post ) ) {
  28. return $post;
  29. }
  30. return wp_setup_nav_menu_item( $post );
  31. }
  32. /**
  33. * Checks if a given request has access to read menu items.
  34. *
  35. * @since 5.9.0
  36. *
  37. * @param WP_REST_Request $request Full details about the request.
  38. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  39. */
  40. public function get_items_permissions_check( $request ) {
  41. $has_permission = parent::get_items_permissions_check( $request );
  42. if ( true !== $has_permission ) {
  43. return $has_permission;
  44. }
  45. return $this->check_has_read_only_access( $request );
  46. }
  47. /**
  48. * Checks if a given request has access to read a menu item if they have access to edit them.
  49. *
  50. * @since 5.9.0
  51. *
  52. * @param WP_REST_Request $request Full details about the request.
  53. * @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  54. */
  55. public function get_item_permissions_check( $request ) {
  56. $permission_check = parent::get_item_permissions_check( $request );
  57. if ( true !== $permission_check ) {
  58. return $permission_check;
  59. }
  60. return $this->check_has_read_only_access( $request );
  61. }
  62. /**
  63. * Checks whether the current user has read permission for the endpoint.
  64. *
  65. * This allows for any user that can `edit_theme_options` or edit any REST API available post type.
  66. *
  67. * @since 5.9.0
  68. *
  69. * @param WP_REST_Request $request Full details about the request.
  70. * @return bool|WP_Error Whether the current user has permission.
  71. */
  72. protected function check_has_read_only_access( $request ) {
  73. if ( current_user_can( 'edit_theme_options' ) ) {
  74. return true;
  75. }
  76. if ( current_user_can( 'edit_posts' ) ) {
  77. return true;
  78. }
  79. foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
  80. if ( current_user_can( $post_type->cap->edit_posts ) ) {
  81. return true;
  82. }
  83. }
  84. return new WP_Error(
  85. 'rest_cannot_view',
  86. __( 'Sorry, you are not allowed to view menu items.' ),
  87. array( 'status' => rest_authorization_required_code() )
  88. );
  89. }
  90. /**
  91. * Creates a single post.
  92. *
  93. * @since 5.9.0
  94. *
  95. * @param WP_REST_Request $request Full details about the request.
  96. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  97. */
  98. public function create_item( $request ) {
  99. if ( ! empty( $request['id'] ) ) {
  100. return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
  101. }
  102. $prepared_nav_item = $this->prepare_item_for_database( $request );
  103. if ( is_wp_error( $prepared_nav_item ) ) {
  104. return $prepared_nav_item;
  105. }
  106. $prepared_nav_item = (array) $prepared_nav_item;
  107. $nav_menu_item_id = wp_update_nav_menu_item( $prepared_nav_item['menu-id'], $prepared_nav_item['menu-item-db-id'], wp_slash( $prepared_nav_item ), false );
  108. if ( is_wp_error( $nav_menu_item_id ) ) {
  109. if ( 'db_insert_error' === $nav_menu_item_id->get_error_code() ) {
  110. $nav_menu_item_id->add_data( array( 'status' => 500 ) );
  111. } else {
  112. $nav_menu_item_id->add_data( array( 'status' => 400 ) );
  113. }
  114. return $nav_menu_item_id;
  115. }
  116. $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
  117. if ( is_wp_error( $nav_menu_item ) ) {
  118. $nav_menu_item->add_data( array( 'status' => 404 ) );
  119. return $nav_menu_item;
  120. }
  121. /**
  122. * Fires after a single menu item is created or updated via the REST API.
  123. *
  124. * @since 5.9.0
  125. *
  126. * @param object $nav_menu_item Inserted or updated menu item object.
  127. * @param WP_REST_Request $request Request object.
  128. * @param bool $creating True when creating a menu item, false when updating.
  129. */
  130. do_action( 'rest_insert_nav_menu_item', $nav_menu_item, $request, true );
  131. $schema = $this->get_item_schema();
  132. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  133. $meta_update = $this->meta->update_value( $request['meta'], $nav_menu_item_id );
  134. if ( is_wp_error( $meta_update ) ) {
  135. return $meta_update;
  136. }
  137. }
  138. $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
  139. $fields_update = $this->update_additional_fields_for_object( $nav_menu_item, $request );
  140. if ( is_wp_error( $fields_update ) ) {
  141. return $fields_update;
  142. }
  143. $request->set_param( 'context', 'edit' );
  144. /**
  145. * Fires after a single menu item is completely created or updated via the REST API.
  146. *
  147. * @since 5.9.0
  148. *
  149. * @param object $nav_menu_item Inserted or updated menu item object.
  150. * @param WP_REST_Request $request Request object.
  151. * @param bool $creating True when creating a menu item, false when updating.
  152. */
  153. do_action( 'rest_after_insert_nav_menu_item', $nav_menu_item, $request, true );
  154. $post = get_post( $nav_menu_item_id );
  155. wp_after_insert_post( $post, false, null );
  156. $response = $this->prepare_item_for_response( $post, $request );
  157. $response = rest_ensure_response( $response );
  158. $response->set_status( 201 );
  159. $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $nav_menu_item_id ) ) );
  160. return $response;
  161. }
  162. /**
  163. * Updates a single nav menu item.
  164. *
  165. * @since 5.9.0
  166. *
  167. * @param WP_REST_Request $request Full details about the request.
  168. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  169. */
  170. public function update_item( $request ) {
  171. $valid_check = $this->get_nav_menu_item( $request['id'] );
  172. if ( is_wp_error( $valid_check ) ) {
  173. return $valid_check;
  174. }
  175. $post_before = get_post( $request['id'] );
  176. $prepared_nav_item = $this->prepare_item_for_database( $request );
  177. if ( is_wp_error( $prepared_nav_item ) ) {
  178. return $prepared_nav_item;
  179. }
  180. $prepared_nav_item = (array) $prepared_nav_item;
  181. $nav_menu_item_id = wp_update_nav_menu_item( $prepared_nav_item['menu-id'], $prepared_nav_item['menu-item-db-id'], wp_slash( $prepared_nav_item ), false );
  182. if ( is_wp_error( $nav_menu_item_id ) ) {
  183. if ( 'db_update_error' === $nav_menu_item_id->get_error_code() ) {
  184. $nav_menu_item_id->add_data( array( 'status' => 500 ) );
  185. } else {
  186. $nav_menu_item_id->add_data( array( 'status' => 400 ) );
  187. }
  188. return $nav_menu_item_id;
  189. }
  190. $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
  191. if ( is_wp_error( $nav_menu_item ) ) {
  192. $nav_menu_item->add_data( array( 'status' => 404 ) );
  193. return $nav_menu_item;
  194. }
  195. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php */
  196. do_action( 'rest_insert_nav_menu_item', $nav_menu_item, $request, false );
  197. $schema = $this->get_item_schema();
  198. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  199. $meta_update = $this->meta->update_value( $request['meta'], $nav_menu_item->ID );
  200. if ( is_wp_error( $meta_update ) ) {
  201. return $meta_update;
  202. }
  203. }
  204. $post = get_post( $nav_menu_item_id );
  205. $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
  206. $fields_update = $this->update_additional_fields_for_object( $nav_menu_item, $request );
  207. if ( is_wp_error( $fields_update ) ) {
  208. return $fields_update;
  209. }
  210. $request->set_param( 'context', 'edit' );
  211. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php */
  212. do_action( 'rest_after_insert_nav_menu_item', $nav_menu_item, $request, false );
  213. wp_after_insert_post( $post, true, $post_before );
  214. $response = $this->prepare_item_for_response( get_post( $nav_menu_item_id ), $request );
  215. return rest_ensure_response( $response );
  216. }
  217. /**
  218. * Deletes a single menu item.
  219. *
  220. * @since 5.9.0
  221. *
  222. * @param WP_REST_Request $request Full details about the request.
  223. * @return WP_REST_Response|WP_Error True on success, or WP_Error object on failure.
  224. */
  225. public function delete_item( $request ) {
  226. $menu_item = $this->get_nav_menu_item( $request['id'] );
  227. if ( is_wp_error( $menu_item ) ) {
  228. return $menu_item;
  229. }
  230. // We don't support trashing for menu items.
  231. if ( ! $request['force'] ) {
  232. /* translators: %s: force=true */
  233. return new WP_Error( 'rest_trash_not_supported', sprintf( __( "Menu items do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) );
  234. }
  235. $previous = $this->prepare_item_for_response( get_post( $request['id'] ), $request );
  236. $result = wp_delete_post( $request['id'], true );
  237. if ( ! $result ) {
  238. return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
  239. }
  240. $response = new WP_REST_Response();
  241. $response->set_data(
  242. array(
  243. 'deleted' => true,
  244. 'previous' => $previous->get_data(),
  245. )
  246. );
  247. /**
  248. * Fires immediately after a single menu item is deleted via the REST API.
  249. *
  250. * @since 5.9.0
  251. *
  252. * @param object $nav_menu_item Inserted or updated menu item object.
  253. * @param WP_REST_Response $response The response data.
  254. * @param WP_REST_Request $request Request object.
  255. */
  256. do_action( 'rest_delete_nav_menu_item', $menu_item, $response, $request );
  257. return $response;
  258. }
  259. /**
  260. * Prepares a single post for create or update.
  261. *
  262. * @since 5.9.0
  263. *
  264. * @param WP_REST_Request $request Request object.
  265. *
  266. * @return object|WP_Error
  267. */
  268. protected function prepare_item_for_database( $request ) {
  269. $menu_item_db_id = $request['id'];
  270. $menu_item_obj = $this->get_nav_menu_item( $menu_item_db_id );
  271. // Need to persist the menu item data. See https://core.trac.wordpress.org/ticket/28138
  272. if ( ! is_wp_error( $menu_item_obj ) ) {
  273. // Correct the menu position if this was the first item. See https://core.trac.wordpress.org/ticket/28140
  274. $position = ( 0 === $menu_item_obj->menu_order ) ? 1 : $menu_item_obj->menu_order;
  275. $prepared_nav_item = array(
  276. 'menu-item-db-id' => $menu_item_db_id,
  277. 'menu-item-object-id' => $menu_item_obj->object_id,
  278. 'menu-item-object' => $menu_item_obj->object,
  279. 'menu-item-parent-id' => $menu_item_obj->menu_item_parent,
  280. 'menu-item-position' => $position,
  281. 'menu-item-type' => $menu_item_obj->type,
  282. 'menu-item-title' => $menu_item_obj->title,
  283. 'menu-item-url' => $menu_item_obj->url,
  284. 'menu-item-description' => $menu_item_obj->description,
  285. 'menu-item-attr-title' => $menu_item_obj->attr_title,
  286. 'menu-item-target' => $menu_item_obj->target,
  287. 'menu-item-classes' => $menu_item_obj->classes,
  288. // Stored in the database as a string.
  289. 'menu-item-xfn' => explode( ' ', $menu_item_obj->xfn ),
  290. 'menu-item-status' => $menu_item_obj->post_status,
  291. 'menu-id' => $this->get_menu_id( $menu_item_db_id ),
  292. );
  293. } else {
  294. $prepared_nav_item = array(
  295. 'menu-id' => 0,
  296. 'menu-item-db-id' => 0,
  297. 'menu-item-object-id' => 0,
  298. 'menu-item-object' => '',
  299. 'menu-item-parent-id' => 0,
  300. 'menu-item-position' => 1,
  301. 'menu-item-type' => 'custom',
  302. 'menu-item-title' => '',
  303. 'menu-item-url' => '',
  304. 'menu-item-description' => '',
  305. 'menu-item-attr-title' => '',
  306. 'menu-item-target' => '',
  307. 'menu-item-classes' => array(),
  308. 'menu-item-xfn' => array(),
  309. 'menu-item-status' => 'publish',
  310. );
  311. }
  312. $mapping = array(
  313. 'menu-item-db-id' => 'id',
  314. 'menu-item-object-id' => 'object_id',
  315. 'menu-item-object' => 'object',
  316. 'menu-item-parent-id' => 'parent',
  317. 'menu-item-position' => 'menu_order',
  318. 'menu-item-type' => 'type',
  319. 'menu-item-url' => 'url',
  320. 'menu-item-description' => 'description',
  321. 'menu-item-attr-title' => 'attr_title',
  322. 'menu-item-target' => 'target',
  323. 'menu-item-classes' => 'classes',
  324. 'menu-item-xfn' => 'xfn',
  325. 'menu-item-status' => 'status',
  326. );
  327. $schema = $this->get_item_schema();
  328. foreach ( $mapping as $original => $api_request ) {
  329. if ( isset( $request[ $api_request ] ) ) {
  330. $prepared_nav_item[ $original ] = $request[ $api_request ];
  331. }
  332. }
  333. $taxonomy = get_taxonomy( 'nav_menu' );
  334. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  335. // If menus submitted, cast to int.
  336. if ( ! empty( $request[ $base ] ) ) {
  337. $prepared_nav_item['menu-id'] = absint( $request[ $base ] );
  338. }
  339. // Nav menu title.
  340. if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
  341. if ( is_string( $request['title'] ) ) {
  342. $prepared_nav_item['menu-item-title'] = $request['title'];
  343. } elseif ( ! empty( $request['title']['raw'] ) ) {
  344. $prepared_nav_item['menu-item-title'] = $request['title']['raw'];
  345. }
  346. }
  347. $error = new WP_Error();
  348. // Check if object id exists before saving.
  349. if ( ! $prepared_nav_item['menu-item-object'] ) {
  350. // If taxonomy, check if term exists.
  351. if ( 'taxonomy' === $prepared_nav_item['menu-item-type'] ) {
  352. $original = get_term( absint( $prepared_nav_item['menu-item-object-id'] ) );
  353. if ( empty( $original ) || is_wp_error( $original ) ) {
  354. $error->add( 'rest_term_invalid_id', __( 'Invalid term ID.' ), array( 'status' => 400 ) );
  355. } else {
  356. $prepared_nav_item['menu-item-object'] = get_term_field( 'taxonomy', $original );
  357. }
  358. // If post, check if post object exists.
  359. } elseif ( 'post_type' === $prepared_nav_item['menu-item-type'] ) {
  360. $original = get_post( absint( $prepared_nav_item['menu-item-object-id'] ) );
  361. if ( empty( $original ) ) {
  362. $error->add( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 400 ) );
  363. } else {
  364. $prepared_nav_item['menu-item-object'] = get_post_type( $original );
  365. }
  366. }
  367. }
  368. // If post type archive, check if post type exists.
  369. if ( 'post_type_archive' === $prepared_nav_item['menu-item-type'] ) {
  370. $post_type = $prepared_nav_item['menu-item-object'] ? $prepared_nav_item['menu-item-object'] : false;
  371. $original = get_post_type_object( $post_type );
  372. if ( ! $original ) {
  373. $error->add( 'rest_post_invalid_type', __( 'Invalid post type.' ), array( 'status' => 400 ) );
  374. }
  375. }
  376. // Check if menu item is type custom, then title and url are required.
  377. if ( 'custom' === $prepared_nav_item['menu-item-type'] ) {
  378. if ( '' === $prepared_nav_item['menu-item-title'] ) {
  379. $error->add( 'rest_title_required', __( 'The title is required when using a custom menu item type.' ), array( 'status' => 400 ) );
  380. }
  381. if ( empty( $prepared_nav_item['menu-item-url'] ) ) {
  382. $error->add( 'rest_url_required', __( 'The url is required when using a custom menu item type.' ), array( 'status' => 400 ) );
  383. }
  384. }
  385. if ( $error->has_errors() ) {
  386. return $error;
  387. }
  388. // The xfn and classes properties are arrays, but passed to wp_update_nav_menu_item as a string.
  389. foreach ( array( 'menu-item-xfn', 'menu-item-classes' ) as $key ) {
  390. $prepared_nav_item[ $key ] = implode( ' ', $prepared_nav_item[ $key ] );
  391. }
  392. // Only draft / publish are valid post status for menu items.
  393. if ( 'publish' !== $prepared_nav_item['menu-item-status'] ) {
  394. $prepared_nav_item['menu-item-status'] = 'draft';
  395. }
  396. $prepared_nav_item = (object) $prepared_nav_item;
  397. /**
  398. * Filters a menu item before it is inserted via the REST API.
  399. *
  400. * @since 5.9.0
  401. *
  402. * @param object $prepared_nav_item An object representing a single menu item prepared
  403. * for inserting or updating the database.
  404. * @param WP_REST_Request $request Request object.
  405. */
  406. return apply_filters( 'rest_pre_insert_nav_menu_item', $prepared_nav_item, $request );
  407. }
  408. /**
  409. * Prepares a single post output for response.
  410. *
  411. * @since 5.9.0
  412. *
  413. * @param WP_Post $item Post object.
  414. * @param WP_REST_Request $request Request object.
  415. * @return WP_REST_Response Response object.
  416. */
  417. public function prepare_item_for_response( $item, $request ) {
  418. // Base fields for every post.
  419. $fields = $this->get_fields_for_response( $request );
  420. $menu_item = $this->get_nav_menu_item( $item->ID );
  421. $data = array();
  422. if ( rest_is_field_included( 'id', $fields ) ) {
  423. $data['id'] = $menu_item->ID;
  424. }
  425. if ( rest_is_field_included( 'title', $fields ) ) {
  426. $data['title'] = array();
  427. }
  428. if ( rest_is_field_included( 'title.raw', $fields ) ) {
  429. $data['title']['raw'] = $menu_item->title;
  430. }
  431. if ( rest_is_field_included( 'title.rendered', $fields ) ) {
  432. add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  433. /** This filter is documented in wp-includes/post-template.php */
  434. $title = apply_filters( 'the_title', $menu_item->title, $menu_item->ID );
  435. $data['title']['rendered'] = $title;
  436. remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  437. }
  438. if ( rest_is_field_included( 'status', $fields ) ) {
  439. $data['status'] = $menu_item->post_status;
  440. }
  441. if ( rest_is_field_included( 'url', $fields ) ) {
  442. $data['url'] = $menu_item->url;
  443. }
  444. if ( rest_is_field_included( 'attr_title', $fields ) ) {
  445. // Same as post_excerpt.
  446. $data['attr_title'] = $menu_item->attr_title;
  447. }
  448. if ( rest_is_field_included( 'description', $fields ) ) {
  449. // Same as post_content.
  450. $data['description'] = $menu_item->description;
  451. }
  452. if ( rest_is_field_included( 'type', $fields ) ) {
  453. $data['type'] = $menu_item->type;
  454. }
  455. if ( rest_is_field_included( 'type_label', $fields ) ) {
  456. $data['type_label'] = $menu_item->type_label;
  457. }
  458. if ( rest_is_field_included( 'object', $fields ) ) {
  459. $data['object'] = $menu_item->object;
  460. }
  461. if ( rest_is_field_included( 'object_id', $fields ) ) {
  462. // It is stored as a string, but should be exposed as an integer.
  463. $data['object_id'] = absint( $menu_item->object_id );
  464. }
  465. if ( rest_is_field_included( 'parent', $fields ) ) {
  466. // Same as post_parent, exposed as an integer.
  467. $data['parent'] = (int) $menu_item->menu_item_parent;
  468. }
  469. if ( rest_is_field_included( 'menu_order', $fields ) ) {
  470. // Same as post_parent, exposed as an integer.
  471. $data['menu_order'] = (int) $menu_item->menu_order;
  472. }
  473. if ( rest_is_field_included( 'target', $fields ) ) {
  474. $data['target'] = $menu_item->target;
  475. }
  476. if ( rest_is_field_included( 'classes', $fields ) ) {
  477. $data['classes'] = (array) $menu_item->classes;
  478. }
  479. if ( rest_is_field_included( 'xfn', $fields ) ) {
  480. $data['xfn'] = array_map( 'sanitize_html_class', explode( ' ', $menu_item->xfn ) );
  481. }
  482. if ( rest_is_field_included( 'invalid', $fields ) ) {
  483. $data['invalid'] = (bool) $menu_item->_invalid;
  484. }
  485. if ( rest_is_field_included( 'meta', $fields ) ) {
  486. $data['meta'] = $this->meta->get_value( $menu_item->ID, $request );
  487. }
  488. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  489. foreach ( $taxonomies as $taxonomy ) {
  490. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  491. if ( rest_is_field_included( $base, $fields ) ) {
  492. $terms = get_the_terms( $item, $taxonomy->name );
  493. if ( ! is_array( $terms ) ) {
  494. continue;
  495. }
  496. $term_ids = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
  497. if ( 'nav_menu' === $taxonomy->name ) {
  498. $data[ $base ] = $term_ids ? array_shift( $term_ids ) : 0;
  499. } else {
  500. $data[ $base ] = $term_ids;
  501. }
  502. }
  503. }
  504. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  505. $data = $this->add_additional_fields_to_object( $data, $request );
  506. $data = $this->filter_response_by_context( $data, $context );
  507. // Wrap the data in a response object.
  508. $response = rest_ensure_response( $data );
  509. if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
  510. $links = $this->prepare_links( $item );
  511. $response->add_links( $links );
  512. if ( ! empty( $links['self']['href'] ) ) {
  513. $actions = $this->get_available_actions( $item, $request );
  514. $self = $links['self']['href'];
  515. foreach ( $actions as $rel ) {
  516. $response->add_link( $rel, $self );
  517. }
  518. }
  519. }
  520. /**
  521. * Filters the menu item data for a REST API response.
  522. *
  523. * @since 5.9.0
  524. *
  525. * @param WP_REST_Response $response The response object.
  526. * @param object $menu_item Menu item setup by {@see wp_setup_nav_menu_item()}.
  527. * @param WP_REST_Request $request Request object.
  528. */
  529. return apply_filters( 'rest_prepare_nav_menu_item', $response, $menu_item, $request );
  530. }
  531. /**
  532. * Prepares links for the request.
  533. *
  534. * @since 5.9.0
  535. *
  536. * @param WP_Post $post Post object.
  537. * @return array Links for the given post.
  538. */
  539. protected function prepare_links( $post ) {
  540. $links = parent::prepare_links( $post );
  541. $menu_item = $this->get_nav_menu_item( $post->ID );
  542. if ( empty( $menu_item->object_id ) ) {
  543. return $links;
  544. }
  545. $path = '';
  546. $type = '';
  547. $key = $menu_item->type;
  548. if ( 'post_type' === $menu_item->type ) {
  549. $path = rest_get_route_for_post( $menu_item->object_id );
  550. $type = get_post_type( $menu_item->object_id );
  551. } elseif ( 'taxonomy' === $menu_item->type ) {
  552. $path = rest_get_route_for_term( $menu_item->object_id );
  553. $type = get_term_field( 'taxonomy', $menu_item->object_id );
  554. }
  555. if ( $path && $type ) {
  556. $links['https://api.w.org/menu-item-object'][] = array(
  557. 'href' => rest_url( $path ),
  558. $key => $type,
  559. 'embeddable' => true,
  560. );
  561. }
  562. return $links;
  563. }
  564. /**
  565. * Retrieves Link Description Objects that should be added to the Schema for the posts collection.
  566. *
  567. * @since 5.9.0
  568. *
  569. * @return array
  570. */
  571. protected function get_schema_links() {
  572. $links = parent::get_schema_links();
  573. $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" );
  574. $links[] = array(
  575. 'rel' => 'https://api.w.org/menu-item-object',
  576. 'title' => __( 'Get linked object.' ),
  577. 'href' => $href,
  578. 'targetSchema' => array(
  579. 'type' => 'object',
  580. 'properties' => array(
  581. 'object' => array(
  582. 'type' => 'integer',
  583. ),
  584. ),
  585. ),
  586. );
  587. return $links;
  588. }
  589. /**
  590. * Retrieves the term's schema, conforming to JSON Schema.
  591. *
  592. * @since 5.9.0
  593. *
  594. * @return array Item schema data.
  595. */
  596. public function get_item_schema() {
  597. $schema = array(
  598. '$schema' => 'http://json-schema.org/draft-04/schema#',
  599. 'title' => $this->post_type,
  600. 'type' => 'object',
  601. );
  602. $schema['properties']['title'] = array(
  603. 'description' => __( 'The title for the object.' ),
  604. 'type' => array( 'string', 'object' ),
  605. 'context' => array( 'view', 'edit', 'embed' ),
  606. 'properties' => array(
  607. 'raw' => array(
  608. 'description' => __( 'Title for the object, as it exists in the database.' ),
  609. 'type' => 'string',
  610. 'context' => array( 'edit' ),
  611. ),
  612. 'rendered' => array(
  613. 'description' => __( 'HTML title for the object, transformed for display.' ),
  614. 'type' => 'string',
  615. 'context' => array( 'view', 'edit', 'embed' ),
  616. 'readonly' => true,
  617. ),
  618. ),
  619. );
  620. $schema['properties']['id'] = array(
  621. 'description' => __( 'Unique identifier for the object.' ),
  622. 'type' => 'integer',
  623. 'default' => 0,
  624. 'minimum' => 0,
  625. 'context' => array( 'view', 'edit', 'embed' ),
  626. 'readonly' => true,
  627. );
  628. $schema['properties']['type_label'] = array(
  629. 'description' => __( 'The singular label used to describe this type of menu item.' ),
  630. 'type' => 'string',
  631. 'context' => array( 'view', 'edit', 'embed' ),
  632. 'readonly' => true,
  633. );
  634. $schema['properties']['type'] = array(
  635. 'description' => __( 'The family of objects originally represented, such as "post_type" or "taxonomy".' ),
  636. 'type' => 'string',
  637. 'enum' => array( 'taxonomy', 'post_type', 'post_type_archive', 'custom' ),
  638. 'context' => array( 'view', 'edit', 'embed' ),
  639. 'default' => 'custom',
  640. );
  641. $schema['properties']['status'] = array(
  642. 'description' => __( 'A named status for the object.' ),
  643. 'type' => 'string',
  644. 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ),
  645. 'default' => 'publish',
  646. 'context' => array( 'view', 'edit', 'embed' ),
  647. );
  648. $schema['properties']['parent'] = array(
  649. 'description' => __( 'The ID for the parent of the object.' ),
  650. 'type' => 'integer',
  651. 'minimum' => 0,
  652. 'default' => 0,
  653. 'context' => array( 'view', 'edit', 'embed' ),
  654. );
  655. $schema['properties']['attr_title'] = array(
  656. 'description' => __( 'Text for the title attribute of the link element for this menu item.' ),
  657. 'type' => 'string',
  658. 'context' => array( 'view', 'edit', 'embed' ),
  659. 'arg_options' => array(
  660. 'sanitize_callback' => 'sanitize_text_field',
  661. ),
  662. );
  663. $schema['properties']['classes'] = array(
  664. 'description' => __( 'Class names for the link element of this menu item.' ),
  665. 'type' => 'array',
  666. 'items' => array(
  667. 'type' => 'string',
  668. ),
  669. 'context' => array( 'view', 'edit', 'embed' ),
  670. 'arg_options' => array(
  671. 'sanitize_callback' => function ( $value ) {
  672. return array_map( 'sanitize_html_class', wp_parse_list( $value ) );
  673. },
  674. ),
  675. );
  676. $schema['properties']['description'] = array(
  677. 'description' => __( 'The description of this menu item.' ),
  678. 'type' => 'string',
  679. 'context' => array( 'view', 'edit', 'embed' ),
  680. 'arg_options' => array(
  681. 'sanitize_callback' => 'sanitize_text_field',
  682. ),
  683. );
  684. $schema['properties']['menu_order'] = array(
  685. 'description' => __( 'The DB ID of the nav_menu_item that is this item\'s menu parent, if any, otherwise 0.' ),
  686. 'context' => array( 'view', 'edit', 'embed' ),
  687. 'type' => 'integer',
  688. 'minimum' => 1,
  689. 'default' => 1,
  690. );
  691. $schema['properties']['object'] = array(
  692. 'description' => __( 'The type of object originally represented, such as "category", "post", or "attachment".' ),
  693. 'context' => array( 'view', 'edit', 'embed' ),
  694. 'type' => 'string',
  695. 'arg_options' => array(
  696. 'sanitize_callback' => 'sanitize_key',
  697. ),
  698. );
  699. $schema['properties']['object_id'] = array(
  700. 'description' => __( 'The database ID of the original object this menu item represents, for example the ID for posts or the term_id for categories.' ),
  701. 'context' => array( 'view', 'edit', 'embed' ),
  702. 'type' => 'integer',
  703. 'minimum' => 0,
  704. 'default' => 0,
  705. );
  706. $schema['properties']['target'] = array(
  707. 'description' => __( 'The target attribute of the link element for this menu item.' ),
  708. 'type' => 'string',
  709. 'context' => array( 'view', 'edit', 'embed' ),
  710. 'enum' => array(
  711. '_blank',
  712. '',
  713. ),
  714. );
  715. $schema['properties']['url'] = array(
  716. 'description' => __( 'The URL to which this menu item points.' ),
  717. 'type' => 'string',
  718. 'format' => 'uri',
  719. 'context' => array( 'view', 'edit', 'embed' ),
  720. 'arg_options' => array(
  721. 'validate_callback' => static function ( $url ) {
  722. if ( '' === $url ) {
  723. return true;
  724. }
  725. if ( sanitize_url( $url ) ) {
  726. return true;
  727. }
  728. return new WP_Error(
  729. 'rest_invalid_url',
  730. __( 'Invalid URL.' )
  731. );
  732. },
  733. ),
  734. );
  735. $schema['properties']['xfn'] = array(
  736. 'description' => __( 'The XFN relationship expressed in the link of this menu item.' ),
  737. 'type' => 'array',
  738. 'items' => array(
  739. 'type' => 'string',
  740. ),
  741. 'context' => array( 'view', 'edit', 'embed' ),
  742. 'arg_options' => array(
  743. 'sanitize_callback' => function ( $value ) {
  744. return array_map( 'sanitize_html_class', wp_parse_list( $value ) );
  745. },
  746. ),
  747. );
  748. $schema['properties']['invalid'] = array(
  749. 'description' => __( 'Whether the menu item represents an object that no longer exists.' ),
  750. 'context' => array( 'view', 'edit', 'embed' ),
  751. 'type' => 'boolean',
  752. 'readonly' => true,
  753. );
  754. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  755. foreach ( $taxonomies as $taxonomy ) {
  756. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  757. $schema['properties'][ $base ] = array(
  758. /* translators: %s: taxonomy name */
  759. 'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
  760. 'type' => 'array',
  761. 'items' => array(
  762. 'type' => 'integer',
  763. ),
  764. 'context' => array( 'view', 'edit' ),
  765. );
  766. if ( 'nav_menu' === $taxonomy->name ) {
  767. $schema['properties'][ $base ]['type'] = 'integer';
  768. unset( $schema['properties'][ $base ]['items'] );
  769. }
  770. }
  771. $schema['properties']['meta'] = $this->meta->get_field_schema();
  772. $schema_links = $this->get_schema_links();
  773. if ( $schema_links ) {
  774. $schema['links'] = $schema_links;
  775. }
  776. return $this->add_additional_fields_schema( $schema );
  777. }
  778. /**
  779. * Retrieves the query params for the posts collection.
  780. *
  781. * @since 5.9.0
  782. *
  783. * @return array Collection parameters.
  784. */
  785. public function get_collection_params() {
  786. $query_params = parent::get_collection_params();
  787. $query_params['menu_order'] = array(
  788. 'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
  789. 'type' => 'integer',
  790. );
  791. $query_params['order'] = array(
  792. 'description' => __( 'Order sort attribute ascending or descending.' ),
  793. 'type' => 'string',
  794. 'default' => 'asc',
  795. 'enum' => array( 'asc', 'desc' ),
  796. );
  797. $query_params['orderby'] = array(
  798. 'description' => __( 'Sort collection by object attribute.' ),
  799. 'type' => 'string',
  800. 'default' => 'menu_order',
  801. 'enum' => array(
  802. 'author',
  803. 'date',
  804. 'id',
  805. 'include',
  806. 'modified',
  807. 'parent',
  808. 'relevance',
  809. 'slug',
  810. 'include_slugs',
  811. 'title',
  812. 'menu_order',
  813. ),
  814. );
  815. // Change default to 100 items.
  816. $query_params['per_page']['default'] = 100;
  817. return $query_params;
  818. }
  819. /**
  820. * Determines the allowed query_vars for a get_items() response and prepares
  821. * them for WP_Query.
  822. *
  823. * @since 5.9.0
  824. *
  825. * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
  826. * @param WP_REST_Request $request Optional. Full details about the request.
  827. * @return array Items query arguments.
  828. */
  829. protected function prepare_items_query( $prepared_args = array(), $request = null ) {
  830. $query_args = parent::prepare_items_query( $prepared_args, $request );
  831. // Map to proper WP_Query orderby param.
  832. if ( isset( $query_args['orderby'], $request['orderby'] ) ) {
  833. $orderby_mappings = array(
  834. 'id' => 'ID',
  835. 'include' => 'post__in',
  836. 'slug' => 'post_name',
  837. 'include_slugs' => 'post_name__in',
  838. 'menu_order' => 'menu_order',
  839. );
  840. if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
  841. $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
  842. }
  843. }
  844. $query_args['update_menu_item_cache'] = true;
  845. return $query_args;
  846. }
  847. /**
  848. * Gets the id of the menu that the given menu item belongs to.
  849. *
  850. * @since 5.9.0
  851. *
  852. * @param int $menu_item_id Menu item id.
  853. * @return int
  854. */
  855. protected function get_menu_id( $menu_item_id ) {
  856. $menu_ids = wp_get_post_terms( $menu_item_id, 'nav_menu', array( 'fields' => 'ids' ) );
  857. $menu_id = 0;
  858. if ( $menu_ids && ! is_wp_error( $menu_ids ) ) {
  859. $menu_id = array_shift( $menu_ids );
  860. }
  861. return $menu_id;
  862. }
  863. }