[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * REST API: WP_REST_Themes_Controller class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 5.0.0
   8   */
   9  
  10  /**
  11   * Core class used to manage themes via the REST API.
  12   *
  13   * @since 5.0.0
  14   *
  15   * @see WP_REST_Controller
  16   */
  17  class WP_REST_Themes_Controller extends WP_REST_Controller {
  18  
  19      /**
  20       * Constructor.
  21       *
  22       * @since 5.0.0
  23       */
  24  	public function __construct() {
  25          $this->namespace = 'wp/v2';
  26          $this->rest_base = 'themes';
  27      }
  28  
  29      /**
  30       * Registers the routes for themes.
  31       *
  32       * @since 5.0.0
  33       *
  34       * @see register_rest_route()
  35       */
  36  	public function register_routes() {
  37          register_rest_route(
  38              $this->namespace,
  39              '/' . $this->rest_base,
  40              array(
  41                  array(
  42                      'methods'             => WP_REST_Server::READABLE,
  43                      'callback'            => array( $this, 'get_items' ),
  44                      'permission_callback' => array( $this, 'get_items_permissions_check' ),
  45                      'args'                => $this->get_collection_params(),
  46                  ),
  47                  'schema' => array( $this, 'get_item_schema' ),
  48              )
  49          );
  50  
  51          register_rest_route(
  52              $this->namespace,
  53              '/' . $this->rest_base . '/(?P<stylesheet>[\w-]+)',
  54              array(
  55                  'args'   => array(
  56                      'stylesheet' => array(
  57                          'description' => __( "The theme's stylesheet. This uniquely identifies the theme." ),
  58                          'type'        => 'string',
  59                      ),
  60                  ),
  61                  array(
  62                      'methods'             => WP_REST_Server::READABLE,
  63                      'callback'            => array( $this, 'get_item' ),
  64                      'permission_callback' => array( $this, 'get_item_permissions_check' ),
  65                  ),
  66                  'schema' => array( $this, 'get_public_item_schema' ),
  67              )
  68          );
  69      }
  70  
  71      /**
  72       * Checks if a given request has access to read the theme.
  73       *
  74       * @since 5.0.0
  75       *
  76       * @param WP_REST_Request $request Full details about the request.
  77       * @return true|WP_Error True if the request has read access for the item, otherwise WP_Error object.
  78       */
  79  	public function get_items_permissions_check( $request ) {
  80          if ( current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ) ) {
  81              return true;
  82          }
  83  
  84          $registered = $this->get_collection_params();
  85          if ( isset( $registered['status'], $request['status'] ) && is_array( $request['status'] ) && array( 'active' ) === $request['status'] ) {
  86              return $this->check_read_active_theme_permission();
  87          }
  88  
  89          return new WP_Error(
  90              'rest_cannot_view_themes',
  91              __( 'Sorry, you are not allowed to view themes.' ),
  92              array( 'status' => rest_authorization_required_code() )
  93          );
  94      }
  95  
  96      /**
  97       * Checks if a given request has access to read the theme.
  98       *
  99       * @since 5.7.0
 100       *
 101       * @param WP_REST_Request $request Full details about the request.
 102       * @return bool|WP_Error True if the request has read access for the item, otherwise WP_Error object.
 103       */
 104  	public function get_item_permissions_check( $request ) {
 105          if ( current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ) ) {
 106              return true;
 107          }
 108  
 109          $wp_theme      = wp_get_theme( $request['stylesheet'] );
 110          $current_theme = wp_get_theme();
 111  
 112          if ( $this->is_same_theme( $wp_theme, $current_theme ) ) {
 113              return $this->check_read_active_theme_permission();
 114          }
 115  
 116          return new WP_Error(
 117              'rest_cannot_view_themes',
 118              __( 'Sorry, you are not allowed to view themes.' ),
 119              array( 'status' => rest_authorization_required_code() )
 120          );
 121      }
 122  
 123      /**
 124       * Checks if a theme can be read.
 125       *
 126       * @since 5.7.0
 127       *
 128       * @return bool|WP_Error Whether the theme can be read.
 129       */
 130  	protected function check_read_active_theme_permission() {
 131          if ( current_user_can( 'edit_posts' ) ) {
 132              return true;
 133          }
 134  
 135          foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
 136              if ( current_user_can( $post_type->cap->edit_posts ) ) {
 137                  return true;
 138              }
 139          }
 140  
 141          return new WP_Error(
 142              'rest_cannot_view_active_theme',
 143              __( 'Sorry, you are not allowed to view the active theme.' ),
 144              array( 'status' => rest_authorization_required_code() )
 145          );
 146      }
 147  
 148      /**
 149       * Retrieves a single theme.
 150       *
 151       * @since 5.7.0
 152       *
 153       * @param WP_REST_Request $request Full details about the request.
 154       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 155       */
 156  	public function get_item( $request ) {
 157          $wp_theme = wp_get_theme( $request['stylesheet'] );
 158          if ( ! $wp_theme->exists() ) {
 159              return new WP_Error(
 160                  'rest_theme_not_found',
 161                  __( 'Theme not found.' ),
 162                  array( 'status' => 404 )
 163              );
 164          }
 165          $data = $this->prepare_item_for_response( $wp_theme, $request );
 166  
 167          return rest_ensure_response( $data );
 168      }
 169  
 170      /**
 171       * Retrieves a collection of themes.
 172       *
 173       * @since 5.0.0
 174       *
 175       * @param WP_REST_Request $request Full details about the request.
 176       * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
 177       */
 178  	public function get_items( $request ) {
 179          $themes = array();
 180  
 181          $active_themes = wp_get_themes();
 182          $current_theme = wp_get_theme();
 183          $status        = $request['status'];
 184  
 185          foreach ( $active_themes as $theme_name => $theme ) {
 186              $theme_status = ( $this->is_same_theme( $theme, $current_theme ) ) ? 'active' : 'inactive';
 187              if ( is_array( $status ) && ! in_array( $theme_status, $status, true ) ) {
 188                  continue;
 189              }
 190  
 191              $prepared = $this->prepare_item_for_response( $theme, $request );
 192              $themes[] = $this->prepare_response_for_collection( $prepared );
 193          }
 194  
 195          $response = rest_ensure_response( $themes );
 196  
 197          $response->header( 'X-WP-Total', count( $themes ) );
 198          $response->header( 'X-WP-TotalPages', 1 );
 199  
 200          return $response;
 201      }
 202  
 203      /**
 204       * Prepares a single theme output for response.
 205       *
 206       * @since 5.0.0
 207       * @since 5.9.0 Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support.
 208       *
 209       * @param WP_Theme        $item    Theme object.
 210       * @param WP_REST_Request $request Request object.
 211       * @return WP_REST_Response Response object.
 212       */
 213  	public function prepare_item_for_response( $item, $request ) {
 214          // Restores the more descriptive, specific name for use within this method.
 215          $theme  = $item;
 216          $data   = array();
 217          $fields = $this->get_fields_for_response( $request );
 218  
 219          if ( rest_is_field_included( 'stylesheet', $fields ) ) {
 220              $data['stylesheet'] = $theme->get_stylesheet();
 221          }
 222  
 223          if ( rest_is_field_included( 'template', $fields ) ) {
 224              /**
 225               * Use the get_template() method, not the 'Template' header, for finding the template.
 226               * The 'Template' header is only good for what was written in the style.css, while
 227               * get_template() takes into account where WordPress actually located the theme and
 228               * whether it is actually valid.
 229               */
 230              $data['template'] = $theme->get_template();
 231          }
 232  
 233          $plain_field_mappings = array(
 234              'requires_php' => 'RequiresPHP',
 235              'requires_wp'  => 'RequiresWP',
 236              'textdomain'   => 'TextDomain',
 237              'version'      => 'Version',
 238          );
 239  
 240          foreach ( $plain_field_mappings as $field => $header ) {
 241              if ( rest_is_field_included( $field, $fields ) ) {
 242                  $data[ $field ] = $theme->get( $header );
 243              }
 244          }
 245  
 246          if ( rest_is_field_included( 'screenshot', $fields ) ) {
 247              // Using $theme->get_screenshot() with no args to get absolute URL.
 248              $data['screenshot'] = $theme->get_screenshot() ? $theme->get_screenshot() : '';
 249          }
 250  
 251          $rich_field_mappings = array(
 252              'author'      => 'Author',
 253              'author_uri'  => 'AuthorURI',
 254              'description' => 'Description',
 255              'name'        => 'Name',
 256              'tags'        => 'Tags',
 257              'theme_uri'   => 'ThemeURI',
 258          );
 259  
 260          foreach ( $rich_field_mappings as $field => $header ) {
 261              if ( rest_is_field_included( "{$field}.raw", $fields ) ) {
 262                  $data[ $field ]['raw'] = $theme->display( $header, false, true );
 263              }
 264  
 265              if ( rest_is_field_included( "{$field}.rendered", $fields ) ) {
 266                  $data[ $field ]['rendered'] = $theme->display( $header );
 267              }
 268          }
 269  
 270          $current_theme = wp_get_theme();
 271          if ( rest_is_field_included( 'status', $fields ) ) {
 272              $data['status'] = ( $this->is_same_theme( $theme, $current_theme ) ) ? 'active' : 'inactive';
 273          }
 274  
 275          if ( rest_is_field_included( 'theme_supports', $fields ) && $this->is_same_theme( $theme, $current_theme ) ) {
 276              foreach ( get_registered_theme_features() as $feature => $config ) {
 277                  if ( ! is_array( $config['show_in_rest'] ) ) {
 278                      continue;
 279                  }
 280  
 281                  $name = $config['show_in_rest']['name'];
 282  
 283                  if ( ! rest_is_field_included( "theme_supports.{$name}", $fields ) ) {
 284                      continue;
 285                  }
 286  
 287                  if ( ! current_theme_supports( $feature ) ) {
 288                      $data['theme_supports'][ $name ] = $config['show_in_rest']['schema']['default'];
 289                      continue;
 290                  }
 291  
 292                  $support = get_theme_support( $feature );
 293  
 294                  if ( isset( $config['show_in_rest']['prepare_callback'] ) ) {
 295                      $prepare = $config['show_in_rest']['prepare_callback'];
 296                  } else {
 297                      $prepare = array( $this, 'prepare_theme_support' );
 298                  }
 299  
 300                  $prepared = $prepare( $support, $config, $feature, $request );
 301  
 302                  if ( is_wp_error( $prepared ) ) {
 303                      continue;
 304                  }
 305  
 306                  $data['theme_supports'][ $name ] = $prepared;
 307              }
 308          }
 309  
 310          $data = $this->add_additional_fields_to_object( $data, $request );
 311  
 312          // Wrap the data in a response object.
 313          $response = rest_ensure_response( $data );
 314  
 315          $response->add_links( $this->prepare_links( $theme ) );
 316  
 317          /**
 318           * Filters theme data returned from the REST API.
 319           *
 320           * @since 5.0.0
 321           *
 322           * @param WP_REST_Response $response The response object.
 323           * @param WP_Theme         $theme    Theme object used to create response.
 324           * @param WP_REST_Request  $request  Request object.
 325           */
 326          return apply_filters( 'rest_prepare_theme', $response, $theme, $request );
 327      }
 328  
 329      /**
 330       * Prepares links for the request.
 331       *
 332       * @since 5.7.0
 333       *
 334       * @param WP_Theme $theme Theme data.
 335       * @return array Links for the given block type.
 336       */
 337  	protected function prepare_links( $theme ) {
 338          return array(
 339              'self'       => array(
 340                  'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $theme->get_stylesheet() ) ),
 341              ),
 342              'collection' => array(
 343                  'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
 344              ),
 345          );
 346      }
 347  
 348      /**
 349       * Helper function to compare two themes.
 350       *
 351       * @since 5.7.0
 352       *
 353       * @param WP_Theme $theme_a First theme to compare.
 354       * @param WP_Theme $theme_b Second theme to compare.
 355       * @return bool
 356       */
 357  	protected function is_same_theme( $theme_a, $theme_b ) {
 358          return $theme_a->get_stylesheet() === $theme_b->get_stylesheet();
 359      }
 360  
 361      /**
 362       * Prepares the theme support value for inclusion in the REST API response.
 363       *
 364       * @since 5.5.0
 365       *
 366       * @param mixed           $support The raw value from get_theme_support().
 367       * @param array           $args    The feature's registration args.
 368       * @param string          $feature The feature name.
 369       * @param WP_REST_Request $request The request object.
 370       * @return mixed The prepared support value.
 371       */
 372  	protected function prepare_theme_support( $support, $args, $feature, $request ) {
 373          $schema = $args['show_in_rest']['schema'];
 374  
 375          if ( 'boolean' === $schema['type'] ) {
 376              return true;
 377          }
 378  
 379          if ( is_array( $support ) && ! $args['variadic'] ) {
 380              $support = $support[0];
 381          }
 382  
 383          return rest_sanitize_value_from_schema( $support, $schema );
 384      }
 385  
 386      /**
 387       * Retrieves the theme's schema, conforming to JSON Schema.
 388       *
 389       * @since 5.0.0
 390       *
 391       * @return array Item schema data.
 392       */
 393  	public function get_item_schema() {
 394          if ( $this->schema ) {
 395              return $this->add_additional_fields_schema( $this->schema );
 396          }
 397  
 398          $schema = array(
 399              '$schema'    => 'http://json-schema.org/draft-04/schema#',
 400              'title'      => 'theme',
 401              'type'       => 'object',
 402              'properties' => array(
 403                  'stylesheet'     => array(
 404                      'description' => __( 'The theme\'s stylesheet. This uniquely identifies the theme.' ),
 405                      'type'        => 'string',
 406                      'readonly'    => true,
 407                  ),
 408                  'template'       => array(
 409                      'description' => __( 'The theme\'s template. If this is a child theme, this refers to the parent theme, otherwise this is the same as the theme\'s stylesheet.' ),
 410                      'type'        => 'string',
 411                      'readonly'    => true,
 412                  ),
 413                  'author'         => array(
 414                      'description' => __( 'The theme author.' ),
 415                      'type'        => 'object',
 416                      'readonly'    => true,
 417                      'properties'  => array(
 418                          'raw'      => array(
 419                              'description' => __( 'The theme author\'s name, as found in the theme header.' ),
 420                              'type'        => 'string',
 421                          ),
 422                          'rendered' => array(
 423                              'description' => __( 'HTML for the theme author, transformed for display.' ),
 424                              'type'        => 'string',
 425                          ),
 426                      ),
 427                  ),
 428                  'author_uri'     => array(
 429                      'description' => __( 'The website of the theme author.' ),
 430                      'type'        => 'object',
 431                      'readonly'    => true,
 432                      'properties'  => array(
 433                          'raw'      => array(
 434                              'description' => __( 'The website of the theme author, as found in the theme header.' ),
 435                              'type'        => 'string',
 436                              'format'      => 'uri',
 437                          ),
 438                          'rendered' => array(
 439                              'description' => __( 'The website of the theme author, transformed for display.' ),
 440                              'type'        => 'string',
 441                              'format'      => 'uri',
 442                          ),
 443                      ),
 444                  ),
 445                  'description'    => array(
 446                      'description' => __( 'A description of the theme.' ),
 447                      'type'        => 'object',
 448                      'readonly'    => true,
 449                      'properties'  => array(
 450                          'raw'      => array(
 451                              'description' => __( 'The theme description, as found in the theme header.' ),
 452                              'type'        => 'string',
 453                          ),
 454                          'rendered' => array(
 455                              'description' => __( 'The theme description, transformed for display.' ),
 456                              'type'        => 'string',
 457                          ),
 458                      ),
 459                  ),
 460                  'name'           => array(
 461                      'description' => __( 'The name of the theme.' ),
 462                      'type'        => 'object',
 463                      'readonly'    => true,
 464                      'properties'  => array(
 465                          'raw'      => array(
 466                              'description' => __( 'The theme name, as found in the theme header.' ),
 467                              'type'        => 'string',
 468                          ),
 469                          'rendered' => array(
 470                              'description' => __( 'The theme name, transformed for display.' ),
 471                              'type'        => 'string',
 472                          ),
 473                      ),
 474                  ),
 475                  'requires_php'   => array(
 476                      'description' => __( 'The minimum PHP version required for the theme to work.' ),
 477                      'type'        => 'string',
 478                      'readonly'    => true,
 479                  ),
 480                  'requires_wp'    => array(
 481                      'description' => __( 'The minimum WordPress version required for the theme to work.' ),
 482                      'type'        => 'string',
 483                      'readonly'    => true,
 484                  ),
 485                  'screenshot'     => array(
 486                      'description' => __( 'The theme\'s screenshot URL.' ),
 487                      'type'        => 'string',
 488                      'format'      => 'uri',
 489                      'readonly'    => true,
 490                  ),
 491                  'tags'           => array(
 492                      'description' => __( 'Tags indicating styles and features of the theme.' ),
 493                      'type'        => 'object',
 494                      'readonly'    => true,
 495                      'properties'  => array(
 496                          'raw'      => array(
 497                              'description' => __( 'The theme tags, as found in the theme header.' ),
 498                              'type'        => 'array',
 499                              'items'       => array(
 500                                  'type' => 'string',
 501                              ),
 502                          ),
 503                          'rendered' => array(
 504                              'description' => __( 'The theme tags, transformed for display.' ),
 505                              'type'        => 'string',
 506                          ),
 507                      ),
 508                  ),
 509                  'textdomain'     => array(
 510                      'description' => __( 'The theme\'s text domain.' ),
 511                      'type'        => 'string',
 512                      'readonly'    => true,
 513                  ),
 514                  'theme_supports' => array(
 515                      'description' => __( 'Features supported by this theme.' ),
 516                      'type'        => 'object',
 517                      'readonly'    => true,
 518                      'properties'  => array(),
 519                  ),
 520                  'theme_uri'      => array(
 521                      'description' => __( 'The URI of the theme\'s webpage.' ),
 522                      'type'        => 'object',
 523                      'readonly'    => true,
 524                      'properties'  => array(
 525                          'raw'      => array(
 526                              'description' => __( 'The URI of the theme\'s webpage, as found in the theme header.' ),
 527                              'type'        => 'string',
 528                              'format'      => 'uri',
 529                          ),
 530                          'rendered' => array(
 531                              'description' => __( 'The URI of the theme\'s webpage, transformed for display.' ),
 532                              'type'        => 'string',
 533                              'format'      => 'uri',
 534                          ),
 535                      ),
 536                  ),
 537                  'version'        => array(
 538                      'description' => __( 'The theme\'s current version.' ),
 539                      'type'        => 'string',
 540                      'readonly'    => true,
 541                  ),
 542                  'status'         => array(
 543                      'description' => __( 'A named status for the theme.' ),
 544                      'type'        => 'string',
 545                      'enum'        => array( 'inactive', 'active' ),
 546                  ),
 547              ),
 548          );
 549  
 550          foreach ( get_registered_theme_features() as $feature => $config ) {
 551              if ( ! is_array( $config['show_in_rest'] ) ) {
 552                  continue;
 553              }
 554  
 555              $name = $config['show_in_rest']['name'];
 556  
 557              $schema['properties']['theme_supports']['properties'][ $name ] = $config['show_in_rest']['schema'];
 558          }
 559  
 560          $this->schema = $schema;
 561  
 562          return $this->add_additional_fields_schema( $this->schema );
 563      }
 564  
 565      /**
 566       * Retrieves the search params for the themes collection.
 567       *
 568       * @since 5.0.0
 569       *
 570       * @return array Collection parameters.
 571       */
 572  	public function get_collection_params() {
 573          $query_params = array(
 574              'status' => array(
 575                  'description' => __( 'Limit result set to themes assigned one or more statuses.' ),
 576                  'type'        => 'array',
 577                  'items'       => array(
 578                      'enum' => array( 'active', 'inactive' ),
 579                      'type' => 'string',
 580                  ),
 581              ),
 582          );
 583  
 584          /**
 585           * Filters REST API collection parameters for the themes controller.
 586           *
 587           * @since 5.0.0
 588           *
 589           * @param array $query_params JSON Schema-formatted collection parameters.
 590           */
 591          return apply_filters( 'rest_themes_collection_params', $query_params );
 592      }
 593  
 594      /**
 595       * Sanitizes and validates the list of theme status.
 596       *
 597       * @since 5.0.0
 598       * @deprecated 5.7.0
 599       *
 600       * @param string|array    $statuses  One or more theme statuses.
 601       * @param WP_REST_Request $request   Full details about the request.
 602       * @param string          $parameter Additional parameter to pass to validation.
 603       * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
 604       */
 605  	public function sanitize_theme_status( $statuses, $request, $parameter ) {
 606          _deprecated_function( __METHOD__, '5.7.0' );
 607  
 608          $statuses = wp_parse_slug_list( $statuses );
 609  
 610          foreach ( $statuses as $status ) {
 611              $result = rest_validate_request_arg( $status, $request, $parameter );
 612  
 613              if ( is_wp_error( $result ) ) {
 614                  return $result;
 615              }
 616          }
 617  
 618          return $statuses;
 619      }
 620  }


Generated: Tue Oct 19 01:00:04 2021 Cross-referenced by PHPXref 0.7.1