[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-global-styles-controller.php (source)

   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  /**
  11   * Base Global Styles REST API Controller.
  12   *
  13   * @since 5.9.0
  14   */
  15  class WP_REST_Global_Styles_Controller extends WP_REST_Posts_Controller {
  16      /**
  17       * Whether the controller supports batching.
  18       *
  19       * @since 6.6.0
  20       * @var array
  21       */
  22      protected $allow_batch = array( 'v1' => false );
  23  
  24      /**
  25       * Constructor.
  26       *
  27       * @since 6.6.0
  28       *
  29       * @param string $post_type Post type.
  30       */
  31  	public function __construct( $post_type = 'wp_global_styles' ) {
  32          parent::__construct( $post_type );
  33      }
  34  
  35      /**
  36       * Registers the controllers routes.
  37       *
  38       * @since 5.9.0
  39       */
  40  	public function register_routes() {
  41          register_rest_route(
  42              $this->namespace,
  43              '/' . $this->rest_base . '/themes/(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations',
  44              array(
  45                  array(
  46                      'methods'             => WP_REST_Server::READABLE,
  47                      'callback'            => array( $this, 'get_theme_items' ),
  48                      'permission_callback' => array( $this, 'get_theme_items_permissions_check' ),
  49                      'args'                => array(
  50                          'stylesheet' => array(
  51                              'description' => __( 'The theme identifier' ),
  52                              'type'        => 'string',
  53                          ),
  54                      ),
  55                      'allow_batch'         => $this->allow_batch,
  56                  ),
  57              )
  58          );
  59  
  60          // List themes global styles.
  61          register_rest_route(
  62              $this->namespace,
  63              // The route.
  64              sprintf(
  65                  '/%s/themes/(?P<stylesheet>%s)',
  66                  $this->rest_base,
  67                  /*
  68                   * Matches theme's directory: `/themes/<subdirectory>/<theme>/` or `/themes/<theme>/`.
  69                   * Excludes invalid directory name characters: `/:<>*?"|`.
  70                   */
  71                  '[^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?'
  72              ),
  73              array(
  74                  array(
  75                      'methods'             => WP_REST_Server::READABLE,
  76                      'callback'            => array( $this, 'get_theme_item' ),
  77                      'permission_callback' => array( $this, 'get_theme_item_permissions_check' ),
  78                      'args'                => array(
  79                          'stylesheet' => array(
  80                              'description'       => __( 'The theme identifier' ),
  81                              'type'              => 'string',
  82                              'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
  83                          ),
  84                      ),
  85                      'allow_batch'         => $this->allow_batch,
  86                  ),
  87              )
  88          );
  89  
  90          // Lists/updates a single global style variation based on the given id.
  91          register_rest_route(
  92              $this->namespace,
  93              '/' . $this->rest_base . '/(?P<id>[\/\d+]+)',
  94              array(
  95                  array(
  96                      'methods'             => WP_REST_Server::READABLE,
  97                      'callback'            => array( $this, 'get_item' ),
  98                      'permission_callback' => array( $this, 'get_item_permissions_check' ),
  99                      'args'                => array(
 100                          'id' => array(
 101                              'description' => __( 'ID of global styles config.' ),
 102                              'type'        => 'integer',
 103                          ),
 104                      ),
 105                  ),
 106                  array(
 107                      'methods'             => WP_REST_Server::EDITABLE,
 108                      'callback'            => array( $this, 'update_item' ),
 109                      'permission_callback' => array( $this, 'update_item_permissions_check' ),
 110                      'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
 111                  ),
 112                  'schema'      => array( $this, 'get_public_item_schema' ),
 113                  'allow_batch' => $this->allow_batch,
 114              )
 115          );
 116      }
 117  
 118      /**
 119       * Sanitize the global styles stylesheet to decode endpoint.
 120       * For example, `wp/v2/global-styles/twentytwentytwo%200.4.0`
 121       * would be decoded to `twentytwentytwo 0.4.0`.
 122       *
 123       * @since 5.9.0
 124       *
 125       * @param string $stylesheet Global styles stylesheet.
 126       * @return string Sanitized global styles stylesheet.
 127       */
 128  	public function _sanitize_global_styles_callback( $stylesheet ) {
 129          return urldecode( $stylesheet );
 130      }
 131  
 132      /**
 133       * Get the post, if the ID is valid.
 134       *
 135       * @since 5.9.0
 136       *
 137       * @param int $id Supplied ID.
 138       * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
 139       */
 140  	protected function get_post( $id ) {
 141          $error = new WP_Error(
 142              'rest_global_styles_not_found',
 143              __( 'No global styles config exists with that ID.' ),
 144              array( 'status' => 404 )
 145          );
 146  
 147          $id = (int) $id;
 148          if ( $id <= 0 ) {
 149              return $error;
 150          }
 151  
 152          $post = get_post( $id );
 153          if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
 154              return $error;
 155          }
 156  
 157          return $post;
 158      }
 159  
 160      /**
 161       * Checks if a given request has access to read a single global style.
 162       *
 163       * @since 5.9.0
 164       *
 165       * @param WP_REST_Request $request Full details about the request.
 166       * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
 167       */
 168  	public function get_item_permissions_check( $request ) {
 169          $post = $this->get_post( $request['id'] );
 170          if ( is_wp_error( $post ) ) {
 171              return $post;
 172          }
 173  
 174          if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
 175              return new WP_Error(
 176                  'rest_forbidden_context',
 177                  __( 'Sorry, you are not allowed to edit this global style.' ),
 178                  array( 'status' => rest_authorization_required_code() )
 179              );
 180          }
 181  
 182          if ( ! $this->check_read_permission( $post ) ) {
 183              return new WP_Error(
 184                  'rest_cannot_view',
 185                  __( 'Sorry, you are not allowed to view this global style.' ),
 186                  array( 'status' => rest_authorization_required_code() )
 187              );
 188          }
 189  
 190          return true;
 191      }
 192  
 193      /**
 194       * Checks if a global style can be read.
 195       *
 196       * @since 5.9.0
 197       *
 198       * @param WP_Post $post Post object.
 199       * @return bool Whether the post can be read.
 200       */
 201  	public function check_read_permission( $post ) {
 202          return current_user_can( 'read_post', $post->ID );
 203      }
 204  
 205      /**
 206       * Checks if a given request has access to write a single global styles config.
 207       *
 208       * @since 5.9.0
 209       *
 210       * @param WP_REST_Request $request Full details about the request.
 211       * @return true|WP_Error True if the request has write access for the item, WP_Error object otherwise.
 212       */
 213  	public function update_item_permissions_check( $request ) {
 214          $post = $this->get_post( $request['id'] );
 215          if ( is_wp_error( $post ) ) {
 216              return $post;
 217          }
 218  
 219          if ( $post && ! $this->check_update_permission( $post ) ) {
 220              return new WP_Error(
 221                  'rest_cannot_edit',
 222                  __( 'Sorry, you are not allowed to edit this global style.' ),
 223                  array( 'status' => rest_authorization_required_code() )
 224              );
 225          }
 226  
 227          return true;
 228      }
 229  
 230      /**
 231       * Prepares a single global styles config for update.
 232       *
 233       * @since 5.9.0
 234       * @since 6.2.0 Added validation of styles.css property.
 235       * @since 6.6.0 Added registration of block style variations from theme.json sources (theme.json, user theme.json, partials).
 236       *
 237       * @param WP_REST_Request $request Request object.
 238       * @return stdClass|WP_Error Prepared item on success. WP_Error on when the custom CSS is not valid.
 239       */
 240  	protected function prepare_item_for_database( $request ) {
 241          $changes     = new stdClass();
 242          $changes->ID = $request['id'];
 243  
 244          $post            = get_post( $request['id'] );
 245          $existing_config = array();
 246          if ( $post ) {
 247              $existing_config     = json_decode( $post->post_content, true );
 248              $json_decoding_error = json_last_error();
 249              if ( JSON_ERROR_NONE !== $json_decoding_error || ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) ||
 250                  ! $existing_config['isGlobalStylesUserThemeJSON'] ) {
 251                  $existing_config = array();
 252              }
 253          }
 254  
 255          if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) {
 256              $config = array();
 257              if ( isset( $request['styles'] ) ) {
 258                  if ( isset( $request['styles']['css'] ) ) {
 259                      $css_validation_result = $this->validate_custom_css( $request['styles']['css'] );
 260                      if ( is_wp_error( $css_validation_result ) ) {
 261                          return $css_validation_result;
 262                      }
 263                  }
 264                  $config['styles'] = $request['styles'];
 265              } elseif ( isset( $existing_config['styles'] ) ) {
 266                  $config['styles'] = $existing_config['styles'];
 267              }
 268  
 269              // Register theme-defined variations e.g. from block style variation partials under `/styles`.
 270              $variations = WP_Theme_JSON_Resolver::get_style_variations( 'block' );
 271              wp_register_block_style_variations_from_theme_json_partials( $variations );
 272  
 273              if ( isset( $request['settings'] ) ) {
 274                  $config['settings'] = $request['settings'];
 275              } elseif ( isset( $existing_config['settings'] ) ) {
 276                  $config['settings'] = $existing_config['settings'];
 277              }
 278              $config['isGlobalStylesUserThemeJSON'] = true;
 279              $config['version']                     = WP_Theme_JSON::LATEST_SCHEMA;
 280              /**
 281               * JSON encode the data stored in post content.
 282               * Escape characters that are likely to be mangled by HTML filters: "<>&".
 283               *
 284               * This data is later re-encoded by {@see wp_filter_global_styles_post()}.
 285               * The escaping is also applied here as a precaution.
 286               */
 287              $changes->post_content = wp_json_encode( $config, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
 288          }
 289  
 290          // Post title.
 291          if ( isset( $request['title'] ) ) {
 292              if ( is_string( $request['title'] ) ) {
 293                  $changes->post_title = $request['title'];
 294              } elseif ( ! empty( $request['title']['raw'] ) ) {
 295                  $changes->post_title = $request['title']['raw'];
 296              }
 297          }
 298  
 299          return $changes;
 300      }
 301  
 302      /**
 303       * Prepare a global styles config output for response.
 304       *
 305       * @since 5.9.0
 306       * @since 6.6.0 Added custom relative theme file URIs to `_links`.
 307       *
 308       * @param WP_Post         $post    Global Styles post object.
 309       * @param WP_REST_Request $request Request object.
 310       * @return WP_REST_Response Response object.
 311       */
 312  	public function prepare_item_for_response( $post, $request ) {
 313          $raw_config                       = json_decode( $post->post_content, true );
 314          $is_global_styles_user_theme_json = isset( $raw_config['isGlobalStylesUserThemeJSON'] ) && true === $raw_config['isGlobalStylesUserThemeJSON'];
 315          $config                           = array();
 316          $theme_json                       = null;
 317          if ( $is_global_styles_user_theme_json ) {
 318              $theme_json = new WP_Theme_JSON( $raw_config, 'custom' );
 319              $config     = $theme_json->get_raw_data();
 320          }
 321  
 322          // Base fields for every post.
 323          $fields = $this->get_fields_for_response( $request );
 324          $data   = array();
 325  
 326          if ( rest_is_field_included( 'id', $fields ) ) {
 327              $data['id'] = $post->ID;
 328          }
 329  
 330          if ( rest_is_field_included( 'title', $fields ) ) {
 331              $data['title'] = array();
 332          }
 333          if ( rest_is_field_included( 'title.raw', $fields ) ) {
 334              $data['title']['raw'] = $post->post_title;
 335          }
 336          if ( rest_is_field_included( 'title.rendered', $fields ) ) {
 337              add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
 338              add_filter( 'private_title_format', array( $this, 'protected_title_format' ) );
 339  
 340              $data['title']['rendered'] = get_the_title( $post->ID );
 341  
 342              remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
 343              remove_filter( 'private_title_format', array( $this, 'protected_title_format' ) );
 344          }
 345  
 346          if ( rest_is_field_included( 'settings', $fields ) ) {
 347              $data['settings'] = ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass();
 348          }
 349  
 350          if ( rest_is_field_included( 'styles', $fields ) ) {
 351              $data['styles'] = ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass();
 352          }
 353  
 354          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
 355          $data    = $this->add_additional_fields_to_object( $data, $request );
 356          $data    = $this->filter_response_by_context( $data, $context );
 357  
 358          // Wrap the data in a response object.
 359          $response = rest_ensure_response( $data );
 360  
 361          if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
 362              $links = $this->prepare_links( $post->ID );
 363  
 364              // Only return resolved URIs for get requests to user theme JSON.
 365              if ( $theme_json ) {
 366                  $resolved_theme_uris = WP_Theme_JSON_Resolver::get_resolved_theme_uris( $theme_json );
 367                  if ( ! empty( $resolved_theme_uris ) ) {
 368                      $links['https://api.w.org/theme-file'] = $resolved_theme_uris;
 369                  }
 370              }
 371  
 372              $response->add_links( $links );
 373              if ( ! empty( $links['self']['href'] ) ) {
 374                  $actions = $this->get_available_actions( $post, $request );
 375                  $self    = $links['self']['href'];
 376                  foreach ( $actions as $rel ) {
 377                      $response->add_link( $rel, $self );
 378                  }
 379              }
 380          }
 381  
 382          return $response;
 383      }
 384  
 385      /**
 386       * Prepares links for the request.
 387       *
 388       * @since 5.9.0
 389       * @since 6.3.0 Adds revisions count and rest URL href to version-history.
 390       *
 391       * @param int $id ID.
 392       * @return array Links for the given post.
 393       */
 394  	protected function prepare_links( $id ) {
 395          $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
 396  
 397          $links = array(
 398              'self'  => array(
 399                  'href' => rest_url( trailingslashit( $base ) . $id ),
 400              ),
 401              'about' => array(
 402                  'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
 403              ),
 404          );
 405  
 406          if ( post_type_supports( $this->post_type, 'revisions' ) ) {
 407              $revisions                = wp_get_latest_revision_id_and_total_count( $id );
 408              $revisions_count          = ! is_wp_error( $revisions ) ? $revisions['count'] : 0;
 409              $revisions_base           = sprintf( '/%s/%d/revisions', $base, $id );
 410              $links['version-history'] = array(
 411                  'href'  => rest_url( $revisions_base ),
 412                  'count' => $revisions_count,
 413              );
 414          }
 415  
 416          return $links;
 417      }
 418  
 419      /**
 420       * Get the link relations available for the post and current user.
 421       *
 422       * @since 5.9.0
 423       * @since 6.2.0 Added 'edit-css' action.
 424       * @since 6.6.0 Added $post and $request parameters.
 425       *
 426       * @param WP_Post         $post    Post object.
 427       * @param WP_REST_Request $request Request object.
 428       * @return array List of link relations.
 429       */
 430  	protected function get_available_actions( $post, $request ) {
 431          $rels = array();
 432  
 433          $post_type = get_post_type_object( $post->post_type );
 434          if ( current_user_can( $post_type->cap->publish_posts ) ) {
 435              $rels[] = 'https://api.w.org/action-publish';
 436          }
 437  
 438          if ( current_user_can( 'edit_css' ) ) {
 439              $rels[] = 'https://api.w.org/action-edit-css';
 440          }
 441  
 442          return $rels;
 443      }
 444  
 445      /**
 446       * Retrieves the query params for the global styles collection.
 447       *
 448       * @since 5.9.0
 449       *
 450       * @return array Collection parameters.
 451       */
 452  	public function get_collection_params() {
 453          return array();
 454      }
 455  
 456      /**
 457       * Retrieves the global styles type' schema, conforming to JSON Schema.
 458       *
 459       * @since 5.9.0
 460       *
 461       * @return array Item schema data.
 462       */
 463  	public function get_item_schema() {
 464          if ( $this->schema ) {
 465              return $this->add_additional_fields_schema( $this->schema );
 466          }
 467  
 468          $schema = array(
 469              '$schema'    => 'http://json-schema.org/draft-04/schema#',
 470              'title'      => $this->post_type,
 471              'type'       => 'object',
 472              'properties' => array(
 473                  'id'       => array(
 474                      'description' => __( 'ID of global styles config.' ),
 475                      'type'        => 'integer',
 476                      'context'     => array( 'embed', 'view', 'edit' ),
 477                      'readonly'    => true,
 478                  ),
 479                  'styles'   => array(
 480                      'description' => __( 'Global styles.' ),
 481                      'type'        => array( 'object' ),
 482                      'context'     => array( 'view', 'edit' ),
 483                  ),
 484                  'settings' => array(
 485                      'description' => __( 'Global settings.' ),
 486                      'type'        => array( 'object' ),
 487                      'context'     => array( 'view', 'edit' ),
 488                  ),
 489                  'title'    => array(
 490                      'description' => __( 'Title of the global styles variation.' ),
 491                      'type'        => array( 'object', 'string' ),
 492                      'default'     => '',
 493                      'context'     => array( 'embed', 'view', 'edit' ),
 494                      'properties'  => array(
 495                          'raw'      => array(
 496                              'description' => __( 'Title for the global styles variation, as it exists in the database.' ),
 497                              'type'        => 'string',
 498                              'context'     => array( 'view', 'edit', 'embed' ),
 499                          ),
 500                          'rendered' => array(
 501                              'description' => __( 'HTML title for the post, transformed for display.' ),
 502                              'type'        => 'string',
 503                              'context'     => array( 'view', 'edit', 'embed' ),
 504                              'readonly'    => true,
 505                          ),
 506                      ),
 507                  ),
 508              ),
 509          );
 510  
 511          $this->schema = $schema;
 512  
 513          return $this->add_additional_fields_schema( $this->schema );
 514      }
 515  
 516      /**
 517       * Checks if a given request has access to read a single theme global styles config.
 518       *
 519       * @since 5.9.0
 520       * @since 6.7.0 Allow users with edit post capabilities to view theme global styles.
 521       *
 522       * @param WP_REST_Request $request Full details about the request.
 523       * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
 524       */
 525  	public function get_theme_item_permissions_check( $request ) {
 526          /*
 527           * Verify if the current user has edit_posts capability.
 528           * This capability is required to view global styles.
 529           */
 530          if ( current_user_can( 'edit_posts' ) ) {
 531              return true;
 532          }
 533  
 534          foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
 535              if ( current_user_can( $post_type->cap->edit_posts ) ) {
 536                  return true;
 537              }
 538          }
 539  
 540          /*
 541           * Verify if the current user has edit_theme_options capability.
 542           */
 543          if ( current_user_can( 'edit_theme_options' ) ) {
 544              return true;
 545          }
 546  
 547          return new WP_Error(
 548              'rest_cannot_read_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  
 556      /**
 557       * Returns the given theme global styles config.
 558       *
 559       * @since 5.9.0
 560       * @since 6.6.0 Added custom relative theme file URIs to `_links`.
 561       *
 562       * @param WP_REST_Request $request The request instance.
 563       * @return WP_REST_Response|WP_Error
 564       */
 565  	public function get_theme_item( $request ) {
 566          if ( get_stylesheet() !== $request['stylesheet'] ) {
 567              // This endpoint only supports the active theme for now.
 568              return new WP_Error(
 569                  'rest_theme_not_found',
 570                  __( 'Theme not found.' ),
 571                  array( 'status' => 404 )
 572              );
 573          }
 574  
 575          $theme  = WP_Theme_JSON_Resolver::get_merged_data( 'theme' );
 576          $fields = $this->get_fields_for_response( $request );
 577          $data   = array();
 578  
 579          if ( rest_is_field_included( 'settings', $fields ) ) {
 580              $data['settings'] = $theme->get_settings();
 581          }
 582  
 583          if ( rest_is_field_included( 'styles', $fields ) ) {
 584              $raw_data       = $theme->get_raw_data();
 585              $data['styles'] = $raw_data['styles'] ?? array();
 586          }
 587  
 588          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
 589          $data    = $this->add_additional_fields_to_object( $data, $request );
 590          $data    = $this->filter_response_by_context( $data, $context );
 591  
 592          $response = rest_ensure_response( $data );
 593  
 594          if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
 595              $links               = array(
 596                  'self' => array(
 597                      'href' => rest_url( sprintf( '%s/%s/themes/%s', $this->namespace, $this->rest_base, $request['stylesheet'] ) ),
 598                  ),
 599              );
 600              $resolved_theme_uris = WP_Theme_JSON_Resolver::get_resolved_theme_uris( $theme );
 601              if ( ! empty( $resolved_theme_uris ) ) {
 602                  $links['https://api.w.org/theme-file'] = $resolved_theme_uris;
 603              }
 604              $response->add_links( $links );
 605          }
 606  
 607          return $response;
 608      }
 609  
 610      /**
 611       * Checks if a given request has access to read a single theme global styles config.
 612       *
 613       * @since 6.0.0
 614       * @since 6.7.0 Allow users with edit post capabilities to view theme global styles.
 615       *
 616       * @param WP_REST_Request $request Full details about the request.
 617       * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
 618       */
 619  	public function get_theme_items_permissions_check( $request ) {
 620          return $this->get_theme_item_permissions_check( $request );
 621      }
 622  
 623      /**
 624       * Returns the given theme global styles variations.
 625       *
 626       * @since 6.0.0
 627       * @since 6.2.0 Returns parent theme variations, if they exist.
 628       * @since 6.6.0 Added custom relative theme file URIs to `_links` for each item.
 629       *
 630       * @param WP_REST_Request $request The request instance.
 631       * @return WP_REST_Response|WP_Error
 632       */
 633  	public function get_theme_items( $request ) {
 634          if ( get_stylesheet() !== $request['stylesheet'] ) {
 635              // This endpoint only supports the active theme for now.
 636              return new WP_Error(
 637                  'rest_theme_not_found',
 638                  __( 'Theme not found.' ),
 639                  array( 'status' => 404 )
 640              );
 641          }
 642  
 643          $response = array();
 644  
 645          // Register theme-defined variations e.g. from block style variation partials under `/styles`.
 646          $partials = WP_Theme_JSON_Resolver::get_style_variations( 'block' );
 647          wp_register_block_style_variations_from_theme_json_partials( $partials );
 648  
 649          $variations = WP_Theme_JSON_Resolver::get_style_variations();
 650          foreach ( $variations as $variation ) {
 651              $variation_theme_json = new WP_Theme_JSON( $variation );
 652              $resolved_theme_uris  = WP_Theme_JSON_Resolver::get_resolved_theme_uris( $variation_theme_json );
 653              $data                 = rest_ensure_response( $variation );
 654              if ( ! empty( $resolved_theme_uris ) ) {
 655                  $data->add_links(
 656                      array(
 657                          'https://api.w.org/theme-file' => $resolved_theme_uris,
 658                      )
 659                  );
 660              }
 661              $response[] = $this->prepare_response_for_collection( $data );
 662          }
 663  
 664          return rest_ensure_response( $response );
 665      }
 666  
 667      /**
 668       * Validate style.css as valid CSS.
 669       *
 670       * Currently just checks that CSS will not break an HTML STYLE tag.
 671       *
 672       * @since 6.2.0
 673       * @since 6.4.0 Changed method visibility to protected.
 674       * @since 7.0.0 Only restricts contents which risk prematurely closing the STYLE element,
 675       *              either through a STYLE end tag or a prefix of one which might become a
 676       *              full end tag when combined with the contents of other styles.
 677       * @since 7.1.0 Rejects non-string values with a WP_Error instead of a fatal error.
 678       *
 679       * @see WP_Customize_Custom_CSS_Setting::validate()
 680       *
 681       * @param mixed $css CSS to validate.
 682       * @return true|WP_Error True if the input was validated, otherwise WP_Error.
 683       */
 684  	protected function validate_custom_css( $css ) {
 685          if ( ! is_string( $css ) ) {
 686              return new WP_Error(
 687                  'rest_custom_css_invalid_type',
 688                  __( 'CSS must be a string.' ),
 689                  array( 'status' => 400 )
 690              );
 691          }
 692  
 693          $length = strlen( $css );
 694          for (
 695              $at = strcspn( $css, '<' );
 696              $at < $length;
 697              $at += strcspn( $css, '<', ++$at )
 698          ) {
 699              $remaining_strlen = $length - $at;
 700              /**
 701               * Custom CSS text is expected to render inside an HTML STYLE element.
 702               * A STYLE closing tag must not appear within the CSS text because it
 703               * would close the element prematurely.
 704               *
 705               * The text must also *not* end with a partial closing tag (e.g., `<`,
 706               * `</`, … `</style`) because subsequent styles which are concatenated
 707               * could complete it, forming a valid `</style>` tag.
 708               *
 709               * Example:
 710               *
 711               *     $style_a = 'p { font-weight: bold; </sty';
 712               *     $style_b = 'le> gotcha!';
 713               *     $combined = "{$style_a}{$style_b}";
 714               *
 715               *     $style_a = 'p { font-weight: bold; </style';
 716               *     $style_b = 'p > b { color: red; }';
 717               *     $combined = "{$style_a}\n{$style_b}";
 718               *
 719               * Note how in the second example, both of the style contents are benign
 720               * when analyzed on their own. The first style was likely the result of
 721               * improper truncation, while the second is perfectly sound. It was only
 722               * through concatenation that these two styles combined to form content
 723               * that would have broken out of the containing STYLE element, thus
 724               * corrupting the page and potentially introducing security issues.
 725               *
 726               * @link https://html.spec.whatwg.org/multipage/parsing.html#rawtext-end-tag-name-state
 727               */
 728              $possible_style_close_tag = 0 === substr_compare(
 729                  $css,
 730                  '</style',
 731                  $at,
 732                  min( 7, $remaining_strlen ),
 733                  true
 734              );
 735              if ( $possible_style_close_tag ) {
 736                  if ( $remaining_strlen < 8 ) {
 737                      return new WP_Error(
 738                          'rest_custom_css_illegal_markup',
 739                          sprintf(
 740                              /* translators: %s is the CSS that was provided. */
 741                              __( 'The CSS must not end in "%s".' ),
 742                              esc_html( substr( $css, $at ) )
 743                          ),
 744                          array( 'status' => 400 )
 745                      );
 746                  }
 747  
 748                  if ( 1 === strspn( $css, " \t\f\r\n/>", $at + 7, 1 ) ) {
 749                      return new WP_Error(
 750                          'rest_custom_css_illegal_markup',
 751                          sprintf(
 752                              /* translators: %s is the CSS that was provided. */
 753                              __( 'The CSS must not contain "%s".' ),
 754                              esc_html( substr( $css, $at, 8 ) )
 755                          ),
 756                          array( 'status' => 400 )
 757                      );
 758                  }
 759              }
 760          }
 761  
 762          return true;
 763      }
 764  }


Generated : Sun Oct 11 08:20:32 2026 Cross-referenced by PHPXref