Nessuna descrizione

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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. * Checks if a given request has access to read a single global style.
  122. *
  123. * @since 5.9.0
  124. *
  125. * @param WP_REST_Request $request Full details about the request.
  126. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  127. */
  128. public function get_item_permissions_check( $request ) {
  129. $post = $this->get_post( $request['id'] );
  130. if ( is_wp_error( $post ) ) {
  131. return $post;
  132. }
  133. if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
  134. return new WP_Error(
  135. 'rest_forbidden_context',
  136. __( 'Sorry, you are not allowed to edit this global style.' ),
  137. array( 'status' => rest_authorization_required_code() )
  138. );
  139. }
  140. if ( ! $this->check_read_permission( $post ) ) {
  141. return new WP_Error(
  142. 'rest_cannot_view',
  143. __( 'Sorry, you are not allowed to view this global style.' ),
  144. array( 'status' => rest_authorization_required_code() )
  145. );
  146. }
  147. return true;
  148. }
  149. /**
  150. * Checks if a global style can be read.
  151. *
  152. * @since 5.9.0
  153. *
  154. * @param WP_Post $post Post object.
  155. * @return bool Whether the post can be read.
  156. */
  157. protected function check_read_permission( $post ) {
  158. return current_user_can( 'read_post', $post->ID );
  159. }
  160. /**
  161. * Returns the given global styles config.
  162. *
  163. * @since 5.9.0
  164. *
  165. * @param WP_REST_Request $request The request instance.
  166. *
  167. * @return WP_REST_Response|WP_Error
  168. */
  169. public function get_item( $request ) {
  170. $post = $this->get_post( $request['id'] );
  171. if ( is_wp_error( $post ) ) {
  172. return $post;
  173. }
  174. return $this->prepare_item_for_response( $post, $request );
  175. }
  176. /**
  177. * Checks if a given request has access to write a single global styles config.
  178. *
  179. * @since 5.9.0
  180. *
  181. * @param WP_REST_Request $request Full details about the request.
  182. * @return true|WP_Error True if the request has write access for the item, WP_Error object otherwise.
  183. */
  184. public function update_item_permissions_check( $request ) {
  185. $post = $this->get_post( $request['id'] );
  186. if ( is_wp_error( $post ) ) {
  187. return $post;
  188. }
  189. if ( $post && ! $this->check_update_permission( $post ) ) {
  190. return new WP_Error(
  191. 'rest_cannot_edit',
  192. __( 'Sorry, you are not allowed to edit this global style.' ),
  193. array( 'status' => rest_authorization_required_code() )
  194. );
  195. }
  196. return true;
  197. }
  198. /**
  199. * Checks if a global style can be edited.
  200. *
  201. * @since 5.9.0
  202. *
  203. * @param WP_Post $post Post object.
  204. * @return bool Whether the post can be edited.
  205. */
  206. protected function check_update_permission( $post ) {
  207. return current_user_can( 'edit_post', $post->ID );
  208. }
  209. /**
  210. * Updates a single global style config.
  211. *
  212. * @since 5.9.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 update_item( $request ) {
  218. $post_before = $this->get_post( $request['id'] );
  219. if ( is_wp_error( $post_before ) ) {
  220. return $post_before;
  221. }
  222. $changes = $this->prepare_item_for_database( $request );
  223. $result = wp_update_post( wp_slash( (array) $changes ), true, false );
  224. if ( is_wp_error( $result ) ) {
  225. return $result;
  226. }
  227. $post = get_post( $request['id'] );
  228. $fields_update = $this->update_additional_fields_for_object( $post, $request );
  229. if ( is_wp_error( $fields_update ) ) {
  230. return $fields_update;
  231. }
  232. wp_after_insert_post( $post, true, $post_before );
  233. $response = $this->prepare_item_for_response( $post, $request );
  234. return rest_ensure_response( $response );
  235. }
  236. /**
  237. * Prepares a single global styles config for update.
  238. *
  239. * @since 5.9.0
  240. *
  241. * @param WP_REST_Request $request Request object.
  242. * @return stdClass Changes to pass to wp_update_post.
  243. */
  244. protected function prepare_item_for_database( $request ) {
  245. $changes = new stdClass();
  246. $changes->ID = $request['id'];
  247. $post = get_post( $request['id'] );
  248. $existing_config = array();
  249. if ( $post ) {
  250. $existing_config = json_decode( $post->post_content, true );
  251. $json_decoding_error = json_last_error();
  252. if ( JSON_ERROR_NONE !== $json_decoding_error || ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) ||
  253. ! $existing_config['isGlobalStylesUserThemeJSON'] ) {
  254. $existing_config = array();
  255. }
  256. }
  257. if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) {
  258. $config = array();
  259. if ( isset( $request['styles'] ) ) {
  260. $config['styles'] = $request['styles'];
  261. } elseif ( isset( $existing_config['styles'] ) ) {
  262. $config['styles'] = $existing_config['styles'];
  263. }
  264. if ( isset( $request['settings'] ) ) {
  265. $config['settings'] = $request['settings'];
  266. } elseif ( isset( $existing_config['settings'] ) ) {
  267. $config['settings'] = $existing_config['settings'];
  268. }
  269. $config['isGlobalStylesUserThemeJSON'] = true;
  270. $config['version'] = WP_Theme_JSON::LATEST_SCHEMA;
  271. $changes->post_content = wp_json_encode( $config );
  272. }
  273. // Post title.
  274. if ( isset( $request['title'] ) ) {
  275. if ( is_string( $request['title'] ) ) {
  276. $changes->post_title = $request['title'];
  277. } elseif ( ! empty( $request['title']['raw'] ) ) {
  278. $changes->post_title = $request['title']['raw'];
  279. }
  280. }
  281. return $changes;
  282. }
  283. /**
  284. * Prepare a global styles config output for response.
  285. *
  286. * @since 5.9.0
  287. *
  288. * @param WP_Post $post Global Styles post object.
  289. * @param WP_REST_Request $request Request object.
  290. * @return WP_REST_Response Response object.
  291. */
  292. public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
  293. $raw_config = json_decode( $post->post_content, true );
  294. $is_global_styles_user_theme_json = isset( $raw_config['isGlobalStylesUserThemeJSON'] ) && true === $raw_config['isGlobalStylesUserThemeJSON'];
  295. $config = array();
  296. if ( $is_global_styles_user_theme_json ) {
  297. $config = ( new WP_Theme_JSON( $raw_config, 'custom' ) )->get_raw_data();
  298. }
  299. // Base fields for every post.
  300. $data = array();
  301. $fields = $this->get_fields_for_response( $request );
  302. if ( rest_is_field_included( 'id', $fields ) ) {
  303. $data['id'] = $post->ID;
  304. }
  305. if ( rest_is_field_included( 'title', $fields ) ) {
  306. $data['title'] = array();
  307. }
  308. if ( rest_is_field_included( 'title.raw', $fields ) ) {
  309. $data['title']['raw'] = $post->post_title;
  310. }
  311. if ( rest_is_field_included( 'title.rendered', $fields ) ) {
  312. add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  313. $data['title']['rendered'] = get_the_title( $post->ID );
  314. remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  315. }
  316. if ( rest_is_field_included( 'settings', $fields ) ) {
  317. $data['settings'] = ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass();
  318. }
  319. if ( rest_is_field_included( 'styles', $fields ) ) {
  320. $data['styles'] = ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass();
  321. }
  322. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  323. $data = $this->add_additional_fields_to_object( $data, $request );
  324. $data = $this->filter_response_by_context( $data, $context );
  325. // Wrap the data in a response object.
  326. $response = rest_ensure_response( $data );
  327. $links = $this->prepare_links( $post->ID );
  328. $response->add_links( $links );
  329. if ( ! empty( $links['self']['href'] ) ) {
  330. $actions = $this->get_available_actions();
  331. $self = $links['self']['href'];
  332. foreach ( $actions as $rel ) {
  333. $response->add_link( $rel, $self );
  334. }
  335. }
  336. return $response;
  337. }
  338. /**
  339. * Get the post, if the ID is valid.
  340. *
  341. * @since 5.9.0
  342. *
  343. * @param int $id Supplied ID.
  344. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
  345. */
  346. protected function get_post( $id ) {
  347. $error = new WP_Error(
  348. 'rest_global_styles_not_found',
  349. __( 'No global styles config exist with that id.' ),
  350. array( 'status' => 404 )
  351. );
  352. $id = (int) $id;
  353. if ( $id <= 0 ) {
  354. return $error;
  355. }
  356. $post = get_post( $id );
  357. if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
  358. return $error;
  359. }
  360. return $post;
  361. }
  362. /**
  363. * Prepares links for the request.
  364. *
  365. * @since 5.9.0
  366. *
  367. * @param integer $id ID.
  368. * @return array Links for the given post.
  369. */
  370. protected function prepare_links( $id ) {
  371. $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
  372. $links = array(
  373. 'self' => array(
  374. 'href' => rest_url( trailingslashit( $base ) . $id ),
  375. ),
  376. );
  377. return $links;
  378. }
  379. /**
  380. * Get the link relations available for the post and current user.
  381. *
  382. * @since 5.9.0
  383. *
  384. * @return array List of link relations.
  385. */
  386. protected function get_available_actions() {
  387. $rels = array();
  388. $post_type = get_post_type_object( $this->post_type );
  389. if ( current_user_can( $post_type->cap->publish_posts ) ) {
  390. $rels[] = 'https://api.w.org/action-publish';
  391. }
  392. return $rels;
  393. }
  394. /**
  395. * Overwrites the default protected title format.
  396. *
  397. * By default, WordPress will show password protected posts with a title of
  398. * "Protected: %s", as the REST API communicates the protected status of a post
  399. * in a machine readable format, we remove the "Protected: " prefix.
  400. *
  401. * @since 5.9.0
  402. *
  403. * @return string Protected title format.
  404. */
  405. public function protected_title_format() {
  406. return '%s';
  407. }
  408. /**
  409. * Retrieves the query params for the global styles collection.
  410. *
  411. * @since 5.9.0
  412. *
  413. * @return array Collection parameters.
  414. */
  415. public function get_collection_params() {
  416. return array();
  417. }
  418. /**
  419. * Retrieves the global styles type' schema, conforming to JSON Schema.
  420. *
  421. * @since 5.9.0
  422. *
  423. * @return array Item schema data.
  424. */
  425. public function get_item_schema() {
  426. if ( $this->schema ) {
  427. return $this->add_additional_fields_schema( $this->schema );
  428. }
  429. $schema = array(
  430. '$schema' => 'http://json-schema.org/draft-04/schema#',
  431. 'title' => $this->post_type,
  432. 'type' => 'object',
  433. 'properties' => array(
  434. 'id' => array(
  435. 'description' => __( 'ID of global styles config.' ),
  436. 'type' => 'string',
  437. 'context' => array( 'embed', 'view', 'edit' ),
  438. 'readonly' => true,
  439. ),
  440. 'styles' => array(
  441. 'description' => __( 'Global styles.' ),
  442. 'type' => array( 'object' ),
  443. 'context' => array( 'view', 'edit' ),
  444. ),
  445. 'settings' => array(
  446. 'description' => __( 'Global settings.' ),
  447. 'type' => array( 'object' ),
  448. 'context' => array( 'view', 'edit' ),
  449. ),
  450. 'title' => array(
  451. 'description' => __( 'Title of the global styles variation.' ),
  452. 'type' => array( 'object', 'string' ),
  453. 'default' => '',
  454. 'context' => array( 'embed', 'view', 'edit' ),
  455. 'properties' => array(
  456. 'raw' => array(
  457. 'description' => __( 'Title for the global styles variation, as it exists in the database.' ),
  458. 'type' => 'string',
  459. 'context' => array( 'view', 'edit', 'embed' ),
  460. ),
  461. 'rendered' => array(
  462. 'description' => __( 'HTML title for the post, transformed for display.' ),
  463. 'type' => 'string',
  464. 'context' => array( 'view', 'edit', 'embed' ),
  465. 'readonly' => true,
  466. ),
  467. ),
  468. ),
  469. ),
  470. );
  471. $this->schema = $schema;
  472. return $this->add_additional_fields_schema( $this->schema );
  473. }
  474. /**
  475. * Checks if a given request has access to read a single theme global styles config.
  476. *
  477. * @since 5.9.0
  478. *
  479. * @param WP_REST_Request $request Full details about the request.
  480. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  481. */
  482. public function get_theme_item_permissions_check( $request ) {
  483. // Verify if the current user has edit_theme_options capability.
  484. // This capability is required to edit/view/delete templates.
  485. if ( ! current_user_can( 'edit_theme_options' ) ) {
  486. return new WP_Error(
  487. 'rest_cannot_manage_global_styles',
  488. __( 'Sorry, you are not allowed to access the global styles on this site.' ),
  489. array(
  490. 'status' => rest_authorization_required_code(),
  491. )
  492. );
  493. }
  494. return true;
  495. }
  496. /**
  497. * Returns the given theme global styles config.
  498. *
  499. * @since 5.9.0
  500. *
  501. * @param WP_REST_Request $request The request instance.
  502. * @return WP_REST_Response|WP_Error
  503. */
  504. public function get_theme_item( $request ) {
  505. if ( wp_get_theme()->get_stylesheet() !== $request['stylesheet'] ) {
  506. // This endpoint only supports the active theme for now.
  507. return new WP_Error(
  508. 'rest_theme_not_found',
  509. __( 'Theme not found.' ),
  510. array( 'status' => 404 )
  511. );
  512. }
  513. $theme = WP_Theme_JSON_Resolver::get_merged_data( 'theme' );
  514. $data = array();
  515. $fields = $this->get_fields_for_response( $request );
  516. if ( rest_is_field_included( 'settings', $fields ) ) {
  517. $data['settings'] = $theme->get_settings();
  518. }
  519. if ( rest_is_field_included( 'styles', $fields ) ) {
  520. $raw_data = $theme->get_raw_data();
  521. $data['styles'] = isset( $raw_data['styles'] ) ? $raw_data['styles'] : array();
  522. }
  523. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  524. $data = $this->add_additional_fields_to_object( $data, $request );
  525. $data = $this->filter_response_by_context( $data, $context );
  526. $response = rest_ensure_response( $data );
  527. $links = array(
  528. 'self' => array(
  529. 'href' => rest_url( sprintf( '%s/%s/themes/%s', $this->namespace, $this->rest_base, $request['stylesheet'] ) ),
  530. ),
  531. );
  532. $response->add_links( $links );
  533. return $response;
  534. }
  535. /**
  536. * Checks if a given request has access to read a single theme global styles config.
  537. *
  538. * @since 6.0.0
  539. *
  540. * @param WP_REST_Request $request Full details about the request.
  541. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  542. */
  543. public function get_theme_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
  544. // Verify if the current user has edit_theme_options capability.
  545. // This capability is required to edit/view/delete templates.
  546. if ( ! current_user_can( 'edit_theme_options' ) ) {
  547. return new WP_Error(
  548. 'rest_cannot_manage_global_styles',
  549. __( 'Sorry, you are not allowed to access the global styles on this site.' ),
  550. array(
  551. 'status' => rest_authorization_required_code(),
  552. )
  553. );
  554. }
  555. return true;
  556. }
  557. /**
  558. * Returns the given theme global styles variations.
  559. *
  560. * @since 6.0.0
  561. *
  562. * @param WP_REST_Request $request The request instance.
  563. *
  564. * @return WP_REST_Response|WP_Error
  565. */
  566. public function get_theme_items( $request ) {
  567. if ( wp_get_theme()->get_stylesheet() !== $request['stylesheet'] ) {
  568. // This endpoint only supports the active theme for now.
  569. return new WP_Error(
  570. 'rest_theme_not_found',
  571. __( 'Theme not found.' ),
  572. array( 'status' => 404 )
  573. );
  574. }
  575. $variations = WP_Theme_JSON_Resolver::get_style_variations();
  576. $response = rest_ensure_response( $variations );
  577. return $response;
  578. }
  579. }