class-wp-rest-widgets-controller.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. <?php
  2. /**
  3. * REST API: WP_REST_Widgets_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 5.8.0
  8. */
  9. /**
  10. * Core class to access widgets via the REST API.
  11. *
  12. * @since 5.8.0
  13. *
  14. * @see WP_REST_Controller
  15. */
  16. class WP_REST_Widgets_Controller extends WP_REST_Controller {
  17. /**
  18. * Tracks whether {@see retrieve_widgets()} has been called in the current request.
  19. *
  20. * @since 5.9.0
  21. * @var bool
  22. */
  23. protected $widgets_retrieved = false;
  24. /**
  25. * Whether the controller supports batching.
  26. *
  27. * @since 5.9.0
  28. * @var array
  29. */
  30. protected $allow_batch = array( 'v1' => true );
  31. /**
  32. * Widgets controller constructor.
  33. *
  34. * @since 5.8.0
  35. */
  36. public function __construct() {
  37. $this->namespace = 'wp/v2';
  38. $this->rest_base = 'widgets';
  39. }
  40. /**
  41. * Registers the widget routes for the controller.
  42. *
  43. * @since 5.8.0
  44. */
  45. public function register_routes() {
  46. register_rest_route(
  47. $this->namespace,
  48. $this->rest_base,
  49. array(
  50. array(
  51. 'methods' => WP_REST_Server::READABLE,
  52. 'callback' => array( $this, 'get_items' ),
  53. 'permission_callback' => array( $this, 'get_items_permissions_check' ),
  54. 'args' => $this->get_collection_params(),
  55. ),
  56. array(
  57. 'methods' => WP_REST_Server::CREATABLE,
  58. 'callback' => array( $this, 'create_item' ),
  59. 'permission_callback' => array( $this, 'create_item_permissions_check' ),
  60. 'args' => $this->get_endpoint_args_for_item_schema(),
  61. ),
  62. 'allow_batch' => $this->allow_batch,
  63. 'schema' => array( $this, 'get_public_item_schema' ),
  64. )
  65. );
  66. register_rest_route(
  67. $this->namespace,
  68. $this->rest_base . '/(?P<id>[\w\-]+)',
  69. array(
  70. array(
  71. 'methods' => WP_REST_Server::READABLE,
  72. 'callback' => array( $this, 'get_item' ),
  73. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  74. 'args' => array(
  75. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  76. ),
  77. ),
  78. array(
  79. 'methods' => WP_REST_Server::EDITABLE,
  80. 'callback' => array( $this, 'update_item' ),
  81. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  82. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  83. ),
  84. array(
  85. 'methods' => WP_REST_Server::DELETABLE,
  86. 'callback' => array( $this, 'delete_item' ),
  87. 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  88. 'args' => array(
  89. 'force' => array(
  90. 'description' => __( 'Whether to force removal of the widget, or move it to the inactive sidebar.' ),
  91. 'type' => 'boolean',
  92. ),
  93. ),
  94. ),
  95. 'allow_batch' => $this->allow_batch,
  96. 'schema' => array( $this, 'get_public_item_schema' ),
  97. )
  98. );
  99. }
  100. /**
  101. * Checks if a given request has access to get widgets.
  102. *
  103. * @since 5.8.0
  104. *
  105. * @param WP_REST_Request $request Full details about the request.
  106. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  107. */
  108. public function get_items_permissions_check( $request ) {
  109. $this->retrieve_widgets();
  110. if ( isset( $request['sidebar'] ) && $this->check_read_sidebar_permission( $request['sidebar'] ) ) {
  111. return true;
  112. }
  113. foreach ( wp_get_sidebars_widgets() as $sidebar_id => $widget_ids ) {
  114. if ( $this->check_read_sidebar_permission( $sidebar_id ) ) {
  115. return true;
  116. }
  117. }
  118. return $this->permissions_check( $request );
  119. }
  120. /**
  121. * Retrieves a collection of widgets.
  122. *
  123. * @since 5.8.0
  124. *
  125. * @param WP_REST_Request $request Full details about the request.
  126. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  127. */
  128. public function get_items( $request ) {
  129. $this->retrieve_widgets();
  130. $prepared = array();
  131. $permissions_check = $this->permissions_check( $request );
  132. foreach ( wp_get_sidebars_widgets() as $sidebar_id => $widget_ids ) {
  133. if ( isset( $request['sidebar'] ) && $sidebar_id !== $request['sidebar'] ) {
  134. continue;
  135. }
  136. if ( is_wp_error( $permissions_check ) && ! $this->check_read_sidebar_permission( $sidebar_id ) ) {
  137. continue;
  138. }
  139. foreach ( $widget_ids as $widget_id ) {
  140. $response = $this->prepare_item_for_response( compact( 'sidebar_id', 'widget_id' ), $request );
  141. if ( ! is_wp_error( $response ) ) {
  142. $prepared[] = $this->prepare_response_for_collection( $response );
  143. }
  144. }
  145. }
  146. return new WP_REST_Response( $prepared );
  147. }
  148. /**
  149. * Checks if a given request has access to get a widget.
  150. *
  151. * @since 5.8.0
  152. *
  153. * @param WP_REST_Request $request Full details about the request.
  154. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  155. */
  156. public function get_item_permissions_check( $request ) {
  157. $this->retrieve_widgets();
  158. $widget_id = $request['id'];
  159. $sidebar_id = wp_find_widgets_sidebar( $widget_id );
  160. if ( $sidebar_id && $this->check_read_sidebar_permission( $sidebar_id ) ) {
  161. return true;
  162. }
  163. return $this->permissions_check( $request );
  164. }
  165. /**
  166. * Checks if a sidebar can be read publicly.
  167. *
  168. * @since 5.9.0
  169. *
  170. * @param string $sidebar_id The sidebar ID.
  171. * @return bool Whether the sidebar can be read.
  172. */
  173. protected function check_read_sidebar_permission( $sidebar_id ) {
  174. $sidebar = wp_get_sidebar( $sidebar_id );
  175. return ! empty( $sidebar['show_in_rest'] );
  176. }
  177. /**
  178. * Gets an individual widget.
  179. *
  180. * @since 5.8.0
  181. *
  182. * @param WP_REST_Request $request Full details about the request.
  183. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  184. */
  185. public function get_item( $request ) {
  186. $this->retrieve_widgets();
  187. $widget_id = $request['id'];
  188. $sidebar_id = wp_find_widgets_sidebar( $widget_id );
  189. if ( is_null( $sidebar_id ) ) {
  190. return new WP_Error(
  191. 'rest_widget_not_found',
  192. __( 'No widget was found with that id.' ),
  193. array( 'status' => 404 )
  194. );
  195. }
  196. return $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request );
  197. }
  198. /**
  199. * Checks if a given request has access to create widgets.
  200. *
  201. * @since 5.8.0
  202. *
  203. * @param WP_REST_Request $request Full details about the request.
  204. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  205. */
  206. public function create_item_permissions_check( $request ) {
  207. return $this->permissions_check( $request );
  208. }
  209. /**
  210. * Creates a widget.
  211. *
  212. * @since 5.8.0
  213. *
  214. * @param WP_REST_Request $request Full details about the request.
  215. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  216. */
  217. public function create_item( $request ) {
  218. $sidebar_id = $request['sidebar'];
  219. $widget_id = $this->save_widget( $request, $sidebar_id );
  220. if ( is_wp_error( $widget_id ) ) {
  221. return $widget_id;
  222. }
  223. wp_assign_widget_to_sidebar( $widget_id, $sidebar_id );
  224. $request['context'] = 'edit';
  225. $response = $this->prepare_item_for_response( compact( 'sidebar_id', 'widget_id' ), $request );
  226. if ( is_wp_error( $response ) ) {
  227. return $response;
  228. }
  229. $response->set_status( 201 );
  230. return $response;
  231. }
  232. /**
  233. * Checks if a given request has access to update widgets.
  234. *
  235. * @since 5.8.0
  236. *
  237. * @param WP_REST_Request $request Full details about the request.
  238. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  239. */
  240. public function update_item_permissions_check( $request ) {
  241. return $this->permissions_check( $request );
  242. }
  243. /**
  244. * Updates an existing widget.
  245. *
  246. * @since 5.8.0
  247. *
  248. * @global WP_Widget_Factory $wp_widget_factory
  249. *
  250. * @param WP_REST_Request $request Full details about the request.
  251. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  252. */
  253. public function update_item( $request ) {
  254. global $wp_widget_factory;
  255. /*
  256. * retrieve_widgets() contains logic to move "hidden" or "lost" widgets to the
  257. * wp_inactive_widgets sidebar based on the contents of the $sidebars_widgets global.
  258. *
  259. * When batch requests are processed, this global is not properly updated by previous
  260. * calls, resulting in widgets incorrectly being moved to the wp_inactive_widgets
  261. * sidebar.
  262. *
  263. * See https://core.trac.wordpress.org/ticket/53657.
  264. */
  265. wp_get_sidebars_widgets();
  266. $this->retrieve_widgets();
  267. $widget_id = $request['id'];
  268. $sidebar_id = wp_find_widgets_sidebar( $widget_id );
  269. // Allow sidebar to be unset or missing when widget is not a WP_Widget.
  270. $parsed_id = wp_parse_widget_id( $widget_id );
  271. $widget_object = $wp_widget_factory->get_widget_object( $parsed_id['id_base'] );
  272. if ( is_null( $sidebar_id ) && $widget_object ) {
  273. return new WP_Error(
  274. 'rest_widget_not_found',
  275. __( 'No widget was found with that id.' ),
  276. array( 'status' => 404 )
  277. );
  278. }
  279. if (
  280. $request->has_param( 'instance' ) ||
  281. $request->has_param( 'form_data' )
  282. ) {
  283. $maybe_error = $this->save_widget( $request, $sidebar_id );
  284. if ( is_wp_error( $maybe_error ) ) {
  285. return $maybe_error;
  286. }
  287. }
  288. if ( $request->has_param( 'sidebar' ) ) {
  289. if ( $sidebar_id !== $request['sidebar'] ) {
  290. $sidebar_id = $request['sidebar'];
  291. wp_assign_widget_to_sidebar( $widget_id, $sidebar_id );
  292. }
  293. }
  294. $request['context'] = 'edit';
  295. return $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request );
  296. }
  297. /**
  298. * Checks if a given request has access to delete widgets.
  299. *
  300. * @since 5.8.0
  301. *
  302. * @param WP_REST_Request $request Full details about the request.
  303. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  304. */
  305. public function delete_item_permissions_check( $request ) {
  306. return $this->permissions_check( $request );
  307. }
  308. /**
  309. * Deletes a widget.
  310. *
  311. * @since 5.8.0
  312. *
  313. * @global WP_Widget_Factory $wp_widget_factory
  314. * @global array $wp_registered_widget_updates The registered widget update functions.
  315. *
  316. * @param WP_REST_Request $request Full details about the request.
  317. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  318. */
  319. public function delete_item( $request ) {
  320. global $wp_widget_factory, $wp_registered_widget_updates;
  321. /*
  322. * retrieve_widgets() contains logic to move "hidden" or "lost" widgets to the
  323. * wp_inactive_widgets sidebar based on the contents of the $sidebars_widgets global.
  324. *
  325. * When batch requests are processed, this global is not properly updated by previous
  326. * calls, resulting in widgets incorrectly being moved to the wp_inactive_widgets
  327. * sidebar.
  328. *
  329. * See https://core.trac.wordpress.org/ticket/53657.
  330. */
  331. wp_get_sidebars_widgets();
  332. $this->retrieve_widgets();
  333. $widget_id = $request['id'];
  334. $sidebar_id = wp_find_widgets_sidebar( $widget_id );
  335. if ( is_null( $sidebar_id ) ) {
  336. return new WP_Error(
  337. 'rest_widget_not_found',
  338. __( 'No widget was found with that id.' ),
  339. array( 'status' => 404 )
  340. );
  341. }
  342. $request['context'] = 'edit';
  343. if ( $request['force'] ) {
  344. $response = $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request );
  345. $parsed_id = wp_parse_widget_id( $widget_id );
  346. $id_base = $parsed_id['id_base'];
  347. $original_post = $_POST;
  348. $original_request = $_REQUEST;
  349. $_POST = array(
  350. 'sidebar' => $sidebar_id,
  351. "widget-$id_base" => array(),
  352. 'the-widget-id' => $widget_id,
  353. 'delete_widget' => '1',
  354. );
  355. $_REQUEST = $_POST;
  356. /** This action is documented in wp-admin/widgets-form.php */
  357. do_action( 'delete_widget', $widget_id, $sidebar_id, $id_base );
  358. $callback = $wp_registered_widget_updates[ $id_base ]['callback'];
  359. $params = $wp_registered_widget_updates[ $id_base ]['params'];
  360. if ( is_callable( $callback ) ) {
  361. ob_start();
  362. call_user_func_array( $callback, $params );
  363. ob_end_clean();
  364. }
  365. $_POST = $original_post;
  366. $_REQUEST = $original_request;
  367. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  368. if ( $widget_object ) {
  369. /*
  370. * WP_Widget sets `updated = true` after an update to prevent more than one widget
  371. * from being saved per request. This isn't what we want in the REST API, though,
  372. * as we support batch requests.
  373. */
  374. $widget_object->updated = false;
  375. }
  376. wp_assign_widget_to_sidebar( $widget_id, '' );
  377. $response->set_data(
  378. array(
  379. 'deleted' => true,
  380. 'previous' => $response->get_data(),
  381. )
  382. );
  383. } else {
  384. wp_assign_widget_to_sidebar( $widget_id, 'wp_inactive_widgets' );
  385. $response = $this->prepare_item_for_response(
  386. array(
  387. 'sidebar_id' => 'wp_inactive_widgets',
  388. 'widget_id' => $widget_id,
  389. ),
  390. $request
  391. );
  392. }
  393. /**
  394. * Fires after a widget is deleted via the REST API.
  395. *
  396. * @since 5.8.0
  397. *
  398. * @param string $widget_id ID of the widget marked for deletion.
  399. * @param string $sidebar_id ID of the sidebar the widget was deleted from.
  400. * @param WP_REST_Response|WP_Error $response The response data, or WP_Error object on failure.
  401. * @param WP_REST_Request $request The request sent to the API.
  402. */
  403. do_action( 'rest_delete_widget', $widget_id, $sidebar_id, $response, $request );
  404. return $response;
  405. }
  406. /**
  407. * Performs a permissions check for managing widgets.
  408. *
  409. * @since 5.8.0
  410. *
  411. * @param WP_REST_Request $request Full details about the request.
  412. * @return true|WP_Error
  413. */
  414. protected function permissions_check( $request ) {
  415. if ( ! current_user_can( 'edit_theme_options' ) ) {
  416. return new WP_Error(
  417. 'rest_cannot_manage_widgets',
  418. __( 'Sorry, you are not allowed to manage widgets on this site.' ),
  419. array(
  420. 'status' => rest_authorization_required_code(),
  421. )
  422. );
  423. }
  424. return true;
  425. }
  426. /**
  427. * Looks for "lost" widgets once per request.
  428. *
  429. * @since 5.9.0
  430. *
  431. * @see retrieve_widgets()
  432. */
  433. protected function retrieve_widgets() {
  434. if ( ! $this->widgets_retrieved ) {
  435. retrieve_widgets();
  436. $this->widgets_retrieved = true;
  437. }
  438. }
  439. /**
  440. * Saves the widget in the request object.
  441. *
  442. * @since 5.8.0
  443. *
  444. * @global WP_Widget_Factory $wp_widget_factory
  445. * @global array $wp_registered_widget_updates The registered widget update functions.
  446. *
  447. * @param WP_REST_Request $request Full details about the request.
  448. * @param string $sidebar_id ID of the sidebar the widget belongs to.
  449. * @return string|WP_Error The saved widget ID.
  450. */
  451. protected function save_widget( $request, $sidebar_id ) {
  452. global $wp_widget_factory, $wp_registered_widget_updates;
  453. require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number().
  454. if ( isset( $request['id'] ) ) {
  455. // Saving an existing widget.
  456. $id = $request['id'];
  457. $parsed_id = wp_parse_widget_id( $id );
  458. $id_base = $parsed_id['id_base'];
  459. $number = isset( $parsed_id['number'] ) ? $parsed_id['number'] : null;
  460. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  461. $creating = false;
  462. } elseif ( $request['id_base'] ) {
  463. // Saving a new widget.
  464. $id_base = $request['id_base'];
  465. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  466. $number = $widget_object ? next_widget_id_number( $id_base ) : null;
  467. $id = $widget_object ? $id_base . '-' . $number : $id_base;
  468. $creating = true;
  469. } else {
  470. return new WP_Error(
  471. 'rest_invalid_widget',
  472. __( 'Widget type (id_base) is required.' ),
  473. array( 'status' => 400 )
  474. );
  475. }
  476. if ( ! isset( $wp_registered_widget_updates[ $id_base ] ) ) {
  477. return new WP_Error(
  478. 'rest_invalid_widget',
  479. __( 'The provided widget type (id_base) cannot be updated.' ),
  480. array( 'status' => 400 )
  481. );
  482. }
  483. if ( isset( $request['instance'] ) ) {
  484. if ( ! $widget_object ) {
  485. return new WP_Error(
  486. 'rest_invalid_widget',
  487. __( 'Cannot set instance on a widget that does not extend WP_Widget.' ),
  488. array( 'status' => 400 )
  489. );
  490. }
  491. if ( isset( $request['instance']['raw'] ) ) {
  492. if ( empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  493. return new WP_Error(
  494. 'rest_invalid_widget',
  495. __( 'Widget type does not support raw instances.' ),
  496. array( 'status' => 400 )
  497. );
  498. }
  499. $instance = $request['instance']['raw'];
  500. } elseif ( isset( $request['instance']['encoded'], $request['instance']['hash'] ) ) {
  501. $serialized_instance = base64_decode( $request['instance']['encoded'] );
  502. if ( ! hash_equals( wp_hash( $serialized_instance ), $request['instance']['hash'] ) ) {
  503. return new WP_Error(
  504. 'rest_invalid_widget',
  505. __( 'The provided instance is malformed.' ),
  506. array( 'status' => 400 )
  507. );
  508. }
  509. $instance = unserialize( $serialized_instance );
  510. } else {
  511. return new WP_Error(
  512. 'rest_invalid_widget',
  513. __( 'The provided instance is invalid. Must contain raw OR encoded and hash.' ),
  514. array( 'status' => 400 )
  515. );
  516. }
  517. $form_data = array(
  518. "widget-$id_base" => array(
  519. $number => $instance,
  520. ),
  521. 'sidebar' => $sidebar_id,
  522. );
  523. } elseif ( isset( $request['form_data'] ) ) {
  524. $form_data = $request['form_data'];
  525. } else {
  526. $form_data = array();
  527. }
  528. $original_post = $_POST;
  529. $original_request = $_REQUEST;
  530. foreach ( $form_data as $key => $value ) {
  531. $slashed_value = wp_slash( $value );
  532. $_POST[ $key ] = $slashed_value;
  533. $_REQUEST[ $key ] = $slashed_value;
  534. }
  535. $callback = $wp_registered_widget_updates[ $id_base ]['callback'];
  536. $params = $wp_registered_widget_updates[ $id_base ]['params'];
  537. if ( is_callable( $callback ) ) {
  538. ob_start();
  539. call_user_func_array( $callback, $params );
  540. ob_end_clean();
  541. }
  542. $_POST = $original_post;
  543. $_REQUEST = $original_request;
  544. if ( $widget_object ) {
  545. // Register any multi-widget that the update callback just created.
  546. $widget_object->_set( $number );
  547. $widget_object->_register_one( $number );
  548. /*
  549. * WP_Widget sets `updated = true` after an update to prevent more than one widget
  550. * from being saved per request. This isn't what we want in the REST API, though,
  551. * as we support batch requests.
  552. */
  553. $widget_object->updated = false;
  554. }
  555. /**
  556. * Fires after a widget is created or updated via the REST API.
  557. *
  558. * @since 5.8.0
  559. *
  560. * @param string $id ID of the widget being saved.
  561. * @param string $sidebar_id ID of the sidebar containing the widget being saved.
  562. * @param WP_REST_Request $request Request object.
  563. * @param bool $creating True when creating a widget, false when updating.
  564. */
  565. do_action( 'rest_after_save_widget', $id, $sidebar_id, $request, $creating );
  566. return $id;
  567. }
  568. /**
  569. * Prepares the widget for the REST response.
  570. *
  571. * @since 5.8.0
  572. *
  573. * @global WP_Widget_Factory $wp_widget_factory
  574. * @global array $wp_registered_widgets The registered widgets.
  575. *
  576. * @param array $item An array containing a widget_id and sidebar_id.
  577. * @param WP_REST_Request $request Request object.
  578. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  579. */
  580. public function prepare_item_for_response( $item, $request ) {
  581. global $wp_widget_factory, $wp_registered_widgets;
  582. $widget_id = $item['widget_id'];
  583. $sidebar_id = $item['sidebar_id'];
  584. if ( ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
  585. return new WP_Error(
  586. 'rest_invalid_widget',
  587. __( 'The requested widget is invalid.' ),
  588. array( 'status' => 500 )
  589. );
  590. }
  591. $widget = $wp_registered_widgets[ $widget_id ];
  592. $parsed_id = wp_parse_widget_id( $widget_id );
  593. $fields = $this->get_fields_for_response( $request );
  594. $prepared = array(
  595. 'id' => $widget_id,
  596. 'id_base' => $parsed_id['id_base'],
  597. 'sidebar' => $sidebar_id,
  598. 'rendered' => '',
  599. 'rendered_form' => null,
  600. 'instance' => null,
  601. );
  602. if (
  603. rest_is_field_included( 'rendered', $fields ) &&
  604. 'wp_inactive_widgets' !== $sidebar_id
  605. ) {
  606. $prepared['rendered'] = trim( wp_render_widget( $widget_id, $sidebar_id ) );
  607. }
  608. if ( rest_is_field_included( 'rendered_form', $fields ) ) {
  609. $rendered_form = wp_render_widget_control( $widget_id );
  610. if ( ! is_null( $rendered_form ) ) {
  611. $prepared['rendered_form'] = trim( $rendered_form );
  612. }
  613. }
  614. if ( rest_is_field_included( 'instance', $fields ) ) {
  615. $widget_object = $wp_widget_factory->get_widget_object( $parsed_id['id_base'] );
  616. if ( $widget_object && isset( $parsed_id['number'] ) ) {
  617. $all_instances = $widget_object->get_settings();
  618. $instance = $all_instances[ $parsed_id['number'] ];
  619. $serialized_instance = serialize( $instance );
  620. $prepared['instance']['encoded'] = base64_encode( $serialized_instance );
  621. $prepared['instance']['hash'] = wp_hash( $serialized_instance );
  622. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  623. // Use new stdClass so that JSON result is {} and not [].
  624. $prepared['instance']['raw'] = empty( $instance ) ? new stdClass : $instance;
  625. }
  626. }
  627. }
  628. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  629. $prepared = $this->add_additional_fields_to_object( $prepared, $request );
  630. $prepared = $this->filter_response_by_context( $prepared, $context );
  631. $response = rest_ensure_response( $prepared );
  632. if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
  633. $response->add_links( $this->prepare_links( $prepared ) );
  634. }
  635. /**
  636. * Filters the REST API response for a widget.
  637. *
  638. * @since 5.8.0
  639. *
  640. * @param WP_REST_Response|WP_Error $response The response object, or WP_Error object on failure.
  641. * @param array $widget The registered widget data.
  642. * @param WP_REST_Request $request Request used to generate the response.
  643. */
  644. return apply_filters( 'rest_prepare_widget', $response, $widget, $request );
  645. }
  646. /**
  647. * Prepares links for the widget.
  648. *
  649. * @since 5.8.0
  650. *
  651. * @param array $prepared Widget.
  652. * @return array Links for the given widget.
  653. */
  654. protected function prepare_links( $prepared ) {
  655. $id_base = ! empty( $prepared['id_base'] ) ? $prepared['id_base'] : $prepared['id'];
  656. return array(
  657. 'self' => array(
  658. 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $prepared['id'] ) ),
  659. ),
  660. 'collection' => array(
  661. 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
  662. ),
  663. 'about' => array(
  664. 'href' => rest_url( sprintf( 'wp/v2/widget-types/%s', $id_base ) ),
  665. 'embeddable' => true,
  666. ),
  667. 'https://api.w.org/sidebar' => array(
  668. 'href' => rest_url( sprintf( 'wp/v2/sidebars/%s/', $prepared['sidebar'] ) ),
  669. ),
  670. );
  671. }
  672. /**
  673. * Gets the list of collection params.
  674. *
  675. * @since 5.8.0
  676. *
  677. * @return array[]
  678. */
  679. public function get_collection_params() {
  680. return array(
  681. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  682. 'sidebar' => array(
  683. 'description' => __( 'The sidebar to return widgets for.' ),
  684. 'type' => 'string',
  685. ),
  686. );
  687. }
  688. /**
  689. * Retrieves the widget's schema, conforming to JSON Schema.
  690. *
  691. * @since 5.8.0
  692. *
  693. * @return array Item schema data.
  694. */
  695. public function get_item_schema() {
  696. if ( $this->schema ) {
  697. return $this->add_additional_fields_schema( $this->schema );
  698. }
  699. $this->schema = array(
  700. '$schema' => 'http://json-schema.org/draft-04/schema#',
  701. 'title' => 'widget',
  702. 'type' => 'object',
  703. 'properties' => array(
  704. 'id' => array(
  705. 'description' => __( 'Unique identifier for the widget.' ),
  706. 'type' => 'string',
  707. 'context' => array( 'view', 'edit', 'embed' ),
  708. ),
  709. 'id_base' => array(
  710. 'description' => __( 'The type of the widget. Corresponds to ID in widget-types endpoint.' ),
  711. 'type' => 'string',
  712. 'context' => array( 'view', 'edit', 'embed' ),
  713. ),
  714. 'sidebar' => array(
  715. 'description' => __( 'The sidebar the widget belongs to.' ),
  716. 'type' => 'string',
  717. 'default' => 'wp_inactive_widgets',
  718. 'required' => true,
  719. 'context' => array( 'view', 'edit', 'embed' ),
  720. ),
  721. 'rendered' => array(
  722. 'description' => __( 'HTML representation of the widget.' ),
  723. 'type' => 'string',
  724. 'context' => array( 'view', 'edit', 'embed' ),
  725. 'readonly' => true,
  726. ),
  727. 'rendered_form' => array(
  728. 'description' => __( 'HTML representation of the widget admin form.' ),
  729. 'type' => 'string',
  730. 'context' => array( 'edit' ),
  731. 'readonly' => true,
  732. ),
  733. 'instance' => array(
  734. 'description' => __( 'Instance settings of the widget, if supported.' ),
  735. 'type' => 'object',
  736. 'context' => array( 'edit' ),
  737. 'default' => null,
  738. 'properties' => array(
  739. 'encoded' => array(
  740. 'description' => __( 'Base64 encoded representation of the instance settings.' ),
  741. 'type' => 'string',
  742. 'context' => array( 'edit' ),
  743. ),
  744. 'hash' => array(
  745. 'description' => __( 'Cryptographic hash of the instance settings.' ),
  746. 'type' => 'string',
  747. 'context' => array( 'edit' ),
  748. ),
  749. 'raw' => array(
  750. 'description' => __( 'Unencoded instance settings, if supported.' ),
  751. 'type' => 'object',
  752. 'context' => array( 'edit' ),
  753. ),
  754. ),
  755. ),
  756. 'form_data' => array(
  757. 'description' => __( 'URL-encoded form data from the widget admin form. Used to update a widget that does not support instance. Write only.' ),
  758. 'type' => 'string',
  759. 'context' => array(),
  760. 'arg_options' => array(
  761. 'sanitize_callback' => static function( $string ) {
  762. $array = array();
  763. wp_parse_str( $string, $array );
  764. return $array;
  765. },
  766. ),
  767. ),
  768. ),
  769. );
  770. return $this->add_additional_fields_schema( $this->schema );
  771. }
  772. }