class-wp-rest-global-styles-controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. <?php
  2. /**
  3. * REST API: WP_REST_Global_Styles_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 5.9.0
  8. */
  9. /**
  10. * Base Global Styles REST API Controller.
  11. */
  12. class WP_REST_Global_Styles_Controller extends WP_REST_Controller {
  13. /**
  14. * Post type.
  15. *
  16. * @since 5.9.0
  17. * @var string
  18. */
  19. protected $post_type;
  20. /**
  21. * Constructor.
  22. * @since 5.9.0
  23. */
  24. public function __construct() {
  25. $this->namespace = 'wp/v2';
  26. $this->rest_base = 'global-styles';
  27. $this->post_type = 'wp_global_styles';
  28. }
  29. /**
  30. * Registers the controllers routes.
  31. *
  32. * @since 5.9.0
  33. *
  34. * @return void
  35. */
  36. public function register_routes() {
  37. register_rest_route(
  38. $this->namespace,
  39. '/' . $this->rest_base . '/themes/(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations',
  40. array(
  41. array(
  42. 'methods' => WP_REST_Server::READABLE,
  43. 'callback' => array( $this, 'get_theme_items' ),
  44. 'permission_callback' => array( $this, 'get_theme_items_permissions_check' ),
  45. 'args' => array(
  46. 'stylesheet' => array(
  47. 'description' => __( 'The theme identifier' ),
  48. 'type' => 'string',
  49. ),
  50. ),
  51. ),
  52. )
  53. );
  54. // List themes global styles.
  55. register_rest_route(
  56. $this->namespace,
  57. // The route.
  58. sprintf(
  59. '/%s/themes/(?P<stylesheet>%s)',
  60. $this->rest_base,
  61. // Matches theme's directory: `/themes/<subdirectory>/<theme>/` or `/themes/<theme>/`.
  62. // Excludes invalid directory name characters: `/:<>*?"|`.
  63. '[^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?'
  64. ),
  65. array(
  66. array(
  67. 'methods' => WP_REST_Server::READABLE,
  68. 'callback' => array( $this, 'get_theme_item' ),
  69. 'permission_callback' => array( $this, 'get_theme_item_permissions_check' ),
  70. 'args' => array(
  71. 'stylesheet' => array(
  72. 'description' => __( 'The theme identifier' ),
  73. 'type' => 'string',
  74. 'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
  75. ),
  76. ),
  77. ),
  78. )
  79. );
  80. // Lists/updates a single global style variation based on the given id.
  81. register_rest_route(
  82. $this->namespace,
  83. '/' . $this->rest_base . '/(?P<id>[\/\w-]+)',
  84. array(
  85. array(
  86. 'methods' => WP_REST_Server::READABLE,
  87. 'callback' => array( $this, 'get_item' ),
  88. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  89. 'args' => array(
  90. 'id' => array(
  91. 'description' => __( 'The id of a template' ),
  92. 'type' => 'string',
  93. 'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
  94. ),
  95. ),
  96. ),
  97. array(
  98. 'methods' => WP_REST_Server::EDITABLE,
  99. 'callback' => array( $this, 'update_item' ),
  100. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  101. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  102. ),
  103. 'schema' => array( $this, 'get_public_item_schema' ),
  104. )
  105. );
  106. }
  107. /**
  108. * Sanitize the global styles ID or stylesheet to decode endpoint.
  109. * For example, `wp/v2/global-styles/twentytwentytwo%200.4.0`
  110. * would be decoded to `twentytwentytwo 0.4.0`.
  111. *
  112. * @since 5.9.0
  113. *
  114. * @param string $id_or_stylesheet Global styles ID or stylesheet.
  115. * @return string Sanitized global styles ID or stylesheet.
  116. */
  117. public function _sanitize_global_styles_callback( $id_or_stylesheet ) {
  118. return urldecode( $id_or_stylesheet );
  119. }
  120. /**
  121. * Get the post, if the ID is valid.
  122. *
  123. * @since 5.9.0
  124. *
  125. * @param int $id Supplied ID.
  126. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
  127. */
  128. protected function get_post( $id ) {
  129. $error = new WP_Error(
  130. 'rest_global_styles_not_found',
  131. __( 'No global styles config exist with that id.' ),
  132. array( 'status' => 404 )
  133. );
  134. $id = (int) $id;
  135. if ( $id <= 0 ) {
  136. return $error;
  137. }
  138. $post = get_post( $id );
  139. if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
  140. return $error;
  141. }
  142. return $post;
  143. }
  144. /**
  145. * Checks if a given request has access to read a single global style.
  146. *
  147. * @since 5.9.0
  148. *
  149. * @param WP_REST_Request $request Full details about the request.
  150. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  151. */
  152. public function get_item_permissions_check( $request ) {
  153. $post = $this->get_post( $request['id'] );
  154. if ( is_wp_error( $post ) ) {
  155. return $post;
  156. }
  157. if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
  158. return new WP_Error(
  159. 'rest_forbidden_context',
  160. __( 'Sorry, you are not allowed to edit this global style.' ),
  161. array( 'status' => rest_authorization_required_code() )
  162. );
  163. }
  164. if ( ! $this->check_read_permission( $post ) ) {
  165. return new WP_Error(
  166. 'rest_cannot_view',
  167. __( 'Sorry, you are not allowed to view this global style.' ),
  168. array( 'status' => rest_authorization_required_code() )
  169. );
  170. }
  171. return true;
  172. }
  173. /**
  174. * Checks if a global style can be read.
  175. *
  176. * @since 5.9.0
  177. *
  178. * @param WP_Post $post Post object.
  179. * @return bool Whether the post can be read.
  180. */
  181. protected function check_read_permission( $post ) {
  182. return current_user_can( 'read_post', $post->ID );
  183. }
  184. /**
  185. * Returns the given global styles config.
  186. *
  187. * @since 5.9.0
  188. *
  189. * @param WP_REST_Request $request The request instance.
  190. *
  191. * @return WP_REST_Response|WP_Error
  192. */
  193. public function get_item( $request ) {
  194. $post = $this->get_post( $request['id'] );
  195. if ( is_wp_error( $post ) ) {
  196. return $post;
  197. }
  198. return $this->prepare_item_for_response( $post, $request );
  199. }
  200. /**
  201. * Checks if a given request has access to write a single global styles config.
  202. *
  203. * @since 5.9.0
  204. *
  205. * @param WP_REST_Request $request Full details about the request.
  206. * @return true|WP_Error True if the request has write access for the item, WP_Error object otherwise.
  207. */
  208. public function update_item_permissions_check( $request ) {
  209. $post = $this->get_post( $request['id'] );
  210. if ( is_wp_error( $post ) ) {
  211. return $post;
  212. }
  213. if ( $post && ! $this->check_update_permission( $post ) ) {
  214. return new WP_Error(
  215. 'rest_cannot_edit',
  216. __( 'Sorry, you are not allowed to edit this global style.' ),
  217. array( 'status' => rest_authorization_required_code() )
  218. );
  219. }
  220. return true;
  221. }
  222. /**
  223. * Checks if a global style can be edited.
  224. *
  225. * @since 5.9.0
  226. *
  227. * @param WP_Post $post Post object.
  228. * @return bool Whether the post can be edited.
  229. */
  230. protected function check_update_permission( $post ) {
  231. return current_user_can( 'edit_post', $post->ID );
  232. }
  233. /**
  234. * Updates a single global style config.
  235. *
  236. * @since 5.9.0
  237. *
  238. * @param WP_REST_Request $request Full details about the request.
  239. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  240. */
  241. public function update_item( $request ) {
  242. $post_before = $this->get_post( $request['id'] );
  243. if ( is_wp_error( $post_before ) ) {
  244. return $post_before;
  245. }
  246. $changes = $this->prepare_item_for_database( $request );
  247. $result = wp_update_post( wp_slash( (array) $changes ), true, false );
  248. if ( is_wp_error( $result ) ) {
  249. return $result;
  250. }
  251. $post = get_post( $request['id'] );
  252. $fields_update = $this->update_additional_fields_for_object( $post, $request );
  253. if ( is_wp_error( $fields_update ) ) {
  254. return $fields_update;
  255. }
  256. wp_after_insert_post( $post, true, $post_before );
  257. $response = $this->prepare_item_for_response( $post, $request );
  258. return rest_ensure_response( $response );
  259. }
  260. /**
  261. * Prepares a single global styles config for update.
  262. *
  263. * @since 5.9.0
  264. *
  265. * @param WP_REST_Request $request Request object.
  266. * @return stdClass Changes to pass to wp_update_post.
  267. */
  268. protected function prepare_item_for_database( $request ) {
  269. $changes = new stdClass();
  270. $changes->ID = $request['id'];
  271. $post = get_post( $request['id'] );
  272. $existing_config = array();
  273. if ( $post ) {
  274. $existing_config = json_decode( $post->post_content, true );
  275. $json_decoding_error = json_last_error();
  276. if ( JSON_ERROR_NONE !== $json_decoding_error || ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) ||
  277. ! $existing_config['isGlobalStylesUserThemeJSON'] ) {
  278. $existing_config = array();
  279. }
  280. }
  281. if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) {
  282. $config = array();
  283. if ( isset( $request['styles'] ) ) {
  284. $config['styles'] = $request['styles'];
  285. } elseif ( isset( $existing_config['styles'] ) ) {
  286. $config['styles'] = $existing_config['styles'];
  287. }
  288. if ( isset( $request['settings'] ) ) {
  289. $config['settings'] = $request['settings'];
  290. } elseif ( isset( $existing_config['settings'] ) ) {
  291. $config['settings'] = $existing_config['settings'];
  292. }
  293. $config['isGlobalStylesUserThemeJSON'] = true;
  294. $config['version'] = WP_Theme_JSON::LATEST_SCHEMA;
  295. $changes->post_content = wp_json_encode( $config );
  296. }
  297. // Post title.
  298. if ( isset( $request['title'] ) ) {
  299. if ( is_string( $request['title'] ) ) {
  300. $changes->post_title = $request['title'];
  301. } elseif ( ! empty( $request['title']['raw'] ) ) {
  302. $changes->post_title = $request['title']['raw'];
  303. }
  304. }
  305. return $changes;
  306. }
  307. /**
  308. * Prepare a global styles config output for response.
  309. *
  310. * @since 5.9.0
  311. *
  312. * @param WP_Post $post Global Styles post object.
  313. * @param WP_REST_Request $request Request object.
  314. * @return WP_REST_Response Response object.
  315. */
  316. public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
  317. $raw_config = json_decode( $post->post_content, true );
  318. $is_global_styles_user_theme_json = isset( $raw_config['isGlobalStylesUserThemeJSON'] ) && true === $raw_config['isGlobalStylesUserThemeJSON'];
  319. $config = array();
  320. if ( $is_global_styles_user_theme_json ) {
  321. $config = ( new WP_Theme_JSON( $raw_config, 'custom' ) )->get_raw_data();
  322. }
  323. // Base fields for every post.
  324. $data = array();
  325. $fields = $this->get_fields_for_response( $request );
  326. if ( rest_is_field_included( 'id', $fields ) ) {
  327. $data['id'] = $post->ID;
  328. }
  329. if ( rest_is_field_included( 'title', $fields ) ) {
  330. $data['title'] = array();
  331. }
  332. if ( rest_is_field_included( 'title.raw', $fields ) ) {
  333. $data['title']['raw'] = $post->post_title;
  334. }
  335. if ( rest_is_field_included( 'title.rendered', $fields ) ) {
  336. add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  337. $data['title']['rendered'] = get_the_title( $post->ID );
  338. remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  339. }
  340. if ( rest_is_field_included( 'settings', $fields ) ) {
  341. $data['settings'] = ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass();
  342. }
  343. if ( rest_is_field_included( 'styles', $fields ) ) {
  344. $data['styles'] = ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass();
  345. }
  346. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  347. $data = $this->add_additional_fields_to_object( $data, $request );
  348. $data = $this->filter_response_by_context( $data, $context );
  349. // Wrap the data in a response object.
  350. $response = rest_ensure_response( $data );
  351. if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
  352. $links = $this->prepare_links( $post->ID );
  353. $response->add_links( $links );
  354. if ( ! empty( $links['self']['href'] ) ) {
  355. $actions = $this->get_available_actions();
  356. $self = $links['self']['href'];
  357. foreach ( $actions as $rel ) {
  358. $response->add_link( $rel, $self );
  359. }
  360. }
  361. }
  362. return $response;
  363. }
  364. /**
  365. * Prepares links for the request.
  366. *
  367. * @since 5.9.0
  368. *
  369. * @param integer $id ID.
  370. * @return array Links for the given post.
  371. */
  372. protected function prepare_links( $id ) {
  373. $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
  374. $links = array(
  375. 'self' => array(
  376. 'href' => rest_url( trailingslashit( $base ) . $id ),
  377. ),
  378. );
  379. return $links;
  380. }
  381. /**
  382. * Get the link relations available for the post and current user.
  383. *
  384. * @since 5.9.0
  385. *
  386. * @return array List of link relations.
  387. */
  388. protected function get_available_actions() {
  389. $rels = array();
  390. $post_type = get_post_type_object( $this->post_type );
  391. if ( current_user_can( $post_type->cap->publish_posts ) ) {
  392. $rels[] = 'https://api.w.org/action-publish';
  393. }
  394. return $rels;
  395. }
  396. /**
  397. * Overwrites the default protected title format.
  398. *
  399. * By default, WordPress will show password protected posts with a title of
  400. * "Protected: %s", as the REST API communicates the protected status of a post
  401. * in a machine readable format, we remove the "Protected: " prefix.
  402. *
  403. * @since 5.9.0
  404. *
  405. * @return string Protected title format.
  406. */
  407. public function protected_title_format() {
  408. return '%s';
  409. }
  410. /**
  411. * Retrieves the query params for the global styles collection.
  412. *
  413. * @since 5.9.0
  414. *
  415. * @return array Collection parameters.
  416. */
  417. public function get_collection_params() {
  418. return array();
  419. }
  420. /**
  421. * Retrieves the global styles type' schema, conforming to JSON Schema.
  422. *
  423. * @since 5.9.0
  424. *
  425. * @return array Item schema data.
  426. */
  427. public function get_item_schema() {
  428. if ( $this->schema ) {
  429. return $this->add_additional_fields_schema( $this->schema );
  430. }
  431. $schema = array(
  432. '$schema' => 'http://json-schema.org/draft-04/schema#',
  433. 'title' => $this->post_type,
  434. 'type' => 'object',
  435. 'properties' => array(
  436. 'id' => array(
  437. 'description' => __( 'ID of global styles config.' ),
  438. 'type' => 'string',
  439. 'context' => array( 'embed', 'view', 'edit' ),
  440. 'readonly' => true,
  441. ),
  442. 'styles' => array(
  443. 'description' => __( 'Global styles.' ),
  444. 'type' => array( 'object' ),
  445. 'context' => array( 'view', 'edit' ),
  446. ),
  447. 'settings' => array(
  448. 'description' => __( 'Global settings.' ),
  449. 'type' => array( 'object' ),
  450. 'context' => array( 'view', 'edit' ),
  451. ),
  452. 'title' => array(
  453. 'description' => __( 'Title of the global styles variation.' ),
  454. 'type' => array( 'object', 'string' ),
  455. 'default' => '',
  456. 'context' => array( 'embed', 'view', 'edit' ),
  457. 'properties' => array(
  458. 'raw' => array(
  459. 'description' => __( 'Title for the global styles variation, as it exists in the database.' ),
  460. 'type' => 'string',
  461. 'context' => array( 'view', 'edit', 'embed' ),
  462. ),
  463. 'rendered' => array(
  464. 'description' => __( 'HTML title for the post, transformed for display.' ),
  465. 'type' => 'string',
  466. 'context' => array( 'view', 'edit', 'embed' ),
  467. 'readonly' => true,
  468. ),
  469. ),
  470. ),
  471. ),
  472. );
  473. $this->schema = $schema;
  474. return $this->add_additional_fields_schema( $this->schema );
  475. }
  476. /**
  477. * Checks if a given request has access to read a single theme global styles config.
  478. *
  479. * @since 5.9.0
  480. *
  481. * @param WP_REST_Request $request Full details about the request.
  482. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  483. */
  484. public function get_theme_item_permissions_check( $request ) {
  485. // Verify if the current user has edit_theme_options capability.
  486. // This capability is required to edit/view/delete templates.
  487. if ( ! current_user_can( 'edit_theme_options' ) ) {
  488. return new WP_Error(
  489. 'rest_cannot_manage_global_styles',
  490. __( 'Sorry, you are not allowed to access the global styles on this site.' ),
  491. array(
  492. 'status' => rest_authorization_required_code(),
  493. )
  494. );
  495. }
  496. return true;
  497. }
  498. /**
  499. * Returns the given theme global styles config.
  500. *
  501. * @since 5.9.0
  502. *
  503. * @param WP_REST_Request $request The request instance.
  504. * @return WP_REST_Response|WP_Error
  505. */
  506. public function get_theme_item( $request ) {
  507. if ( get_stylesheet() !== $request['stylesheet'] ) {
  508. // This endpoint only supports the active theme for now.
  509. return new WP_Error(
  510. 'rest_theme_not_found',
  511. __( 'Theme not found.' ),
  512. array( 'status' => 404 )
  513. );
  514. }
  515. $theme = WP_Theme_JSON_Resolver::get_merged_data( 'theme' );
  516. $data = array();
  517. $fields = $this->get_fields_for_response( $request );
  518. if ( rest_is_field_included( 'settings', $fields ) ) {
  519. $data['settings'] = $theme->get_settings();
  520. }
  521. if ( rest_is_field_included( 'styles', $fields ) ) {
  522. $raw_data = $theme->get_raw_data();
  523. $data['styles'] = isset( $raw_data['styles'] ) ? $raw_data['styles'] : array();
  524. }
  525. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  526. $data = $this->add_additional_fields_to_object( $data, $request );
  527. $data = $this->filter_response_by_context( $data, $context );
  528. $response = rest_ensure_response( $data );
  529. if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
  530. $links = array(
  531. 'self' => array(
  532. 'href' => rest_url( sprintf( '%s/%s/themes/%s', $this->namespace, $this->rest_base, $request['stylesheet'] ) ),
  533. ),
  534. );
  535. $response->add_links( $links );
  536. }
  537. return $response;
  538. }
  539. /**
  540. * Checks if a given request has access to read a single theme global styles config.
  541. *
  542. * @since 6.0.0
  543. *
  544. * @param WP_REST_Request $request Full details about the request.
  545. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  546. */
  547. public function get_theme_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
  548. // Verify if the current user has edit_theme_options capability.
  549. // This capability is required to edit/view/delete templates.
  550. if ( ! current_user_can( 'edit_theme_options' ) ) {
  551. return new WP_Error(
  552. 'rest_cannot_manage_global_styles',
  553. __( 'Sorry, you are not allowed to access the global styles on this site.' ),
  554. array(
  555. 'status' => rest_authorization_required_code(),
  556. )
  557. );
  558. }
  559. return true;
  560. }
  561. /**
  562. * Returns the given theme global styles variations.
  563. *
  564. * @since 6.0.0
  565. *
  566. * @param WP_REST_Request $request The request instance.
  567. *
  568. * @return WP_REST_Response|WP_Error
  569. */
  570. public function get_theme_items( $request ) {
  571. if ( get_stylesheet() !== $request['stylesheet'] ) {
  572. // This endpoint only supports the active theme for now.
  573. return new WP_Error(
  574. 'rest_theme_not_found',
  575. __( 'Theme not found.' ),
  576. array( 'status' => 404 )
  577. );
  578. }
  579. $variations = WP_Theme_JSON_Resolver::get_style_variations();
  580. $response = rest_ensure_response( $variations );
  581. return $response;
  582. }
  583. }