| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * WordPress Customize Manager classes 4 * 5 * @package WordPress 6 * @subpackage Customize 7 * @since 3.4.0 8 */ 9 10 /** 11 * Customize Manager class. 12 * 13 * Bootstraps the Customize experience on the server-side. 14 * 15 * Sets up the theme-switching process if a theme other than the active one is 16 * being previewed and customized. 17 * 18 * Serves as a factory for Customize Controls and Settings, and 19 * instantiates default Customize Controls and Settings. 20 * 21 * @since 3.4.0 22 */ 23 #[AllowDynamicProperties] 24 final class WP_Customize_Manager { 25 /** 26 * An instance of the theme being previewed. 27 * 28 * @since 3.4.0 29 * @var WP_Theme 30 */ 31 protected $theme; 32 33 /** 34 * The directory name of the previously active theme (within the theme_root). 35 * 36 * @since 3.4.0 37 * @var string 38 */ 39 protected $original_stylesheet; 40 41 /** 42 * Whether this is a Customizer pageload. 43 * 44 * @since 3.4.0 45 * @var bool 46 */ 47 protected $previewing = false; 48 49 /** 50 * Methods and properties dealing with managing widgets in the Customizer. 51 * 52 * @since 3.9.0 53 * @var WP_Customize_Widgets 54 */ 55 public $widgets; 56 57 /** 58 * Methods and properties dealing with managing nav menus in the Customizer. 59 * 60 * @since 4.3.0 61 * @var WP_Customize_Nav_Menus 62 */ 63 public $nav_menus; 64 65 /** 66 * Methods and properties dealing with selective refresh in the Customizer preview. 67 * 68 * @since 4.5.0 69 * @var WP_Customize_Selective_Refresh 70 */ 71 public $selective_refresh; 72 73 /** 74 * Registered instances of WP_Customize_Setting. 75 * 76 * @since 3.4.0 77 * @var array 78 */ 79 protected $settings = array(); 80 81 /** 82 * Sorted top-level instances of WP_Customize_Panel and WP_Customize_Section. 83 * 84 * @since 4.0.0 85 * @var array 86 */ 87 protected $containers = array(); 88 89 /** 90 * Registered instances of WP_Customize_Panel. 91 * 92 * @since 4.0.0 93 * @var array 94 */ 95 protected $panels = array(); 96 97 /** 98 * List of core components. 99 * 100 * @since 4.5.0 101 * @var array 102 */ 103 protected $components = array( 'nav_menus' ); 104 105 /** 106 * Registered instances of WP_Customize_Section. 107 * 108 * @since 3.4.0 109 * @var array 110 */ 111 protected $sections = array(); 112 113 /** 114 * Registered instances of WP_Customize_Control. 115 * 116 * @since 3.4.0 117 * @var array 118 */ 119 protected $controls = array(); 120 121 /** 122 * Panel types that may be rendered from JS templates. 123 * 124 * @since 4.3.0 125 * @var array 126 */ 127 protected $registered_panel_types = array(); 128 129 /** 130 * Section types that may be rendered from JS templates. 131 * 132 * @since 4.3.0 133 * @var array 134 */ 135 protected $registered_section_types = array(); 136 137 /** 138 * Control types that may be rendered from JS templates. 139 * 140 * @since 4.1.0 141 * @var array 142 */ 143 protected $registered_control_types = array(); 144 145 /** 146 * Initial URL being previewed. 147 * 148 * @since 4.4.0 149 * @var string 150 */ 151 protected $preview_url; 152 153 /** 154 * URL to link the user to when closing the Customizer. 155 * 156 * @since 4.4.0 157 * @var string 158 */ 159 protected $return_url; 160 161 /** 162 * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. 163 * 164 * @since 4.4.0 165 * @var string[] 166 */ 167 protected $autofocus = array(); 168 169 /** 170 * Messenger channel. 171 * 172 * @since 4.7.0 173 * @var string 174 */ 175 protected $messenger_channel; 176 177 /** 178 * Whether the autosave revision of the changeset should be loaded. 179 * 180 * @since 4.9.0 181 * @var bool 182 */ 183 protected $autosaved = false; 184 185 /** 186 * Whether the changeset branching is allowed. 187 * 188 * @since 4.9.0 189 * @var bool 190 */ 191 protected $branching = true; 192 193 /** 194 * Whether settings should be previewed. 195 * 196 * @since 4.9.0 197 * @var bool 198 */ 199 protected $settings_previewed = true; 200 201 /** 202 * Whether a starter content changeset was saved. 203 * 204 * @since 4.9.0 205 * @var bool 206 */ 207 protected $saved_starter_content_changeset = false; 208 209 /** 210 * Unsanitized values for Customize Settings parsed from $_POST['customized']. 211 * 212 * @var array 213 */ 214 private $_post_values; 215 216 /** 217 * Changeset UUID. 218 * 219 * @since 4.7.0 220 * @var string 221 */ 222 private $_changeset_uuid; 223 224 /** 225 * Changeset post ID. 226 * 227 * @since 4.7.0 228 * @var int|false 229 */ 230 private $_changeset_post_id; 231 232 /** 233 * Changeset data loaded from a customize_changeset post. 234 * 235 * @since 4.7.0 236 * @var array|null 237 */ 238 private $_changeset_data; 239 240 /** 241 * Constructor. 242 * 243 * @since 3.4.0 244 * @since 4.7.0 Added `$args` parameter. 245 * 246 * @param array $args { 247 * Args. 248 * 249 * @type null|string|false $changeset_uuid Changeset UUID, the `post_name` for the customize_changeset post containing the customized state. 250 * Defaults to `null` resulting in a UUID to be immediately generated. If `false` is provided, then 251 * then the changeset UUID will be determined during `after_setup_theme`: when the 252 * `customize_changeset_branching` filter returns false, then the default UUID will be that 253 * of the most recent `customize_changeset` post that has a status other than 'auto-draft', 254 * 'publish', or 'trash'. Otherwise, if changeset branching is enabled, then a random UUID will be used. 255 * @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params. 256 * @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param. 257 * @type bool $settings_previewed If settings should be previewed. Defaults to true. 258 * @type bool $branching If changeset branching is allowed; otherwise, changesets are linear. Defaults to true. 259 * @type bool $autosaved If data from a changeset's autosaved revision should be loaded if it exists. Defaults to false. 260 * } 261 */ 262 public function __construct( $args = array() ) { 263 264 $args = array_merge( 265 array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed', 'autosaved', 'branching' ), null ), 266 $args 267 ); 268 269 // Note that the UUID format will be validated in the setup_theme() method. 270 if ( ! isset( $args['changeset_uuid'] ) ) { 271 $args['changeset_uuid'] = wp_generate_uuid4(); 272 } 273 274 /* 275 * The theme and messenger_channel should be supplied via $args, 276 * but they are also looked at in the $_REQUEST global here for back-compat. 277 */ 278 if ( ! isset( $args['theme'] ) ) { 279 if ( isset( $_REQUEST['customize_theme'] ) ) { 280 $args['theme'] = wp_unslash( $_REQUEST['customize_theme'] ); 281 } elseif ( isset( $_REQUEST['theme'] ) ) { // Deprecated. 282 $args['theme'] = wp_unslash( $_REQUEST['theme'] ); 283 } 284 } 285 if ( ! isset( $args['messenger_channel'] ) && isset( $_REQUEST['customize_messenger_channel'] ) ) { 286 $args['messenger_channel'] = sanitize_key( wp_unslash( $_REQUEST['customize_messenger_channel'] ) ); 287 } 288 289 // Do not load 'widgets' component if a block theme is activated. 290 if ( ! wp_is_block_theme() ) { 291 $this->components[] = 'widgets'; 292 } 293 294 $this->original_stylesheet = get_stylesheet(); 295 $this->theme = wp_get_theme( 0 === validate_file( $args['theme'] ) ? $args['theme'] : null ); 296 $this->messenger_channel = $args['messenger_channel']; 297 $this->_changeset_uuid = $args['changeset_uuid']; 298 299 foreach ( array( 'settings_previewed', 'autosaved', 'branching' ) as $key ) { 300 if ( isset( $args[ $key ] ) ) { 301 $this->$key = (bool) $args[ $key ]; 302 } 303 } 304 305 require_once ABSPATH . WPINC . '/class-wp-customize-setting.php'; 306 require_once ABSPATH . WPINC . '/class-wp-customize-panel.php'; 307 require_once ABSPATH . WPINC . '/class-wp-customize-section.php'; 308 require_once ABSPATH . WPINC . '/class-wp-customize-control.php'; 309 310 require_once ABSPATH . WPINC . '/customize/class-wp-customize-color-control.php'; 311 require_once ABSPATH . WPINC . '/customize/class-wp-customize-media-control.php'; 312 require_once ABSPATH . WPINC . '/customize/class-wp-customize-upload-control.php'; 313 require_once ABSPATH . WPINC . '/customize/class-wp-customize-image-control.php'; 314 require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-control.php'; 315 require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-position-control.php'; 316 require_once ABSPATH . WPINC . '/customize/class-wp-customize-cropped-image-control.php'; 317 require_once ABSPATH . WPINC . '/customize/class-wp-customize-site-icon-control.php'; 318 require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-control.php'; 319 require_once ABSPATH . WPINC . '/customize/class-wp-customize-theme-control.php'; 320 require_once ABSPATH . WPINC . '/customize/class-wp-customize-code-editor-control.php'; 321 require_once ABSPATH . WPINC . '/customize/class-wp-widget-area-customize-control.php'; 322 require_once ABSPATH . WPINC . '/customize/class-wp-widget-form-customize-control.php'; 323 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-control.php'; 324 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-control.php'; 325 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-location-control.php'; 326 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-name-control.php'; 327 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-locations-control.php'; 328 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-auto-add-control.php'; 329 330 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menus-panel.php'; 331 332 require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-panel.php'; 333 require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-section.php'; 334 require_once ABSPATH . WPINC . '/customize/class-wp-customize-sidebar-section.php'; 335 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-section.php'; 336 337 require_once ABSPATH . WPINC . '/customize/class-wp-customize-custom-css-setting.php'; 338 require_once ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php'; 339 require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php'; 340 require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php'; 341 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php'; 342 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php'; 343 344 /** 345 * Filters the core Customizer components to load. 346 * 347 * This allows Core components to be excluded from being instantiated by 348 * filtering them out of the array. Note that this filter generally runs 349 * during the {@see 'plugins_loaded'} action, so it cannot be added 350 * in a theme. 351 * 352 * @since 4.4.0 353 * 354 * @see WP_Customize_Manager::__construct() 355 * 356 * @param string[] $components Array of core components to load. 357 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 358 */ 359 $components = apply_filters( 'customize_loaded_components', $this->components, $this ); 360 361 require_once ABSPATH . WPINC . '/customize/class-wp-customize-selective-refresh.php'; 362 $this->selective_refresh = new WP_Customize_Selective_Refresh( $this ); 363 364 if ( in_array( 'widgets', $components, true ) ) { 365 require_once ABSPATH . WPINC . '/class-wp-customize-widgets.php'; 366 $this->widgets = new WP_Customize_Widgets( $this ); 367 } 368 369 if ( in_array( 'nav_menus', $components, true ) ) { 370 require_once ABSPATH . WPINC . '/class-wp-customize-nav-menus.php'; 371 $this->nav_menus = new WP_Customize_Nav_Menus( $this ); 372 } 373 374 add_action( 'setup_theme', array( $this, 'setup_theme' ) ); 375 add_action( 'wp_loaded', array( $this, 'wp_loaded' ) ); 376 377 // Do not spawn cron (especially the alternate cron) while running the Customizer. 378 remove_action( 'init', 'wp_cron' ); 379 380 // Do not run update checks when rendering the controls. 381 remove_action( 'admin_init', '_maybe_update_core' ); 382 remove_action( 'admin_init', '_maybe_update_plugins' ); 383 remove_action( 'admin_init', '_maybe_update_themes' ); 384 385 add_action( 'wp_ajax_customize_save', array( $this, 'save' ) ); 386 add_action( 'wp_ajax_customize_trash', array( $this, 'handle_changeset_trash_request' ) ); 387 add_action( 'wp_ajax_customize_refresh_nonces', array( $this, 'refresh_nonces' ) ); 388 add_action( 'wp_ajax_customize_load_themes', array( $this, 'handle_load_themes_request' ) ); 389 add_filter( 'heartbeat_settings', array( $this, 'add_customize_screen_to_heartbeat_settings' ) ); 390 add_filter( 'heartbeat_received', array( $this, 'check_changeset_lock_with_heartbeat' ), 10, 3 ); 391 add_action( 'wp_ajax_customize_override_changeset_lock', array( $this, 'handle_override_changeset_lock_request' ) ); 392 add_action( 'wp_ajax_customize_dismiss_autosave_or_lock', array( $this, 'handle_dismiss_autosave_or_lock_request' ) ); 393 394 add_action( 'customize_register', array( $this, 'register_controls' ) ); 395 add_action( 'customize_register', array( $this, 'register_dynamic_settings' ), 11 ); // Allow code to create settings first. 396 add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) ); 397 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) ); 398 399 // Render Common, Panel, Section, and Control templates. 400 add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_panel_templates' ), 1 ); 401 add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_section_templates' ), 1 ); 402 add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_control_templates' ), 1 ); 403 404 // Export header video settings with the partial response. 405 add_filter( 'customize_render_partials_response', array( $this, 'export_header_video_settings' ), 10, 3 ); 406 407 // Export the settings to JS via the _wpCustomizeSettings variable. 408 add_action( 'customize_controls_print_footer_scripts', array( $this, 'customize_pane_settings' ), 1000 ); 409 410 // Add theme update notices. 411 if ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) ) { 412 require_once ABSPATH . 'wp-admin/includes/update.php'; 413 add_action( 'customize_controls_print_footer_scripts', 'wp_print_admin_notice_templates' ); 414 } 415 } 416 417 /** 418 * Returns true if it's an Ajax request. 419 * 420 * @since 3.4.0 421 * @since 4.2.0 Added `$action` param. 422 * 423 * @param string|null $action Whether the supplied Ajax action is being run. 424 * @return bool True if it's an Ajax request, false otherwise. 425 */ 426 public function doing_ajax( $action = null ) { 427 if ( ! wp_doing_ajax() ) { 428 return false; 429 } 430 431 if ( ! $action ) { 432 return true; 433 } else { 434 /* 435 * Note: we can't just use doing_action( "wp_ajax_{$action}" ) because we need 436 * to check before admin-ajax.php gets to that point. 437 */ 438 return isset( $_REQUEST['action'] ) && wp_unslash( $_REQUEST['action'] ) === $action; 439 } 440 } 441 442 /** 443 * Custom wp_die wrapper. Returns either the standard message for UI 444 * or the Ajax message. 445 * 446 * @since 3.4.0 447 * 448 * @param string|WP_Error $ajax_message Ajax return. 449 * @param string $message Optional. UI message. 450 * @return never 451 */ 452 protected function wp_die( $ajax_message, $message = null ) { 453 if ( $this->doing_ajax() ) { 454 wp_die( $ajax_message ); 455 } 456 457 if ( ! $message ) { 458 $message = __( 'An error occurred while customizing. Please refresh the page and try again.' ); 459 } 460 461 if ( $this->messenger_channel ) { 462 ob_start(); 463 wp_enqueue_scripts(); 464 wp_print_scripts( array( 'customize-base' ) ); 465 466 $settings = array( 467 'messengerArgs' => array( 468 'channel' => $this->messenger_channel, 469 'url' => wp_customize_url(), 470 ), 471 'error' => $ajax_message, 472 ); 473 $message .= ob_get_clean(); 474 ob_start(); 475 ?> 476 <script> 477 ( function( api, settings ) { 478 var preview = new api.Messenger( settings.messengerArgs ); 479 preview.send( 'iframe-loading-error', settings.error ); 480 } )( wp.customize, <?php echo wp_json_encode( $settings, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); ?> ); 481 </script> 482 <?php 483 $message .= wp_get_inline_script_tag( wp_remove_surrounding_empty_script_tags( ob_get_clean() ) . "\n//# sourceURL=" . rawurlencode( __METHOD__ ) ); 484 } 485 486 wp_die( $message ); 487 } 488 489 /** 490 * Returns the Ajax wp_die() handler if it's a customized request. 491 * 492 * @since 3.4.0 493 * @deprecated 4.7.0 494 * 495 * @return callable Die handler. 496 */ 497 public function wp_die_handler() { 498 _deprecated_function( __METHOD__, '4.7.0' ); 499 500 if ( $this->doing_ajax() || isset( $_POST['customized'] ) ) { 501 return '_ajax_wp_die_handler'; 502 } 503 504 return '_default_wp_die_handler'; 505 } 506 507 /** 508 * Starts preview and customize theme. 509 * 510 * Check if customize query variable exist. Init filters to filter the active theme. 511 * 512 * @since 3.4.0 513 * 514 * @global string $pagenow The filename of the current screen. 515 */ 516 public function setup_theme() { 517 global $pagenow; 518 519 // Check permissions for customize.php access since this method is called before customize.php can run any code. 520 if ( 'customize.php' === $pagenow && ! current_user_can( 'customize' ) ) { 521 if ( ! is_user_logged_in() ) { 522 auth_redirect(); 523 } else { 524 wp_die( 525 '<h1>' . __( 'You need a higher level of permission.' ) . '</h1>' . 526 '<p>' . __( 'Sorry, you are not allowed to customize this site.' ) . '</p>', 527 403 528 ); 529 } 530 return; 531 } 532 533 // If a changeset was provided is invalid. 534 if ( isset( $this->_changeset_uuid ) && false !== $this->_changeset_uuid && ! wp_is_uuid( $this->_changeset_uuid ) ) { 535 $this->wp_die( -1, __( 'Invalid changeset UUID' ) ); 536 } 537 538 /* 539 * Clear incoming post data if the user lacks a CSRF token (nonce). Note that the customizer 540 * application will inject the customize_preview_nonce query parameter into all Ajax requests. 541 * For similar behavior elsewhere in WordPress, see rest_cookie_check_errors() which logs out 542 * a user when a valid nonce isn't present. 543 */ 544 $has_post_data_nonce = ( 545 check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce', false ) 546 || 547 check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce', false ) 548 || 549 check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'customize_preview_nonce', false ) 550 ); 551 if ( ! current_user_can( 'customize' ) || ! $has_post_data_nonce ) { 552 unset( $_POST['customized'] ); 553 unset( $_REQUEST['customized'] ); 554 } 555 556 /* 557 * If unauthenticated then require a valid changeset UUID to load the preview. 558 * In this way, the UUID serves as a secret key. If the messenger channel is present, 559 * then send unauthenticated code to prompt re-auth. 560 */ 561 if ( ! current_user_can( 'customize' ) && ! $this->changeset_post_id() ) { 562 $this->wp_die( $this->messenger_channel ? 0 : -1, __( 'Non-existent changeset UUID.' ) ); 563 } 564 565 if ( ! headers_sent() ) { 566 send_origin_headers(); 567 } 568 569 // Hide the admin bar if we're embedded in the customizer iframe. 570 if ( $this->messenger_channel ) { 571 show_admin_bar( false ); 572 } 573 574 if ( $this->is_theme_active() ) { 575 // Once the theme is loaded, we'll validate it. 576 add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) ); 577 } else { 578 /* 579 * If the requested theme is not the active theme and the user doesn't have 580 * the switch_themes cap, bail. 581 */ 582 if ( ! current_user_can( 'switch_themes' ) ) { 583 $this->wp_die( -1, __( 'Sorry, you are not allowed to edit theme options on this site.' ) ); 584 } 585 586 // If the theme has errors while loading, bail. 587 if ( $this->theme()->errors() ) { 588 $this->wp_die( -1, $this->theme()->errors()->get_error_message() ); 589 } 590 591 // If the theme isn't allowed per multisite settings, bail. 592 if ( ! $this->theme()->is_allowed() ) { 593 $this->wp_die( -1, __( 'The requested theme does not exist.' ) ); 594 } 595 } 596 597 // Make sure changeset UUID is established immediately after the theme is loaded. 598 add_action( 'after_setup_theme', array( $this, 'establish_loaded_changeset' ), 5 ); 599 600 /* 601 * Import theme starter content for fresh installations when landing in the customizer. 602 * Import starter content at after_setup_theme:100 so that any 603 * add_theme_support( 'starter-content' ) calls will have been made. 604 */ 605 if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) { 606 add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 ); 607 } 608 609 $this->start_previewing_theme(); 610 } 611 612 /** 613 * Establishes the loaded changeset. 614 * 615 * This method runs right at after_setup_theme and applies the 'customize_changeset_branching' filter to determine 616 * whether concurrent changesets are allowed. Then if the Customizer is not initialized with a `changeset_uuid` param, 617 * this method will determine which UUID should be used. If changeset branching is disabled, then the most saved 618 * changeset will be loaded by default. Otherwise, if there are no existing saved changesets or if changeset branching is 619 * enabled, then a new UUID will be generated. 620 * 621 * @since 4.9.0 622 * 623 * @global string $pagenow The filename of the current screen. 624 */ 625 public function establish_loaded_changeset() { 626 global $pagenow; 627 628 if ( empty( $this->_changeset_uuid ) ) { 629 $changeset_uuid = null; 630 631 if ( ! $this->branching() && $this->is_theme_active() ) { 632 $unpublished_changeset_posts = $this->get_changeset_posts( 633 array( 634 'post_status' => array_diff( get_post_stati(), array( 'auto-draft', 'publish', 'trash', 'inherit', 'private' ) ), 635 'exclude_restore_dismissed' => false, 636 'author' => 'any', 637 'posts_per_page' => 1, 638 'order' => 'DESC', 639 'orderby' => 'date', 640 ) 641 ); 642 $unpublished_changeset_post = array_shift( $unpublished_changeset_posts ); 643 if ( ! empty( $unpublished_changeset_post ) && wp_is_uuid( $unpublished_changeset_post->post_name ) ) { 644 $changeset_uuid = $unpublished_changeset_post->post_name; 645 } 646 } 647 648 // If no changeset UUID has been set yet, then generate a new one. 649 if ( empty( $changeset_uuid ) ) { 650 $changeset_uuid = wp_generate_uuid4(); 651 } 652 653 $this->_changeset_uuid = $changeset_uuid; 654 } 655 656 if ( is_admin() && 'customize.php' === $pagenow ) { 657 $this->set_changeset_lock( $this->changeset_post_id() ); 658 } 659 } 660 661 /** 662 * Callback to validate a theme once it is loaded 663 * 664 * @since 3.4.0 665 */ 666 public function after_setup_theme() { 667 $doing_ajax_or_is_customized = ( $this->doing_ajax() || isset( $_POST['customized'] ) ); 668 if ( ! $doing_ajax_or_is_customized && ! validate_current_theme() ) { 669 wp_redirect( 'themes.php?broken=true' ); 670 exit; 671 } 672 } 673 674 /** 675 * If the theme to be previewed isn't the active theme, add filter callbacks 676 * to swap it out at runtime. 677 * 678 * @since 3.4.0 679 */ 680 public function start_previewing_theme() { 681 // Bail if we're already previewing. 682 if ( $this->is_preview() ) { 683 return; 684 } 685 686 $this->previewing = true; 687 688 if ( ! $this->is_theme_active() ) { 689 add_filter( 'template', array( $this, 'get_template' ) ); 690 add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); 691 add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); 692 693 // @link: https://core.trac.wordpress.org/ticket/20027 694 add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); 695 add_filter( 'pre_option_template', array( $this, 'get_template' ) ); 696 697 // Handle custom theme roots. 698 add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); 699 add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); 700 } 701 702 /** 703 * Fires once the Customizer theme preview has started. 704 * 705 * @since 3.4.0 706 * 707 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 708 */ 709 do_action( 'start_previewing_theme', $this ); 710 } 711 712 /** 713 * Stops previewing the selected theme. 714 * 715 * Removes filters to change the active theme. 716 * 717 * @since 3.4.0 718 */ 719 public function stop_previewing_theme() { 720 if ( ! $this->is_preview() ) { 721 return; 722 } 723 724 $this->previewing = false; 725 726 if ( ! $this->is_theme_active() ) { 727 remove_filter( 'template', array( $this, 'get_template' ) ); 728 remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); 729 remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); 730 731 // @link: https://core.trac.wordpress.org/ticket/20027 732 remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); 733 remove_filter( 'pre_option_template', array( $this, 'get_template' ) ); 734 735 // Handle custom theme roots. 736 remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); 737 remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); 738 } 739 740 /** 741 * Fires once the Customizer theme preview has stopped. 742 * 743 * @since 3.4.0 744 * 745 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 746 */ 747 do_action( 'stop_previewing_theme', $this ); 748 } 749 750 /** 751 * Gets whether settings are or will be previewed. 752 * 753 * @since 4.9.0 754 * 755 * @see WP_Customize_Setting::preview() 756 * 757 * @return bool 758 */ 759 public function settings_previewed() { 760 return $this->settings_previewed; 761 } 762 763 /** 764 * Gets whether data from a changeset's autosaved revision should be loaded if it exists. 765 * 766 * @since 4.9.0 767 * 768 * @see WP_Customize_Manager::changeset_data() 769 * 770 * @return bool Is using autosaved changeset revision. 771 */ 772 public function autosaved() { 773 return $this->autosaved; 774 } 775 776 /** 777 * Whether the changeset branching is allowed. 778 * 779 * @since 4.9.0 780 * 781 * @see WP_Customize_Manager::establish_loaded_changeset() 782 * 783 * @return bool Is changeset branching. 784 */ 785 public function branching() { 786 787 /** 788 * Filters whether or not changeset branching is allowed. 789 * 790 * By default in core, when changeset branching is not allowed, changesets will operate 791 * linearly in that only one saved changeset will exist at a time (with a 'draft' or 792 * 'future' status). This makes the Customizer operate in a way that is similar to going to 793 * "edit" to one existing post: all users will be making changes to the same post, and autosave 794 * revisions will be made for that post. 795 * 796 * By contrast, when changeset branching is allowed, then the model is like users going 797 * to "add new" for a page and each user makes changes independently of each other since 798 * they are all operating on their own separate pages, each getting their own separate 799 * initial auto-drafts and then once initially saved, autosave revisions on top of that 800 * user's specific post. 801 * 802 * Since linear changesets are deemed to be more suitable for the majority of WordPress users, 803 * they are the default. For WordPress sites that have heavy site management in the Customizer 804 * by multiple users then branching changesets should be enabled by means of this filter. 805 * 806 * @since 4.9.0 807 * 808 * @param bool $allow_branching Whether branching is allowed. If `false`, the default, 809 * then only one saved changeset exists at a time. 810 * @param WP_Customize_Manager $wp_customize Manager instance. 811 */ 812 $this->branching = apply_filters( 'customize_changeset_branching', $this->branching, $this ); 813 814 return $this->branching; 815 } 816 817 /** 818 * Gets the changeset UUID. 819 * 820 * @since 4.7.0 821 * 822 * @see WP_Customize_Manager::establish_loaded_changeset() 823 * 824 * @return string UUID. 825 */ 826 public function changeset_uuid() { 827 if ( empty( $this->_changeset_uuid ) ) { 828 $this->establish_loaded_changeset(); 829 } 830 return $this->_changeset_uuid; 831 } 832 833 /** 834 * Gets the theme being customized. 835 * 836 * @since 3.4.0 837 * 838 * @return WP_Theme 839 */ 840 public function theme() { 841 if ( ! $this->theme ) { 842 $this->theme = wp_get_theme(); 843 } 844 return $this->theme; 845 } 846 847 /** 848 * Gets the registered settings. 849 * 850 * @since 3.4.0 851 * 852 * @return array 853 */ 854 public function settings() { 855 return $this->settings; 856 } 857 858 /** 859 * Gets the registered controls. 860 * 861 * @since 3.4.0 862 * 863 * @return array 864 */ 865 public function controls() { 866 return $this->controls; 867 } 868 869 /** 870 * Gets the registered containers. 871 * 872 * @since 4.0.0 873 * 874 * @return array 875 */ 876 public function containers() { 877 return $this->containers; 878 } 879 880 /** 881 * Gets the registered sections. 882 * 883 * @since 3.4.0 884 * 885 * @return array 886 */ 887 public function sections() { 888 return $this->sections; 889 } 890 891 /** 892 * Gets the registered panels. 893 * 894 * @since 4.0.0 895 * 896 * @return array Panels. 897 */ 898 public function panels() { 899 return $this->panels; 900 } 901 902 /** 903 * Checks if the current theme is active. 904 * 905 * @since 3.4.0 906 * 907 * @return bool 908 */ 909 public function is_theme_active() { 910 return $this->get_stylesheet() === $this->original_stylesheet; 911 } 912 913 /** 914 * Registers styles/scripts and initialize the preview of each setting 915 * 916 * @since 3.4.0 917 */ 918 public function wp_loaded() { 919 920 /* 921 * Unconditionally register core types for panels, sections, and controls 922 * in case plugin unhooks all customize_register actions. 923 */ 924 $this->register_panel_type( 'WP_Customize_Panel' ); 925 $this->register_panel_type( 'WP_Customize_Themes_Panel' ); 926 $this->register_section_type( 'WP_Customize_Section' ); 927 $this->register_section_type( 'WP_Customize_Sidebar_Section' ); 928 $this->register_section_type( 'WP_Customize_Themes_Section' ); 929 $this->register_control_type( 'WP_Customize_Color_Control' ); 930 $this->register_control_type( 'WP_Customize_Media_Control' ); 931 $this->register_control_type( 'WP_Customize_Upload_Control' ); 932 $this->register_control_type( 'WP_Customize_Image_Control' ); 933 $this->register_control_type( 'WP_Customize_Background_Image_Control' ); 934 $this->register_control_type( 'WP_Customize_Background_Position_Control' ); 935 $this->register_control_type( 'WP_Customize_Cropped_Image_Control' ); 936 $this->register_control_type( 'WP_Customize_Site_Icon_Control' ); 937 $this->register_control_type( 'WP_Customize_Theme_Control' ); 938 $this->register_control_type( 'WP_Customize_Code_Editor_Control' ); 939 $this->register_control_type( 'WP_Customize_Date_Time_Control' ); 940 941 /** 942 * Fires once WordPress has loaded, allowing scripts and styles to be initialized. 943 * 944 * @since 3.4.0 945 * 946 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 947 */ 948 do_action( 'customize_register', $this ); 949 950 if ( $this->settings_previewed() ) { 951 foreach ( $this->settings as $setting ) { 952 $setting->preview(); 953 } 954 } 955 956 if ( $this->is_preview() && ! is_admin() ) { 957 $this->customize_preview_init(); 958 } 959 } 960 961 /** 962 * Prevents Ajax requests from following redirects when previewing a theme 963 * by issuing a 200 response instead of a 30x. 964 * 965 * Instead, the JS will sniff out the location header. 966 * 967 * @since 3.4.0 968 * @deprecated 4.7.0 969 * 970 * @param int $status Status. 971 * @return int 972 */ 973 public function wp_redirect_status( $status ) { 974 _deprecated_function( __FUNCTION__, '4.7.0' ); 975 976 if ( $this->is_preview() && ! is_admin() ) { 977 return 200; 978 } 979 980 return $status; 981 } 982 983 /** 984 * Finds the changeset post ID for a given changeset UUID. 985 * 986 * @since 4.7.0 987 * 988 * @param string $uuid Changeset UUID. 989 * @return int|null Returns post ID on success and null on failure. 990 */ 991 public function find_changeset_post_id( $uuid ) { 992 $cache_group = 'customize_changeset_post'; 993 $changeset_post_id = wp_cache_get( $uuid, $cache_group ); 994 if ( $changeset_post_id && 'customize_changeset' === get_post_type( $changeset_post_id ) ) { 995 return $changeset_post_id; 996 } 997 998 $changeset_post_query = new WP_Query( 999 array( 1000 'post_type' => 'customize_changeset', 1001 'post_status' => get_post_stati(), 1002 'name' => $uuid, 1003 'posts_per_page' => 1, 1004 'no_found_rows' => true, 1005 'cache_results' => true, 1006 'update_post_meta_cache' => false, 1007 'update_post_term_cache' => false, 1008 'lazy_load_term_meta' => false, 1009 ) 1010 ); 1011 if ( ! empty( $changeset_post_query->posts ) ) { 1012 // Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed. 1013 $changeset_post_id = $changeset_post_query->posts[0]->ID; 1014 wp_cache_set( $uuid, $changeset_post_id, $cache_group ); 1015 return $changeset_post_id; 1016 } 1017 1018 return null; 1019 } 1020 1021 /** 1022 * Gets changeset posts. 1023 * 1024 * @since 4.9.0 1025 * 1026 * @param array $args { 1027 * Args to pass into `get_posts()` to query changesets. 1028 * 1029 * @type int $posts_per_page Number of posts to return. Defaults to -1 (all posts). 1030 * @type int $author Post author. Defaults to current user. 1031 * @type string $post_status Status of changeset. Defaults to 'auto-draft'. 1032 * @type bool $exclude_restore_dismissed Whether to exclude changeset auto-drafts that have been dismissed. Defaults to true. 1033 * } 1034 * @return WP_Post[] Auto-draft changesets. 1035 */ 1036 protected function get_changeset_posts( $args = array() ) { 1037 $default_args = array( 1038 'exclude_restore_dismissed' => true, 1039 'posts_per_page' => -1, 1040 'post_type' => 'customize_changeset', 1041 'post_status' => 'auto-draft', 1042 'order' => 'DESC', 1043 'orderby' => 'date', 1044 'no_found_rows' => true, 1045 'cache_results' => true, 1046 'update_post_meta_cache' => false, 1047 'update_post_term_cache' => false, 1048 'lazy_load_term_meta' => false, 1049 ); 1050 if ( get_current_user_id() ) { 1051 $default_args['author'] = get_current_user_id(); 1052 } 1053 $args = array_merge( $default_args, $args ); 1054 1055 if ( ! empty( $args['exclude_restore_dismissed'] ) ) { 1056 unset( $args['exclude_restore_dismissed'] ); 1057 $args['meta_query'] = array( 1058 array( 1059 'key' => '_customize_restore_dismissed', 1060 'compare' => 'NOT EXISTS', 1061 ), 1062 ); 1063 } 1064 1065 return get_posts( $args ); 1066 } 1067 1068 /** 1069 * Dismisses all of the current user's auto-drafts (other than the present one). 1070 * 1071 * @since 4.9.0 1072 * @return int The number of auto-drafts that were dismissed. 1073 */ 1074 protected function dismiss_user_auto_draft_changesets() { 1075 $changeset_autodraft_posts = $this->get_changeset_posts( 1076 array( 1077 'post_status' => 'auto-draft', 1078 'exclude_restore_dismissed' => true, 1079 'posts_per_page' => -1, 1080 ) 1081 ); 1082 $dismissed = 0; 1083 foreach ( $changeset_autodraft_posts as $autosave_autodraft_post ) { 1084 if ( $autosave_autodraft_post->ID === $this->changeset_post_id() ) { 1085 continue; 1086 } 1087 if ( update_post_meta( $autosave_autodraft_post->ID, '_customize_restore_dismissed', true ) ) { 1088 ++$dismissed; 1089 } 1090 } 1091 return $dismissed; 1092 } 1093 1094 /** 1095 * Gets the changeset post ID for the loaded changeset. 1096 * 1097 * @since 4.7.0 1098 * 1099 * @return int|null Post ID on success or null if there is no post yet saved. 1100 */ 1101 public function changeset_post_id() { 1102 if ( ! isset( $this->_changeset_post_id ) ) { 1103 $post_id = $this->find_changeset_post_id( $this->changeset_uuid() ); 1104 if ( ! $post_id ) { 1105 $post_id = false; 1106 } 1107 $this->_changeset_post_id = $post_id; 1108 } 1109 if ( false === $this->_changeset_post_id ) { 1110 return null; 1111 } 1112 return $this->_changeset_post_id; 1113 } 1114 1115 /** 1116 * Gets the data stored in a changeset post. 1117 * 1118 * @since 4.7.0 1119 * 1120 * @param int $post_id Changeset post ID. 1121 * @return array|WP_Error Changeset data or WP_Error on error. 1122 */ 1123 protected function get_changeset_post_data( $post_id ) { 1124 if ( ! $post_id ) { 1125 return new WP_Error( 'empty_post_id' ); 1126 } 1127 $changeset_post = get_post( $post_id ); 1128 if ( ! $changeset_post ) { 1129 return new WP_Error( 'missing_post' ); 1130 } 1131 if ( 'revision' === $changeset_post->post_type ) { 1132 if ( 'customize_changeset' !== get_post_type( $changeset_post->post_parent ) ) { 1133 return new WP_Error( 'wrong_post_type' ); 1134 } 1135 } elseif ( 'customize_changeset' !== $changeset_post->post_type ) { 1136 return new WP_Error( 'wrong_post_type' ); 1137 } 1138 $changeset_data = json_decode( $changeset_post->post_content, true ); 1139 $last_error = json_last_error(); 1140 if ( $last_error ) { 1141 return new WP_Error( 'json_parse_error', '', $last_error ); 1142 } 1143 if ( ! is_array( $changeset_data ) ) { 1144 return new WP_Error( 'expected_array' ); 1145 } 1146 return $changeset_data; 1147 } 1148 1149 /** 1150 * Gets changeset data. 1151 * 1152 * @since 4.7.0 1153 * @since 4.9.0 This will return the changeset's data with a user's autosave revision merged on top, if one exists and $autosaved is true. 1154 * 1155 * @return array Changeset data. 1156 */ 1157 public function changeset_data() { 1158 if ( isset( $this->_changeset_data ) ) { 1159 return $this->_changeset_data; 1160 } 1161 $changeset_post_id = $this->changeset_post_id(); 1162 if ( ! $changeset_post_id ) { 1163 $this->_changeset_data = array(); 1164 } else { 1165 if ( $this->autosaved() && is_user_logged_in() ) { 1166 $autosave_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); 1167 if ( $autosave_post ) { 1168 $data = $this->get_changeset_post_data( $autosave_post->ID ); 1169 if ( ! is_wp_error( $data ) ) { 1170 $this->_changeset_data = $data; 1171 } 1172 } 1173 } 1174 1175 // Load data from the changeset if it was not loaded from an autosave. 1176 if ( ! isset( $this->_changeset_data ) ) { 1177 $data = $this->get_changeset_post_data( $changeset_post_id ); 1178 if ( ! is_wp_error( $data ) ) { 1179 $this->_changeset_data = $data; 1180 } else { 1181 $this->_changeset_data = array(); 1182 } 1183 } 1184 } 1185 return $this->_changeset_data; 1186 } 1187 1188 /** 1189 * Starter content setting IDs. 1190 * 1191 * @since 4.7.0 1192 * @var array 1193 */ 1194 protected $pending_starter_content_settings_ids = array(); 1195 1196 /** 1197 * Imports theme starter content into the customized state. 1198 * 1199 * @since 4.7.0 1200 * 1201 * @param array $starter_content Starter content. Defaults to `get_theme_starter_content()`. 1202 */ 1203 public function import_theme_starter_content( $starter_content = array() ) { 1204 if ( empty( $starter_content ) ) { 1205 $starter_content = get_theme_starter_content(); 1206 } 1207 1208 $changeset_data = array(); 1209 if ( $this->changeset_post_id() ) { 1210 /* 1211 * Don't re-import starter content into a changeset saved persistently. 1212 * This will need to be revisited in the future once theme switching 1213 * is allowed with drafted/scheduled changesets, since switching to 1214 * another theme could result in more starter content being applied. 1215 * However, when doing an explicit save it is currently possible for 1216 * nav menus and nav menu items specifically to lose their starter_content 1217 * flags, thus resulting in duplicates being created since they fail 1218 * to get re-used. See #40146. 1219 */ 1220 if ( 'auto-draft' !== get_post_status( $this->changeset_post_id() ) ) { 1221 return; 1222 } 1223 1224 $changeset_data = $this->get_changeset_post_data( $this->changeset_post_id() ); 1225 } 1226 1227 $sidebars_widgets = isset( $starter_content['widgets'] ) && ! empty( $this->widgets ) ? $starter_content['widgets'] : array(); 1228 $attachments = isset( $starter_content['attachments'] ) && ! empty( $this->nav_menus ) ? $starter_content['attachments'] : array(); 1229 $posts = isset( $starter_content['posts'] ) && ! empty( $this->nav_menus ) ? $starter_content['posts'] : array(); 1230 $options = $starter_content['options'] ?? array(); 1231 $nav_menus = isset( $starter_content['nav_menus'] ) && ! empty( $this->nav_menus ) ? $starter_content['nav_menus'] : array(); 1232 $theme_mods = $starter_content['theme_mods'] ?? array(); 1233 1234 // Widgets. 1235 $max_widget_numbers = array(); 1236 foreach ( $sidebars_widgets as $sidebar_id => $widgets ) { 1237 $sidebar_widget_ids = array(); 1238 foreach ( $widgets as $widget ) { 1239 list( $id_base, $instance ) = $widget; 1240 1241 if ( ! isset( $max_widget_numbers[ $id_base ] ) ) { 1242 1243 // When $settings is an array-like object, get an intrinsic array for use with array_keys(). 1244 $settings = get_option( "widget_{$id_base}", array() ); 1245 if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) { 1246 $settings = $settings->getArrayCopy(); 1247 } 1248 1249 unset( $settings['_multiwidget'] ); 1250 1251 // Find the max widget number for this type. 1252 $widget_numbers = array_keys( $settings ); 1253 if ( count( $widget_numbers ) > 0 ) { 1254 $widget_numbers[] = 1; 1255 $max_widget_numbers[ $id_base ] = max( ...$widget_numbers ); 1256 } else { 1257 $max_widget_numbers[ $id_base ] = 1; 1258 } 1259 } 1260 $max_widget_numbers[ $id_base ] += 1; 1261 1262 $widget_id = sprintf( '%s-%d', $id_base, $max_widget_numbers[ $id_base ] ); 1263 $setting_id = sprintf( 'widget_%s[%d]', $id_base, $max_widget_numbers[ $id_base ] ); 1264 1265 $setting_value = $this->widgets->sanitize_widget_js_instance( $instance ); 1266 if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { 1267 $this->set_post_value( $setting_id, $setting_value ); 1268 $this->pending_starter_content_settings_ids[] = $setting_id; 1269 } 1270 $sidebar_widget_ids[] = $widget_id; 1271 } 1272 1273 $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id ); 1274 if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { 1275 $this->set_post_value( $setting_id, $sidebar_widget_ids ); 1276 $this->pending_starter_content_settings_ids[] = $setting_id; 1277 } 1278 } 1279 1280 $starter_content_auto_draft_post_ids = array(); 1281 if ( ! empty( $changeset_data['nav_menus_created_posts']['value'] ) ) { 1282 $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, $changeset_data['nav_menus_created_posts']['value'] ); 1283 } 1284 1285 // Make an index of all the posts needed and what their slugs are. 1286 $needed_posts = array(); 1287 $attachments = $this->prepare_starter_content_attachments( $attachments ); 1288 foreach ( $attachments as $attachment ) { 1289 $key = 'attachment:' . $attachment['post_name']; 1290 $needed_posts[ $key ] = true; 1291 } 1292 foreach ( array_keys( $posts ) as $post_symbol ) { 1293 if ( empty( $posts[ $post_symbol ]['post_name'] ) && empty( $posts[ $post_symbol ]['post_title'] ) ) { 1294 unset( $posts[ $post_symbol ] ); 1295 continue; 1296 } 1297 if ( empty( $posts[ $post_symbol ]['post_name'] ) ) { 1298 $posts[ $post_symbol ]['post_name'] = sanitize_title( $posts[ $post_symbol ]['post_title'] ); 1299 } 1300 if ( empty( $posts[ $post_symbol ]['post_type'] ) ) { 1301 $posts[ $post_symbol ]['post_type'] = 'post'; 1302 } 1303 $needed_posts[ $posts[ $post_symbol ]['post_type'] . ':' . $posts[ $post_symbol ]['post_name'] ] = true; 1304 } 1305 $all_post_slugs = array_merge( 1306 wp_list_pluck( $attachments, 'post_name' ), 1307 wp_list_pluck( $posts, 'post_name' ) 1308 ); 1309 1310 /* 1311 * Obtain all post types referenced in starter content to use in query. 1312 * This is needed because 'any' will not account for post types not yet registered. 1313 */ 1314 $post_types = array_filter( array_merge( array( 'attachment' ), wp_list_pluck( $posts, 'post_type' ) ) ); 1315 1316 // Re-use auto-draft starter content posts referenced in the current customized state. 1317 $existing_starter_content_posts = array(); 1318 if ( ! empty( $starter_content_auto_draft_post_ids ) ) { 1319 $existing_posts_query = new WP_Query( 1320 array( 1321 'post__in' => $starter_content_auto_draft_post_ids, 1322 'post_status' => 'auto-draft', 1323 'post_type' => $post_types, 1324 'posts_per_page' => -1, 1325 ) 1326 ); 1327 foreach ( $existing_posts_query->posts as $existing_post ) { 1328 $post_name = $existing_post->post_name; 1329 if ( empty( $post_name ) ) { 1330 $post_name = get_post_meta( $existing_post->ID, '_customize_draft_post_name', true ); 1331 } 1332 $existing_starter_content_posts[ $existing_post->post_type . ':' . $post_name ] = $existing_post; 1333 } 1334 } 1335 1336 // Re-use non-auto-draft posts. 1337 if ( ! empty( $all_post_slugs ) ) { 1338 $existing_posts_query = new WP_Query( 1339 array( 1340 'post_name__in' => $all_post_slugs, 1341 'post_status' => array_diff( get_post_stati(), array( 'auto-draft' ) ), 1342 'post_type' => 'any', 1343 'posts_per_page' => -1, 1344 ) 1345 ); 1346 foreach ( $existing_posts_query->posts as $existing_post ) { 1347 $key = $existing_post->post_type . ':' . $existing_post->post_name; 1348 if ( isset( $needed_posts[ $key ] ) && ! isset( $existing_starter_content_posts[ $key ] ) ) { 1349 $existing_starter_content_posts[ $key ] = $existing_post; 1350 } 1351 } 1352 } 1353 1354 // Attachments are technically posts but handled differently. 1355 if ( ! empty( $attachments ) ) { 1356 1357 $attachment_ids = array(); 1358 1359 foreach ( $attachments as $symbol => $attachment ) { 1360 $file_array = array( 1361 'name' => $attachment['file_name'], 1362 ); 1363 $file_path = $attachment['file_path']; 1364 $attachment_id = null; 1365 $attached_file = null; 1366 if ( isset( $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ] ) ) { 1367 $attachment_post = $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ]; 1368 $attachment_id = $attachment_post->ID; 1369 $attached_file = get_attached_file( $attachment_id ); 1370 if ( empty( $attached_file ) || ! file_exists( $attached_file ) ) { 1371 $attachment_id = null; 1372 $attached_file = null; 1373 } elseif ( $this->get_stylesheet() !== get_post_meta( $attachment_post->ID, '_starter_content_theme', true ) ) { 1374 1375 // Re-generate attachment metadata since it was previously generated for a different theme. 1376 $metadata = wp_generate_attachment_metadata( $attachment_post->ID, $attached_file ); 1377 wp_update_attachment_metadata( $attachment_id, $metadata ); 1378 update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() ); 1379 } 1380 } 1381 1382 // Insert the attachment auto-draft because it doesn't yet exist or the attached file is gone. 1383 if ( ! $attachment_id ) { 1384 1385 // Copy file to temp location so that original file won't get deleted from theme after sideloading. 1386 $temp_file_name = wp_tempnam( wp_basename( $file_path ) ); 1387 if ( $temp_file_name && copy( $file_path, $temp_file_name ) ) { 1388 $file_array['tmp_name'] = $temp_file_name; 1389 } 1390 if ( empty( $file_array['tmp_name'] ) ) { 1391 continue; 1392 } 1393 1394 $attachment_post_data = array_merge( 1395 wp_array_slice_assoc( $attachment, array( 'post_title', 'post_content', 'post_excerpt' ) ), 1396 array( 1397 'post_status' => 'auto-draft', // So attachment will be garbage collected in a week if changeset is never published. 1398 ) 1399 ); 1400 1401 $attachment_id = media_handle_sideload( $file_array, 0, null, $attachment_post_data ); 1402 if ( is_wp_error( $attachment_id ) ) { 1403 continue; 1404 } 1405 update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() ); 1406 update_post_meta( $attachment_id, '_customize_draft_post_name', $attachment['post_name'] ); 1407 } 1408 1409 $attachment_ids[ $symbol ] = $attachment_id; 1410 } 1411 $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, array_values( $attachment_ids ) ); 1412 } 1413 1414 // Posts & pages. 1415 if ( ! empty( $posts ) ) { 1416 foreach ( array_keys( $posts ) as $post_symbol ) { 1417 if ( empty( $posts[ $post_symbol ]['post_type'] ) || empty( $posts[ $post_symbol ]['post_name'] ) ) { 1418 continue; 1419 } 1420 $post_type = $posts[ $post_symbol ]['post_type']; 1421 if ( ! empty( $posts[ $post_symbol ]['post_name'] ) ) { 1422 $post_name = $posts[ $post_symbol ]['post_name']; 1423 } elseif ( ! empty( $posts[ $post_symbol ]['post_title'] ) ) { 1424 $post_name = sanitize_title( $posts[ $post_symbol ]['post_title'] ); 1425 } else { 1426 continue; 1427 } 1428 1429 // Use existing auto-draft post if one already exists with the same type and name. 1430 if ( isset( $existing_starter_content_posts[ $post_type . ':' . $post_name ] ) ) { 1431 $posts[ $post_symbol ]['ID'] = $existing_starter_content_posts[ $post_type . ':' . $post_name ]->ID; 1432 continue; 1433 } 1434 1435 // Translate the featured image symbol. 1436 if ( ! empty( $posts[ $post_symbol ]['thumbnail'] ) 1437 && preg_match( '/^{{(?P<symbol>.+)}}$/', $posts[ $post_symbol ]['thumbnail'], $matches ) 1438 && isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1439 $posts[ $post_symbol ]['meta_input']['_thumbnail_id'] = $attachment_ids[ $matches['symbol'] ]; 1440 } 1441 1442 if ( ! empty( $posts[ $post_symbol ]['template'] ) ) { 1443 $posts[ $post_symbol ]['meta_input']['_wp_page_template'] = $posts[ $post_symbol ]['template']; 1444 } 1445 1446 $r = $this->nav_menus->insert_auto_draft_post( $posts[ $post_symbol ] ); 1447 if ( $r instanceof WP_Post ) { 1448 $posts[ $post_symbol ]['ID'] = $r->ID; 1449 } 1450 } 1451 1452 $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, wp_list_pluck( $posts, 'ID' ) ); 1453 } 1454 1455 // The nav_menus_created_posts setting is why nav_menus component is dependency for adding posts. 1456 if ( ! empty( $this->nav_menus ) && ! empty( $starter_content_auto_draft_post_ids ) ) { 1457 $setting_id = 'nav_menus_created_posts'; 1458 $this->set_post_value( $setting_id, array_unique( array_values( $starter_content_auto_draft_post_ids ) ) ); 1459 $this->pending_starter_content_settings_ids[] = $setting_id; 1460 } 1461 1462 // Nav menus. 1463 $placeholder_id = -1; 1464 $reused_nav_menu_setting_ids = array(); 1465 foreach ( $nav_menus as $nav_menu_location => $nav_menu ) { 1466 1467 $nav_menu_term_id = null; 1468 $nav_menu_setting_id = null; 1469 $matches = array(); 1470 1471 // Look for an existing placeholder menu with starter content to re-use. 1472 foreach ( $changeset_data as $setting_id => $setting_params ) { 1473 $can_reuse = ( 1474 ! empty( $setting_params['starter_content'] ) 1475 && 1476 ! in_array( $setting_id, $reused_nav_menu_setting_ids, true ) 1477 && 1478 preg_match( '#^nav_menu\[(?P<nav_menu_id>-?\d+)\]$#', $setting_id, $matches ) 1479 ); 1480 if ( $can_reuse ) { 1481 $nav_menu_term_id = (int) $matches['nav_menu_id']; 1482 $nav_menu_setting_id = $setting_id; 1483 $reused_nav_menu_setting_ids[] = $setting_id; 1484 break; 1485 } 1486 } 1487 1488 if ( ! $nav_menu_term_id ) { 1489 while ( isset( $changeset_data[ sprintf( 'nav_menu[%d]', $placeholder_id ) ] ) ) { 1490 --$placeholder_id; 1491 } 1492 $nav_menu_term_id = $placeholder_id; 1493 $nav_menu_setting_id = sprintf( 'nav_menu[%d]', $placeholder_id ); 1494 } 1495 1496 $this->set_post_value( 1497 $nav_menu_setting_id, 1498 array( 1499 'name' => $nav_menu['name'] ?? $nav_menu_location, 1500 ) 1501 ); 1502 $this->pending_starter_content_settings_ids[] = $nav_menu_setting_id; 1503 1504 // @todo Add support for menu_item_parent. 1505 $position = 0; 1506 foreach ( $nav_menu['items'] as $nav_menu_item ) { 1507 $nav_menu_item_setting_id = sprintf( 'nav_menu_item[%d]', $placeholder_id-- ); 1508 if ( ! isset( $nav_menu_item['position'] ) ) { 1509 $nav_menu_item['position'] = $position++; 1510 } 1511 $nav_menu_item['nav_menu_term_id'] = $nav_menu_term_id; 1512 1513 if ( isset( $nav_menu_item['object_id'] ) ) { 1514 if ( 'post_type' === $nav_menu_item['type'] && preg_match( '/^{{(?P<symbol>.+)}}$/', $nav_menu_item['object_id'], $matches ) && isset( $posts[ $matches['symbol'] ] ) ) { 1515 $nav_menu_item['object_id'] = $posts[ $matches['symbol'] ]['ID']; 1516 if ( empty( $nav_menu_item['title'] ) ) { 1517 $original_object = get_post( $nav_menu_item['object_id'] ); 1518 $nav_menu_item['title'] = $original_object->post_title; 1519 } 1520 } else { 1521 continue; 1522 } 1523 } else { 1524 $nav_menu_item['object_id'] = 0; 1525 } 1526 1527 if ( empty( $changeset_data[ $nav_menu_item_setting_id ] ) || ! empty( $changeset_data[ $nav_menu_item_setting_id ]['starter_content'] ) ) { 1528 $this->set_post_value( $nav_menu_item_setting_id, $nav_menu_item ); 1529 $this->pending_starter_content_settings_ids[] = $nav_menu_item_setting_id; 1530 } 1531 } 1532 1533 $setting_id = sprintf( 'nav_menu_locations[%s]', $nav_menu_location ); 1534 if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { 1535 $this->set_post_value( $setting_id, $nav_menu_term_id ); 1536 $this->pending_starter_content_settings_ids[] = $setting_id; 1537 } 1538 } 1539 1540 // Options. 1541 foreach ( $options as $name => $value ) { 1542 1543 // Serialize the value to check for post symbols. 1544 $value = maybe_serialize( $value ); 1545 1546 if ( is_serialized( $value ) ) { 1547 if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) { 1548 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1549 $symbol_match = $posts[ $matches['symbol'] ]['ID']; 1550 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1551 $symbol_match = $attachment_ids[ $matches['symbol'] ]; 1552 } 1553 1554 // If we have any symbol matches, update the values. 1555 if ( isset( $symbol_match ) ) { 1556 // Replace found string matches with post IDs. 1557 $value = str_replace( $matches[0], "i:{$symbol_match}", $value ); 1558 } else { 1559 continue; 1560 } 1561 } 1562 } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) { 1563 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1564 $value = $posts[ $matches['symbol'] ]['ID']; 1565 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1566 $value = $attachment_ids[ $matches['symbol'] ]; 1567 } else { 1568 continue; 1569 } 1570 } 1571 1572 // Unserialize values after checking for post symbols, so they can be properly referenced. 1573 $value = maybe_unserialize( $value ); 1574 1575 if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) { 1576 $this->set_post_value( $name, $value ); 1577 $this->pending_starter_content_settings_ids[] = $name; 1578 } 1579 } 1580 1581 // Theme mods. 1582 foreach ( $theme_mods as $name => $value ) { 1583 1584 // Serialize the value to check for post symbols. 1585 $value = maybe_serialize( $value ); 1586 1587 // Check if value was serialized. 1588 if ( is_serialized( $value ) ) { 1589 if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) { 1590 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1591 $symbol_match = $posts[ $matches['symbol'] ]['ID']; 1592 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1593 $symbol_match = $attachment_ids[ $matches['symbol'] ]; 1594 } 1595 1596 // If we have any symbol matches, update the values. 1597 if ( isset( $symbol_match ) ) { 1598 // Replace found string matches with post IDs. 1599 $value = str_replace( $matches[0], "i:{$symbol_match}", $value ); 1600 } else { 1601 continue; 1602 } 1603 } 1604 } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) { 1605 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1606 $value = $posts[ $matches['symbol'] ]['ID']; 1607 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1608 $value = $attachment_ids[ $matches['symbol'] ]; 1609 } else { 1610 continue; 1611 } 1612 } 1613 1614 // Unserialize values after checking for post symbols, so they can be properly referenced. 1615 $value = maybe_unserialize( $value ); 1616 1617 // Handle header image as special case since setting has a legacy format. 1618 if ( 'header_image' === $name ) { 1619 $name = 'header_image_data'; 1620 $metadata = wp_get_attachment_metadata( $value ); 1621 if ( empty( $metadata ) ) { 1622 continue; 1623 } 1624 $value = array( 1625 'attachment_id' => $value, 1626 'url' => wp_get_attachment_url( $value ), 1627 'height' => $metadata['height'], 1628 'width' => $metadata['width'], 1629 ); 1630 } elseif ( 'background_image' === $name ) { 1631 $value = wp_get_attachment_url( $value ); 1632 } 1633 1634 if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) { 1635 $this->set_post_value( $name, $value ); 1636 $this->pending_starter_content_settings_ids[] = $name; 1637 } 1638 } 1639 1640 if ( ! empty( $this->pending_starter_content_settings_ids ) ) { 1641 if ( did_action( 'customize_register' ) ) { 1642 $this->_save_starter_content_changeset(); 1643 } else { 1644 add_action( 'customize_register', array( $this, '_save_starter_content_changeset' ), 1000 ); 1645 } 1646 } 1647 } 1648 1649 /** 1650 * Prepares starter content attachments. 1651 * 1652 * Ensure that the attachments are valid and that they have slugs and file name/path. 1653 * 1654 * @since 4.7.0 1655 * 1656 * @param array $attachments Attachments. 1657 * @return array Prepared attachments. 1658 */ 1659 protected function prepare_starter_content_attachments( $attachments ) { 1660 $prepared_attachments = array(); 1661 if ( empty( $attachments ) ) { 1662 return $prepared_attachments; 1663 } 1664 1665 // Such is The WordPress Way. 1666 require_once ABSPATH . 'wp-admin/includes/file.php'; 1667 require_once ABSPATH . 'wp-admin/includes/media.php'; 1668 require_once ABSPATH . 'wp-admin/includes/image.php'; 1669 1670 foreach ( $attachments as $symbol => $attachment ) { 1671 1672 // A file is required and URLs to files are not currently allowed. 1673 if ( empty( $attachment['file'] ) || preg_match( '#^https?://$#', $attachment['file'] ) ) { 1674 continue; 1675 } 1676 1677 $file_path = null; 1678 if ( file_exists( $attachment['file'] ) ) { 1679 $file_path = $attachment['file']; // Could be absolute path to file in plugin. 1680 } elseif ( is_child_theme() && file_exists( get_stylesheet_directory() . '/' . $attachment['file'] ) ) { 1681 $file_path = get_stylesheet_directory() . '/' . $attachment['file']; 1682 } elseif ( file_exists( get_template_directory() . '/' . $attachment['file'] ) ) { 1683 $file_path = get_template_directory() . '/' . $attachment['file']; 1684 } else { 1685 continue; 1686 } 1687 $file_name = wp_basename( $attachment['file'] ); 1688 1689 // Skip file types that are not recognized. 1690 $checked_filetype = wp_check_filetype( $file_name ); 1691 if ( empty( $checked_filetype['type'] ) ) { 1692 continue; 1693 } 1694 1695 // Ensure post_name is set since not automatically derived from post_title for new auto-draft posts. 1696 if ( empty( $attachment['post_name'] ) ) { 1697 if ( ! empty( $attachment['post_title'] ) ) { 1698 $attachment['post_name'] = sanitize_title( $attachment['post_title'] ); 1699 } else { 1700 $attachment['post_name'] = sanitize_title( preg_replace( '/\.\w+$/', '', $file_name ) ); 1701 } 1702 } 1703 1704 $attachment['file_name'] = $file_name; 1705 $attachment['file_path'] = $file_path; 1706 $prepared_attachments[ $symbol ] = $attachment; 1707 } 1708 return $prepared_attachments; 1709 } 1710 1711 /** 1712 * Saves starter content changeset. 1713 * 1714 * @since 4.7.0 1715 */ 1716 public function _save_starter_content_changeset() { 1717 1718 if ( empty( $this->pending_starter_content_settings_ids ) ) { 1719 return; 1720 } 1721 1722 $this->save_changeset_post( 1723 array( 1724 'data' => array_fill_keys( $this->pending_starter_content_settings_ids, array( 'starter_content' => true ) ), 1725 'starter_content' => true, 1726 ) 1727 ); 1728 $this->saved_starter_content_changeset = true; 1729 1730 $this->pending_starter_content_settings_ids = array(); 1731 } 1732 1733 /** 1734 * Gets dirty pre-sanitized setting values in the current customized state. 1735 * 1736 * The returned array consists of a merge of three sources: 1737 * 1. If the theme is not currently active, then the base array is any stashed 1738 * theme mods that were modified previously but never published. 1739 * 2. The values from the current changeset, if it exists. 1740 * 3. If the user can customize, the values parsed from the incoming 1741 * `$_POST['customized']` JSON data. 1742 * 4. Any programmatically-set post values via `WP_Customize_Manager::set_post_value()`. 1743 * 1744 * The name "unsanitized_post_values" is a carry-over from when the customized 1745 * state was exclusively sourced from `$_POST['customized']`. Nevertheless, 1746 * the value returned will come from the current changeset post and from the 1747 * incoming post data. 1748 * 1749 * @since 4.1.1 1750 * @since 4.7.0 Added `$args` parameter and merging with changeset values and stashed theme mods. 1751 * 1752 * @param array $args { 1753 * Args. 1754 * 1755 * @type bool $exclude_changeset Whether the changeset values should also be excluded. Defaults to false. 1756 * @type bool $exclude_post_data Whether the post input values should also be excluded. Defaults to false when lacking the customize capability. 1757 * } 1758 * @return array 1759 */ 1760 public function unsanitized_post_values( $args = array() ) { 1761 $args = array_merge( 1762 array( 1763 'exclude_changeset' => false, 1764 'exclude_post_data' => ! current_user_can( 'customize' ), 1765 ), 1766 $args 1767 ); 1768 1769 $values = array(); 1770 1771 // Let default values be from the stashed theme mods if doing a theme switch and if no changeset is present. 1772 if ( ! $this->is_theme_active() ) { 1773 $stashed_theme_mods = get_option( 'customize_stashed_theme_mods' ); 1774 $stylesheet = $this->get_stylesheet(); 1775 if ( isset( $stashed_theme_mods[ $stylesheet ] ) ) { 1776 $values = array_merge( $values, wp_list_pluck( $stashed_theme_mods[ $stylesheet ], 'value' ) ); 1777 } 1778 } 1779 1780 if ( ! $args['exclude_changeset'] ) { 1781 foreach ( $this->changeset_data() as $setting_id => $setting_params ) { 1782 if ( ! array_key_exists( 'value', $setting_params ) ) { 1783 continue; 1784 } 1785 if ( isset( $setting_params['type'] ) && 'theme_mod' === $setting_params['type'] ) { 1786 1787 // Ensure that theme mods values are only used if they were saved under the active theme. 1788 $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/'; 1789 if ( preg_match( $namespace_pattern, $setting_id, $matches ) && $this->get_stylesheet() === $matches['stylesheet'] ) { 1790 $values[ $matches['setting_id'] ] = $setting_params['value']; 1791 } 1792 } else { 1793 $values[ $setting_id ] = $setting_params['value']; 1794 } 1795 } 1796 } 1797 1798 if ( ! $args['exclude_post_data'] ) { 1799 if ( ! isset( $this->_post_values ) ) { 1800 if ( isset( $_POST['customized'] ) ) { 1801 $post_values = json_decode( wp_unslash( $_POST['customized'] ), true ); 1802 } else { 1803 $post_values = array(); 1804 } 1805 if ( is_array( $post_values ) ) { 1806 $this->_post_values = $post_values; 1807 } else { 1808 $this->_post_values = array(); 1809 } 1810 } 1811 $values = array_merge( $values, $this->_post_values ); 1812 } 1813 return $values; 1814 } 1815 1816 /** 1817 * Returns the sanitized value for a given setting from the current customized state. 1818 * 1819 * The name "post_value" is a carry-over from when the customized state was exclusively 1820 * sourced from `$_POST['customized']`. Nevertheless, the value returned will come 1821 * from the current changeset post and from the incoming post data. 1822 * 1823 * @since 3.4.0 1824 * @since 4.1.1 Introduced the `$default_value` parameter. 1825 * @since 4.6.0 `$default_value` is now returned early when the setting post value is invalid. 1826 * 1827 * @see WP_REST_Server::dispatch() 1828 * @see WP_REST_Request::sanitize_params() 1829 * @see WP_REST_Request::has_valid_params() 1830 * 1831 * @param WP_Customize_Setting $setting A WP_Customize_Setting derived object. 1832 * @param mixed $default_value Value returned if `$setting` has no post value (added in 4.2.0) 1833 * or the post value is invalid (added in 4.6.0). 1834 * @return string|mixed Sanitized value or the `$default_value` provided. 1835 */ 1836 public function post_value( $setting, $default_value = null ) { 1837 $post_values = $this->unsanitized_post_values(); 1838 if ( ! array_key_exists( $setting->id, $post_values ) ) { 1839 return $default_value; 1840 } 1841 1842 $value = $post_values[ $setting->id ]; 1843 $valid = $setting->validate( $value ); 1844 if ( is_wp_error( $valid ) ) { 1845 return $default_value; 1846 } 1847 1848 $value = $setting->sanitize( $value ); 1849 if ( is_null( $value ) || is_wp_error( $value ) ) { 1850 return $default_value; 1851 } 1852 1853 return $value; 1854 } 1855 1856 /** 1857 * Overrides a setting's value in the current customized state. 1858 * 1859 * The name "post_value" is a carry-over from when the customized state was 1860 * exclusively sourced from `$_POST['customized']`. 1861 * 1862 * @since 4.2.0 1863 * 1864 * @param string $setting_id ID for the WP_Customize_Setting instance. 1865 * @param mixed $value Post value. 1866 */ 1867 public function set_post_value( $setting_id, $value ) { 1868 $this->unsanitized_post_values(); // Populate _post_values from $_POST['customized']. 1869 $this->_post_values[ $setting_id ] = $value; 1870 1871 /** 1872 * Announces when a specific setting's unsanitized post value has been set. 1873 * 1874 * Fires when the WP_Customize_Manager::set_post_value() method is called. 1875 * 1876 * The dynamic portion of the hook name, `$setting_id`, refers to the setting ID. 1877 * 1878 * @since 4.4.0 1879 * 1880 * @param mixed $value Unsanitized setting post value. 1881 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 1882 */ 1883 do_action( "customize_post_value_set_{$setting_id}", $value, $this ); 1884 1885 /** 1886 * Announces when any setting's unsanitized post value has been set. 1887 * 1888 * Fires when the WP_Customize_Manager::set_post_value() method is called. 1889 * 1890 * This is useful for `WP_Customize_Setting` instances to watch 1891 * in order to update a cached previewed value. 1892 * 1893 * @since 4.4.0 1894 * 1895 * @param string $setting_id Setting ID. 1896 * @param mixed $value Unsanitized setting post value. 1897 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 1898 */ 1899 do_action( 'customize_post_value_set', $setting_id, $value, $this ); 1900 } 1901 1902 /** 1903 * Prints JavaScript settings. 1904 * 1905 * @since 3.4.0 1906 */ 1907 public function customize_preview_init() { 1908 1909 /* 1910 * Now that Customizer previews are loaded into iframes via GET requests 1911 * and natural URLs with transaction UUIDs added, we need to ensure that 1912 * the responses are never cached by proxies. In practice, this will not 1913 * be needed if the user is logged-in anyway. But if anonymous access is 1914 * allowed then the auth cookies would not be sent and WordPress would 1915 * not send no-cache headers by default. 1916 */ 1917 if ( ! headers_sent() ) { 1918 nocache_headers(); 1919 header( 'X-Robots: noindex, nofollow, noarchive' ); 1920 header( 'X-Robots-Tag: noindex, nofollow, noarchive' ); 1921 } 1922 add_filter( 'wp_robots', 'wp_robots_no_robots' ); 1923 add_filter( 'wp_headers', array( $this, 'filter_iframe_security_headers' ) ); 1924 1925 /* 1926 * If preview is being served inside the customizer preview iframe, and 1927 * if the user doesn't have customize capability, then it is assumed 1928 * that the user's session has expired and they need to re-authenticate. 1929 */ 1930 if ( $this->messenger_channel && ! current_user_can( 'customize' ) ) { 1931 $this->wp_die( 1932 -1, 1933 sprintf( 1934 /* translators: %s: customize_messenger_channel */ 1935 __( 'Unauthorized. You may remove the %s param to preview as frontend.' ), 1936 '<code>customize_messenger_channel</code>' 1937 ) 1938 ); 1939 } 1940 1941 $this->prepare_controls(); 1942 1943 add_filter( 'wp_redirect', array( $this, 'add_state_query_params' ) ); 1944 1945 wp_enqueue_script( 'customize-preview' ); 1946 wp_enqueue_style( 'customize-preview' ); 1947 add_action( 'wp_head', array( $this, 'customize_preview_loading_style' ) ); 1948 add_action( 'wp_head', array( $this, 'remove_frameless_preview_messenger_channel' ) ); 1949 add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 ); 1950 add_filter( 'get_edit_post_link', '__return_empty_string' ); 1951 1952 /** 1953 * Fires once the Customizer preview has initialized and JavaScript 1954 * settings have been printed. 1955 * 1956 * @since 3.4.0 1957 * 1958 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 1959 */ 1960 do_action( 'customize_preview_init', $this ); 1961 } 1962 1963 /** 1964 * Filters the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer. 1965 * 1966 * @since 4.7.0 1967 * 1968 * @param array $headers Headers. 1969 * @return array Headers. 1970 */ 1971 public function filter_iframe_security_headers( $headers ) { 1972 $headers['X-Frame-Options'] = 'SAMEORIGIN'; 1973 $headers['Content-Security-Policy'] = "frame-ancestors 'self'"; 1974 return $headers; 1975 } 1976 1977 /** 1978 * Adds customize state query params to a given URL if preview is allowed. 1979 * 1980 * @since 4.7.0 1981 * 1982 * @see wp_redirect() 1983 * @see WP_Customize_Manager::get_allowed_url() 1984 * 1985 * @param string $url URL. 1986 * @return string URL. 1987 */ 1988 public function add_state_query_params( $url ) { 1989 $parsed_original_url = wp_parse_url( $url ); 1990 $is_allowed = false; 1991 foreach ( $this->get_allowed_urls() as $allowed_url ) { 1992 $parsed_allowed_url = wp_parse_url( $allowed_url ); 1993 $is_allowed = ( 1994 $parsed_allowed_url['scheme'] === $parsed_original_url['scheme'] 1995 && 1996 $parsed_allowed_url['host'] === $parsed_original_url['host'] 1997 && 1998 str_starts_with( $parsed_original_url['path'], $parsed_allowed_url['path'] ) 1999 ); 2000 if ( $is_allowed ) { 2001 break; 2002 } 2003 } 2004 2005 if ( $is_allowed ) { 2006 $query_params = array( 2007 'customize_changeset_uuid' => $this->changeset_uuid(), 2008 ); 2009 if ( ! $this->is_theme_active() ) { 2010 $query_params['customize_theme'] = $this->get_stylesheet(); 2011 } 2012 if ( $this->messenger_channel ) { 2013 $query_params['customize_messenger_channel'] = $this->messenger_channel; 2014 } 2015 $url = add_query_arg( $query_params, $url ); 2016 } 2017 2018 return $url; 2019 } 2020 2021 /** 2022 * Prevents sending a 404 status when returning the response for the customize 2023 * preview, since it causes the jQuery Ajax to fail. Send 200 instead. 2024 * 2025 * @since 4.0.0 2026 * @deprecated 4.7.0 2027 */ 2028 public function customize_preview_override_404_status() { 2029 _deprecated_function( __METHOD__, '4.7.0' ); 2030 } 2031 2032 /** 2033 * Prints base element for preview frame. 2034 * 2035 * @since 3.4.0 2036 * @deprecated 4.7.0 2037 */ 2038 public function customize_preview_base() { 2039 _deprecated_function( __METHOD__, '4.7.0' ); 2040 } 2041 2042 /** 2043 * Prints a workaround to handle HTML5 tags in IE < 9. 2044 * 2045 * @since 3.4.0 2046 * @deprecated 4.7.0 Customizer no longer supports IE8, so all supported browsers recognize HTML5. 2047 */ 2048 public function customize_preview_html5() { 2049 _deprecated_function( __FUNCTION__, '4.7.0' ); 2050 } 2051 2052 /** 2053 * Prints CSS for loading indicators for the Customizer preview. 2054 * 2055 * @since 4.2.0 2056 */ 2057 public function customize_preview_loading_style() { 2058 ?> 2059 <style> 2060 body.wp-customizer-unloading { 2061 opacity: 0.25; 2062 cursor: progress !important; 2063 -webkit-transition: opacity 0.5s; 2064 transition: opacity 0.5s; 2065 } 2066 body.wp-customizer-unloading * { 2067 pointer-events: none !important; 2068 } 2069 form.customize-unpreviewable, 2070 form.customize-unpreviewable input, 2071 form.customize-unpreviewable select, 2072 form.customize-unpreviewable button, 2073 a.customize-unpreviewable, 2074 area.customize-unpreviewable { 2075 cursor: not-allowed !important; 2076 } 2077 </style> 2078 <?php 2079 } 2080 2081 /** 2082 * Removes customize_messenger_channel query parameter from the preview window when it is not in an iframe. 2083 * 2084 * This ensures that the admin bar will be shown. It also ensures that link navigation will 2085 * work as expected since the parent frame is not being sent the URL to navigate to. 2086 * 2087 * @since 4.7.0 2088 */ 2089 public function remove_frameless_preview_messenger_channel() { 2090 if ( ! $this->messenger_channel ) { 2091 return; 2092 } 2093 ob_start(); 2094 ?> 2095 <script> 2096 ( function() { 2097 if ( parent !== window ) { 2098 return; 2099 } 2100 const url = new URL( location.href ); 2101 if ( url.searchParams.has( 'customize_messenger_channel' ) ) { 2102 url.searchParams.delete( 'customize_messenger_channel' ); 2103 location.replace( url ); 2104 } 2105 } )(); 2106 </script> 2107 <?php 2108 wp_print_inline_script_tag( wp_remove_surrounding_empty_script_tags( ob_get_clean() ) . "\n//# sourceURL=" . rawurlencode( __METHOD__ ) ); 2109 } 2110 2111 /** 2112 * Prints JavaScript settings for preview frame. 2113 * 2114 * @since 3.4.0 2115 */ 2116 public function customize_preview_settings() { 2117 $post_values = $this->unsanitized_post_values( array( 'exclude_changeset' => true ) ); 2118 $setting_validities = $this->validate_setting_values( $post_values ); 2119 $exported_setting_validities = array_map( array( $this, 'prepare_setting_validity_for_js' ), $setting_validities ); 2120 2121 // Note that the REQUEST_URI is not passed into home_url() since this breaks subdirectory installations. 2122 $self_url = empty( $_SERVER['REQUEST_URI'] ) ? home_url( '/' ) : sanitize_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ); 2123 $state_query_params = array( 2124 'customize_theme', 2125 'customize_changeset_uuid', 2126 'customize_messenger_channel', 2127 ); 2128 $self_url = remove_query_arg( $state_query_params, $self_url ); 2129 2130 $allowed_urls = $this->get_allowed_urls(); 2131 $allowed_hosts = array(); 2132 foreach ( $allowed_urls as $allowed_url ) { 2133 $parsed = wp_parse_url( $allowed_url ); 2134 if ( empty( $parsed['host'] ) ) { 2135 continue; 2136 } 2137 $host = $parsed['host']; 2138 if ( ! empty( $parsed['port'] ) ) { 2139 $host .= ':' . $parsed['port']; 2140 } 2141 $allowed_hosts[] = $host; 2142 } 2143 2144 $switched_locale = switch_to_user_locale( get_current_user_id() ); 2145 $l10n = array( 2146 'shiftClickToEdit' => __( 'Shift-click to edit this element.' ), 2147 'linkUnpreviewable' => __( 'This link is not live-previewable.' ), 2148 'formUnpreviewable' => __( 'This form is not live-previewable.' ), 2149 ); 2150 if ( $switched_locale ) { 2151 restore_previous_locale(); 2152 } 2153 2154 $settings = array( 2155 'changeset' => array( 2156 'uuid' => $this->changeset_uuid(), 2157 'autosaved' => $this->autosaved(), 2158 ), 2159 'timeouts' => array( 2160 'selectiveRefresh' => 250, 2161 'keepAliveSend' => 1000, 2162 ), 2163 'theme' => array( 2164 'stylesheet' => $this->get_stylesheet(), 2165 'active' => $this->is_theme_active(), 2166 'isBlockTheme' => wp_is_block_theme(), 2167 ), 2168 'url' => array( 2169 'self' => $self_url, 2170 'allowed' => array_map( 'sanitize_url', $this->get_allowed_urls() ), 2171 'allowedHosts' => array_unique( $allowed_hosts ), 2172 'isCrossDomain' => $this->is_cross_domain(), 2173 ), 2174 'channel' => $this->messenger_channel, 2175 'activePanels' => array(), 2176 'activeSections' => array(), 2177 'activeControls' => array(), 2178 'settingValidities' => $exported_setting_validities, 2179 'nonce' => current_user_can( 'customize' ) ? $this->get_nonces() : array(), 2180 'l10n' => $l10n, 2181 '_dirty' => array_keys( $post_values ), 2182 ); 2183 2184 foreach ( $this->panels as $panel_id => $panel ) { 2185 if ( $panel->check_capabilities() ) { 2186 $settings['activePanels'][ $panel_id ] = $panel->active(); 2187 foreach ( $panel->sections as $section_id => $section ) { 2188 if ( $section->check_capabilities() ) { 2189 $settings['activeSections'][ $section_id ] = $section->active(); 2190 } 2191 } 2192 } 2193 } 2194 foreach ( $this->sections as $id => $section ) { 2195 if ( $section->check_capabilities() ) { 2196 $settings['activeSections'][ $id ] = $section->active(); 2197 } 2198 } 2199 foreach ( $this->controls as $id => $control ) { 2200 if ( $control->check_capabilities() ) { 2201 $settings['activeControls'][ $id ] = $control->active(); 2202 } 2203 } 2204 2205 ob_start(); 2206 ?> 2207 <script> 2208 var _wpCustomizeSettings = <?php echo wp_json_encode( $settings, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); ?>; 2209 _wpCustomizeSettings.values = {}; 2210 (function( v ) { 2211 <?php 2212 /* 2213 * Serialize settings separately from the initial _wpCustomizeSettings 2214 * serialization in order to avoid a peak memory usage spike. 2215 * @todo We may not even need to export the values at all since the pane syncs them anyway. 2216 */ 2217 foreach ( $this->settings as $id => $setting ) { 2218 if ( $setting->check_capabilities() ) { 2219 printf( 2220 "v[%s] = %s;\n", 2221 wp_json_encode( $id, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ), 2222 wp_json_encode( $setting->js_value(), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ) 2223 ); 2224 } 2225 } 2226 ?> 2227 })( _wpCustomizeSettings.values ); 2228 </script> 2229 <?php 2230 wp_print_inline_script_tag( wp_remove_surrounding_empty_script_tags( ob_get_clean() ) . "\n//# sourceURL=" . rawurlencode( __METHOD__ ) ); 2231 } 2232 2233 /** 2234 * Prints a signature so we can ensure the Customizer was properly executed. 2235 * 2236 * @since 3.4.0 2237 * @deprecated 4.7.0 2238 */ 2239 public function customize_preview_signature() { 2240 _deprecated_function( __METHOD__, '4.7.0' ); 2241 } 2242 2243 /** 2244 * Removes the signature in case we experience a case where the Customizer was not properly executed. 2245 * 2246 * @since 3.4.0 2247 * @deprecated 4.7.0 2248 * 2249 * @param callable|null $callback Optional. Value passed through for {@see 'wp_die_handler'} filter. 2250 * Default null. 2251 * @return callable|null Value passed through for {@see 'wp_die_handler'} filter. 2252 */ 2253 public function remove_preview_signature( $callback = null ) { 2254 _deprecated_function( __METHOD__, '4.7.0' ); 2255 2256 return $callback; 2257 } 2258 2259 /** 2260 * Determines whether it is a theme preview or not. 2261 * 2262 * @since 3.4.0 2263 * 2264 * @return bool True if it's a preview, false if not. 2265 */ 2266 public function is_preview() { 2267 return (bool) $this->previewing; 2268 } 2269 2270 /** 2271 * Retrieves the template name of the previewed theme. 2272 * 2273 * @since 3.4.0 2274 * 2275 * @return string Template name. 2276 */ 2277 public function get_template() { 2278 return $this->theme()->get_template(); 2279 } 2280 2281 /** 2282 * Retrieves the stylesheet name of the previewed theme. 2283 * 2284 * @since 3.4.0 2285 * 2286 * @return string Stylesheet name. 2287 */ 2288 public function get_stylesheet() { 2289 return $this->theme()->get_stylesheet(); 2290 } 2291 2292 /** 2293 * Retrieves the template root of the previewed theme. 2294 * 2295 * @since 3.4.0 2296 * 2297 * @return string Theme root. 2298 */ 2299 public function get_template_root() { 2300 return get_raw_theme_root( $this->get_template(), true ); 2301 } 2302 2303 /** 2304 * Retrieves the stylesheet root of the previewed theme. 2305 * 2306 * @since 3.4.0 2307 * 2308 * @return string Theme root. 2309 */ 2310 public function get_stylesheet_root() { 2311 return get_raw_theme_root( $this->get_stylesheet(), true ); 2312 } 2313 2314 /** 2315 * Filters the active theme and return the name of the previewed theme. 2316 * 2317 * @since 3.4.0 2318 * 2319 * @param mixed $current_theme {@internal Parameter is not used} 2320 * @return string Theme name. 2321 */ 2322 public function current_theme( $current_theme ) { 2323 return $this->theme()->display( 'Name' ); 2324 } 2325 2326 /** 2327 * Validates setting values. 2328 * 2329 * Validation is skipped for unregistered settings or for values that are 2330 * already null since they will be skipped anyway. Sanitization is applied 2331 * to values that pass validation, and values that become null or `WP_Error` 2332 * after sanitizing are marked invalid. 2333 * 2334 * @since 4.6.0 2335 * 2336 * @see WP_REST_Request::has_valid_params() 2337 * @see WP_Customize_Setting::validate() 2338 * 2339 * @param array $setting_values Mapping of setting IDs to values to validate and sanitize. 2340 * @param array $options { 2341 * Options. 2342 * 2343 * @type bool $validate_existence Whether a setting's existence will be checked. 2344 * @type bool $validate_capability Whether the setting capability will be checked. 2345 * } 2346 * @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`. 2347 */ 2348 public function validate_setting_values( $setting_values, $options = array() ) { 2349 $options = wp_parse_args( 2350 $options, 2351 array( 2352 'validate_capability' => false, 2353 'validate_existence' => false, 2354 ) 2355 ); 2356 2357 $validities = array(); 2358 foreach ( $setting_values as $setting_id => $unsanitized_value ) { 2359 $setting = $this->get_setting( $setting_id ); 2360 if ( ! $setting ) { 2361 if ( $options['validate_existence'] ) { 2362 $validities[ $setting_id ] = new WP_Error( 'unrecognized', __( 'Setting does not exist or is unrecognized.' ) ); 2363 } 2364 continue; 2365 } 2366 if ( $options['validate_capability'] && ! current_user_can( $setting->capability ) ) { 2367 $validity = new WP_Error( 'unauthorized', __( 'Unauthorized to modify setting due to capability.' ) ); 2368 } else { 2369 if ( is_null( $unsanitized_value ) ) { 2370 continue; 2371 } 2372 $validity = $setting->validate( $unsanitized_value ); 2373 } 2374 if ( ! is_wp_error( $validity ) ) { 2375 /** This filter is documented in wp-includes/class-wp-customize-setting.php */ 2376 $late_validity = apply_filters( "customize_validate_{$setting->id}", new WP_Error(), $unsanitized_value, $setting ); 2377 if ( is_wp_error( $late_validity ) && $late_validity->has_errors() ) { 2378 $validity = $late_validity; 2379 } 2380 } 2381 if ( ! is_wp_error( $validity ) ) { 2382 $value = $setting->sanitize( $unsanitized_value ); 2383 if ( is_null( $value ) ) { 2384 $validity = false; 2385 } elseif ( is_wp_error( $value ) ) { 2386 $validity = $value; 2387 } 2388 } 2389 if ( false === $validity ) { 2390 $validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) ); 2391 } 2392 $validities[ $setting_id ] = $validity; 2393 } 2394 return $validities; 2395 } 2396 2397 /** 2398 * Prepares setting validity for exporting to the client (JS). 2399 * 2400 * Converts `WP_Error` instance into array suitable for passing into the 2401 * `wp.customize.Notification` JS model. 2402 * 2403 * @since 4.6.0 2404 * 2405 * @param true|WP_Error $validity Setting validity. 2406 * @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped 2407 * to their respective `message` and `data` to pass into the 2408 * `wp.customize.Notification` JS model. 2409 */ 2410 public function prepare_setting_validity_for_js( $validity ) { 2411 if ( is_wp_error( $validity ) ) { 2412 $notification = array(); 2413 foreach ( $validity->errors as $error_code => $error_messages ) { 2414 $notification[ $error_code ] = array( 2415 'message' => implode( ' ', $error_messages ), 2416 'data' => $validity->get_error_data( $error_code ), 2417 ); 2418 } 2419 return $notification; 2420 } else { 2421 return true; 2422 } 2423 } 2424 2425 /** 2426 * Handles customize_save WP Ajax request to save/update a changeset. 2427 * 2428 * @since 3.4.0 2429 * @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes. 2430 * 2431 * @return never 2432 */ 2433 public function save() { 2434 if ( ! is_user_logged_in() ) { 2435 wp_send_json_error( 'unauthenticated' ); 2436 } 2437 2438 if ( ! $this->is_preview() ) { 2439 wp_send_json_error( 'not_preview' ); 2440 } 2441 2442 $action = 'save-customize_' . $this->get_stylesheet(); 2443 if ( ! check_ajax_referer( $action, 'nonce', false ) ) { 2444 wp_send_json_error( 'invalid_nonce' ); 2445 } 2446 2447 $changeset_post_id = $this->changeset_post_id(); 2448 $is_new_changeset = empty( $changeset_post_id ); 2449 if ( $is_new_changeset ) { 2450 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) { 2451 wp_send_json_error( 'cannot_create_changeset_post' ); 2452 } 2453 } else { 2454 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { 2455 wp_send_json_error( 'cannot_edit_changeset_post' ); 2456 } 2457 } 2458 2459 if ( ! empty( $_POST['customize_changeset_data'] ) ) { 2460 $input_changeset_data = json_decode( wp_unslash( $_POST['customize_changeset_data'] ), true ); 2461 if ( ! is_array( $input_changeset_data ) ) { 2462 wp_send_json_error( 'invalid_customize_changeset_data' ); 2463 } 2464 } else { 2465 $input_changeset_data = array(); 2466 } 2467 2468 // Validate title. 2469 $changeset_title = null; 2470 if ( isset( $_POST['customize_changeset_title'] ) ) { 2471 $changeset_title = sanitize_text_field( wp_unslash( $_POST['customize_changeset_title'] ) ); 2472 } 2473 2474 // Validate changeset status param. 2475 $is_publish = null; 2476 $changeset_status = null; 2477 if ( isset( $_POST['customize_changeset_status'] ) ) { 2478 $changeset_status = wp_unslash( $_POST['customize_changeset_status'] ); 2479 if ( ! get_post_status_object( $changeset_status ) || ! in_array( $changeset_status, array( 'draft', 'pending', 'publish', 'future' ), true ) ) { 2480 wp_send_json_error( 'bad_customize_changeset_status', 400 ); 2481 } 2482 $is_publish = ( 'publish' === $changeset_status || 'future' === $changeset_status ); 2483 if ( $is_publish && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) { 2484 wp_send_json_error( 'changeset_publish_unauthorized', 403 ); 2485 } 2486 } 2487 2488 /* 2489 * Validate changeset date param. Date is assumed to be in local time for 2490 * the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date 2491 * is parsed with strtotime() so that ISO date format may be supplied 2492 * or a string like "+10 minutes". 2493 */ 2494 $changeset_date_gmt = null; 2495 if ( isset( $_POST['customize_changeset_date'] ) ) { 2496 $changeset_date = wp_unslash( $_POST['customize_changeset_date'] ); 2497 if ( preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $changeset_date ) ) { 2498 $mm = substr( $changeset_date, 5, 2 ); 2499 $jj = substr( $changeset_date, 8, 2 ); 2500 $aa = substr( $changeset_date, 0, 4 ); 2501 $valid_date = wp_checkdate( $mm, $jj, $aa, $changeset_date ); 2502 if ( ! $valid_date ) { 2503 wp_send_json_error( 'bad_customize_changeset_date', 400 ); 2504 } 2505 $changeset_date_gmt = get_gmt_from_date( $changeset_date ); 2506 } else { 2507 $timestamp = strtotime( $changeset_date ); 2508 if ( ! $timestamp ) { 2509 wp_send_json_error( 'bad_customize_changeset_date', 400 ); 2510 } 2511 $changeset_date_gmt = gmdate( 'Y-m-d H:i:s', $timestamp ); 2512 } 2513 } 2514 2515 $lock_user_id = null; 2516 $autosave = ! empty( $_POST['customize_changeset_autosave'] ); 2517 if ( ! $is_new_changeset ) { 2518 $lock_user_id = wp_check_post_lock( $this->changeset_post_id() ); 2519 } 2520 2521 // Force request to autosave when changeset is locked. 2522 if ( $lock_user_id && ! $autosave ) { 2523 $autosave = true; 2524 $changeset_status = null; 2525 $changeset_date_gmt = null; 2526 } 2527 2528 if ( $autosave && ! defined( 'DOING_AUTOSAVE' ) ) { // Back-compat. 2529 define( 'DOING_AUTOSAVE', true ); 2530 } 2531 2532 $autosaved = false; 2533 $r = $this->save_changeset_post( 2534 array( 2535 'status' => $changeset_status, 2536 'title' => $changeset_title, 2537 'date_gmt' => $changeset_date_gmt, 2538 'data' => $input_changeset_data, 2539 'autosave' => $autosave, 2540 ) 2541 ); 2542 if ( $autosave && ! is_wp_error( $r ) ) { 2543 $autosaved = true; 2544 } 2545 2546 // If the changeset was locked and an autosave request wasn't itself an error, then now explicitly return with a failure. 2547 if ( $lock_user_id && ! is_wp_error( $r ) ) { 2548 $r = new WP_Error( 2549 'changeset_locked', 2550 __( 'Changeset is being edited by other user.' ), 2551 array( 2552 'lock_user' => $this->get_lock_user_data( $lock_user_id ), 2553 ) 2554 ); 2555 } 2556 2557 if ( is_wp_error( $r ) ) { 2558 $response = array( 2559 'message' => $r->get_error_message(), 2560 'code' => $r->get_error_code(), 2561 ); 2562 if ( is_array( $r->get_error_data() ) ) { 2563 $response = array_merge( $response, $r->get_error_data() ); 2564 } else { 2565 $response['data'] = $r->get_error_data(); 2566 } 2567 } else { 2568 $response = $r; 2569 $changeset_post = get_post( $this->changeset_post_id() ); 2570 2571 // Dismiss all other auto-draft changeset posts for this user (they serve like autosave revisions), as there should only be one. 2572 if ( $is_new_changeset ) { 2573 $this->dismiss_user_auto_draft_changesets(); 2574 } 2575 2576 // Note that if the changeset status was publish, then it will get set to Trash if revisions are not supported. 2577 $response['changeset_status'] = $changeset_post->post_status; 2578 if ( $is_publish && 'trash' === $response['changeset_status'] ) { 2579 $response['changeset_status'] = 'publish'; 2580 } 2581 2582 if ( 'publish' !== $response['changeset_status'] ) { 2583 $this->set_changeset_lock( $changeset_post->ID ); 2584 } 2585 2586 if ( 'future' === $response['changeset_status'] ) { 2587 $response['changeset_date'] = $changeset_post->post_date; 2588 } 2589 2590 if ( 'publish' === $response['changeset_status'] || 'trash' === $response['changeset_status'] ) { 2591 $response['next_changeset_uuid'] = wp_generate_uuid4(); 2592 } 2593 } 2594 2595 if ( $autosave ) { 2596 $response['autosaved'] = $autosaved; 2597 } 2598 2599 if ( isset( $response['setting_validities'] ) ) { 2600 $response['setting_validities'] = array_map( array( $this, 'prepare_setting_validity_for_js' ), $response['setting_validities'] ); 2601 } 2602 2603 /** 2604 * Filters response data for a successful customize_save Ajax request. 2605 * 2606 * This filter does not apply if there was a nonce or authentication failure. 2607 * 2608 * @since 4.2.0 2609 * 2610 * @param array $response Additional information passed back to the 'saved' 2611 * event on `wp.customize`. 2612 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 2613 */ 2614 $response = apply_filters( 'customize_save_response', $response, $this ); 2615 2616 if ( is_wp_error( $r ) ) { 2617 wp_send_json_error( $response ); 2618 } else { 2619 wp_send_json_success( $response ); 2620 } 2621 } 2622 2623 /** 2624 * Saves the post for the loaded changeset. 2625 * 2626 * @since 4.7.0 2627 * 2628 * @param array $args { 2629 * Args for changeset post. 2630 * 2631 * @type array $data Optional additional changeset data. Values will be merged on top of any existing post values. 2632 * @type string $status Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed. 2633 * @type string $title Post title. Optional. 2634 * @type string $date_gmt Date in GMT. Optional. 2635 * @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID. 2636 * @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved. 2637 * @type bool $autosave Whether this is a request to create an autosave revision. 2638 * } 2639 * 2640 * @return array|WP_Error Returns array on success and WP_Error with array data on error. 2641 */ 2642 public function save_changeset_post( $args = array() ) { 2643 2644 $args = array_merge( 2645 array( 2646 'status' => null, 2647 'title' => null, 2648 'data' => array(), 2649 'date_gmt' => null, 2650 'user_id' => get_current_user_id(), 2651 'starter_content' => false, 2652 'autosave' => false, 2653 ), 2654 $args 2655 ); 2656 2657 $changeset_post_id = $this->changeset_post_id(); 2658 $existing_changeset_data = array(); 2659 if ( $changeset_post_id ) { 2660 $existing_status = get_post_status( $changeset_post_id ); 2661 if ( 'publish' === $existing_status || 'trash' === $existing_status ) { 2662 return new WP_Error( 2663 'changeset_already_published', 2664 __( 'The previous set of changes has already been published. Please try saving your current set of changes again.' ), 2665 array( 2666 'next_changeset_uuid' => wp_generate_uuid4(), 2667 ) 2668 ); 2669 } 2670 2671 $existing_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); 2672 if ( is_wp_error( $existing_changeset_data ) ) { 2673 return $existing_changeset_data; 2674 } 2675 } 2676 2677 // Fail if attempting to publish but publish hook is missing. 2678 if ( 'publish' === $args['status'] && false === has_action( 'transition_post_status', '_wp_customize_publish_changeset' ) ) { 2679 return new WP_Error( 'missing_publish_callback' ); 2680 } 2681 2682 // Validate date. 2683 $now = gmdate( 'Y-m-d H:i:59' ); 2684 if ( $args['date_gmt'] ) { 2685 $is_future_dated = ( mysql2date( 'U', $args['date_gmt'], false ) > mysql2date( 'U', $now, false ) ); 2686 if ( ! $is_future_dated ) { 2687 return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); // Only future dates are allowed. 2688 } 2689 2690 if ( ! $this->is_theme_active() && ( 'future' === $args['status'] || $is_future_dated ) ) { 2691 return new WP_Error( 'cannot_schedule_theme_switches' ); // This should be allowed in the future, when theme is a regular setting. 2692 } 2693 $will_remain_auto_draft = ( ! $args['status'] && ( ! $changeset_post_id || 'auto-draft' === get_post_status( $changeset_post_id ) ) ); 2694 if ( $will_remain_auto_draft ) { 2695 return new WP_Error( 'cannot_supply_date_for_auto_draft_changeset' ); 2696 } 2697 } elseif ( $changeset_post_id && 'future' === $args['status'] ) { 2698 2699 // Fail if the new status is future but the existing post's date is not in the future. 2700 $changeset_post = get_post( $changeset_post_id ); 2701 if ( mysql2date( 'U', $changeset_post->post_date_gmt, false ) <= mysql2date( 'U', $now, false ) ) { 2702 return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); 2703 } 2704 } 2705 2706 if ( ! empty( $is_future_dated ) && 'publish' === $args['status'] ) { 2707 $args['status'] = 'future'; 2708 } 2709 2710 // Validate autosave param. See _wp_post_revision_fields() for why these fields are disallowed. 2711 if ( $args['autosave'] ) { 2712 if ( $args['date_gmt'] ) { 2713 return new WP_Error( 'illegal_autosave_with_date_gmt' ); 2714 } elseif ( $args['status'] ) { 2715 return new WP_Error( 'illegal_autosave_with_status' ); 2716 } elseif ( $args['user_id'] && get_current_user_id() !== $args['user_id'] ) { 2717 return new WP_Error( 'illegal_autosave_with_non_current_user' ); 2718 } 2719 } 2720 2721 // The request was made via wp.customize.previewer.save(). 2722 $update_transactionally = (bool) $args['status']; 2723 $allow_revision = (bool) $args['status']; 2724 2725 // Amend post values with any supplied data. 2726 foreach ( $args['data'] as $setting_id => $setting_params ) { 2727 if ( is_array( $setting_params ) && array_key_exists( 'value', $setting_params ) ) { 2728 $this->set_post_value( $setting_id, $setting_params['value'] ); // Add to post values so that they can be validated and sanitized. 2729 } 2730 } 2731 2732 // Note that in addition to post data, this will include any stashed theme mods. 2733 $post_values = $this->unsanitized_post_values( 2734 array( 2735 'exclude_changeset' => true, 2736 'exclude_post_data' => false, 2737 ) 2738 ); 2739 $this->add_dynamic_settings( array_keys( $post_values ) ); // Ensure settings get created even if they lack an input value. 2740 2741 /* 2742 * Get list of IDs for settings that have values different from what is currently 2743 * saved in the changeset. By skipping any values that are already the same, the 2744 * subset of changed settings can be passed into validate_setting_values to prevent 2745 * an underprivileged modifying a single setting for which they have the capability 2746 * from being blocked from saving. This also prevents a user from touching of the 2747 * previous saved settings and overriding the associated user_id if they made no change. 2748 */ 2749 $changed_setting_ids = array(); 2750 foreach ( $post_values as $setting_id => $setting_value ) { 2751 $setting = $this->get_setting( $setting_id ); 2752 2753 if ( $setting && 'theme_mod' === $setting->type ) { 2754 $prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id; 2755 } else { 2756 $prefixed_setting_id = $setting_id; 2757 } 2758 2759 $is_value_changed = ( 2760 ! isset( $existing_changeset_data[ $prefixed_setting_id ] ) 2761 || 2762 ! array_key_exists( 'value', $existing_changeset_data[ $prefixed_setting_id ] ) 2763 || 2764 $existing_changeset_data[ $prefixed_setting_id ]['value'] !== $setting_value 2765 ); 2766 if ( $is_value_changed ) { 2767 $changed_setting_ids[] = $setting_id; 2768 } 2769 } 2770 2771 /** 2772 * Fires before save validation happens. 2773 * 2774 * Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters 2775 * at this point to catch any settings registered after `customize_register`. 2776 * The dynamic portion of the hook name, `$this->ID` refers to the setting ID. 2777 * 2778 * @since 4.6.0 2779 * 2780 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 2781 */ 2782 do_action( 'customize_save_validation_before', $this ); 2783 2784 // Validate settings. 2785 $validated_values = array_merge( 2786 array_fill_keys( array_keys( $args['data'] ), null ), // Make sure existence/capability checks are done on value-less setting updates. 2787 $post_values 2788 ); 2789 $setting_validities = $this->validate_setting_values( 2790 $validated_values, 2791 array( 2792 'validate_capability' => true, 2793 'validate_existence' => true, 2794 ) 2795 ); 2796 $invalid_setting_count = count( array_filter( $setting_validities, 'is_wp_error' ) ); 2797 2798 /* 2799 * Short-circuit if there are invalid settings the update is transactional. 2800 * A changeset update is transactional when a status is supplied in the request. 2801 */ 2802 if ( $update_transactionally && $invalid_setting_count > 0 ) { 2803 $response = array( 2804 'setting_validities' => $setting_validities, 2805 /* translators: %s: Number of invalid settings. */ 2806 'message' => sprintf( _n( 'Unable to save due to %s invalid setting.', 'Unable to save due to %s invalid settings.', $invalid_setting_count ), number_format_i18n( $invalid_setting_count ) ), 2807 ); 2808 return new WP_Error( 'transaction_fail', '', $response ); 2809 } 2810 2811 // Obtain/merge data for changeset. 2812 $original_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); 2813 $data = $original_changeset_data; 2814 if ( is_wp_error( $data ) ) { 2815 $data = array(); 2816 } 2817 2818 // Ensure that all post values are included in the changeset data. 2819 foreach ( $post_values as $setting_id => $post_value ) { 2820 if ( ! isset( $args['data'][ $setting_id ] ) ) { 2821 $args['data'][ $setting_id ] = array(); 2822 } 2823 if ( ! isset( $args['data'][ $setting_id ]['value'] ) ) { 2824 $args['data'][ $setting_id ]['value'] = $post_value; 2825 } 2826 } 2827 2828 foreach ( $args['data'] as $setting_id => $setting_params ) { 2829 $setting = $this->get_setting( $setting_id ); 2830 if ( ! $setting || ! $setting->check_capabilities() ) { 2831 continue; 2832 } 2833 2834 // Skip updating changeset for invalid setting values. 2835 if ( isset( $setting_validities[ $setting_id ] ) && is_wp_error( $setting_validities[ $setting_id ] ) ) { 2836 continue; 2837 } 2838 2839 $changeset_setting_id = $setting_id; 2840 if ( 'theme_mod' === $setting->type ) { 2841 $changeset_setting_id = sprintf( '%s::%s', $this->get_stylesheet(), $setting_id ); 2842 } 2843 2844 if ( null === $setting_params ) { 2845 // Remove setting from changeset entirely. 2846 unset( $data[ $changeset_setting_id ] ); 2847 } else { 2848 2849 if ( ! isset( $data[ $changeset_setting_id ] ) ) { 2850 $data[ $changeset_setting_id ] = array(); 2851 } 2852 2853 // Merge any additional setting params that have been supplied with the existing params. 2854 $merged_setting_params = array_merge( $data[ $changeset_setting_id ], $setting_params ); 2855 2856 // Skip updating setting params if unchanged (ensuring the user_id is not overwritten). 2857 if ( $data[ $changeset_setting_id ] === $merged_setting_params ) { 2858 continue; 2859 } 2860 2861 $data[ $changeset_setting_id ] = array_merge( 2862 $merged_setting_params, 2863 array( 2864 'type' => $setting->type, 2865 'user_id' => $args['user_id'], 2866 'date_modified_gmt' => current_time( 'mysql', true ), 2867 ) 2868 ); 2869 2870 // Clear starter_content flag in data if changeset is not explicitly being updated for starter content. 2871 if ( empty( $args['starter_content'] ) ) { 2872 unset( $data[ $changeset_setting_id ]['starter_content'] ); 2873 } 2874 } 2875 } 2876 2877 $filter_context = array( 2878 'uuid' => $this->changeset_uuid(), 2879 'title' => $args['title'], 2880 'status' => $args['status'], 2881 'date_gmt' => $args['date_gmt'], 2882 'post_id' => $changeset_post_id, 2883 'previous_data' => is_wp_error( $original_changeset_data ) ? array() : $original_changeset_data, 2884 'manager' => $this, 2885 ); 2886 2887 /** 2888 * Filters the settings' data that will be persisted into the changeset. 2889 * 2890 * Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter. 2891 * 2892 * @since 4.7.0 2893 * 2894 * @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata. 2895 * @param array $context { 2896 * Filter context. 2897 * 2898 * @type string $uuid Changeset UUID. 2899 * @type string $title Requested title for the changeset post. 2900 * @type string $status Requested status for the changeset post. 2901 * @type string $date_gmt Requested date for the changeset post in MySQL format and GMT timezone. 2902 * @type int|false $post_id Post ID for the changeset, or false if it doesn't exist yet. 2903 * @type array $previous_data Previous data contained in the changeset. 2904 * @type WP_Customize_Manager $manager Manager instance. 2905 * } 2906 */ 2907 $data = apply_filters( 'customize_changeset_save_data', $data, $filter_context ); 2908 2909 // Switch theme if publishing changes now. 2910 if ( 'publish' === $args['status'] && ! $this->is_theme_active() ) { 2911 // Temporarily stop previewing the theme to allow switch_themes() to operate properly. 2912 $this->stop_previewing_theme(); 2913 switch_theme( $this->get_stylesheet() ); 2914 update_option( 'theme_switched_via_customizer', true ); 2915 $this->start_previewing_theme(); 2916 } 2917 2918 // Gather the data for wp_insert_post()/wp_update_post(). 2919 $post_array = array( 2920 // JSON_UNESCAPED_SLASHES is only to improve readability as slashes needn't be escaped in storage. 2921 'post_content' => wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ), 2922 ); 2923 if ( $args['title'] ) { 2924 $post_array['post_title'] = $args['title']; 2925 } 2926 if ( $changeset_post_id ) { 2927 $post_array['ID'] = $changeset_post_id; 2928 } else { 2929 $post_array['post_type'] = 'customize_changeset'; 2930 $post_array['post_name'] = $this->changeset_uuid(); 2931 $post_array['post_status'] = 'auto-draft'; 2932 } 2933 if ( $args['status'] ) { 2934 $post_array['post_status'] = $args['status']; 2935 } 2936 2937 // Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date. 2938 if ( 'publish' === $args['status'] ) { 2939 $post_array['post_date_gmt'] = '0000-00-00 00:00:00'; 2940 $post_array['post_date'] = '0000-00-00 00:00:00'; 2941 } elseif ( $args['date_gmt'] ) { 2942 $post_array['post_date_gmt'] = $args['date_gmt']; 2943 $post_array['post_date'] = get_date_from_gmt( $args['date_gmt'] ); 2944 } elseif ( $changeset_post_id && 'auto-draft' === get_post_status( $changeset_post_id ) ) { 2945 /* 2946 * Keep bumping the date for the auto-draft whenever it is modified; 2947 * this extends its life, preserving it from garbage-collection via 2948 * wp_delete_auto_drafts(). 2949 */ 2950 $post_array['post_date'] = current_time( 'mysql' ); 2951 $post_array['post_date_gmt'] = ''; 2952 } 2953 2954 $this->store_changeset_revision = $allow_revision; 2955 add_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ), 5, 3 ); 2956 2957 /* 2958 * Update the changeset post. The publish_customize_changeset action will cause the settings in the 2959 * changeset to be saved via WP_Customize_Setting::save(). Updating a post with publish status will 2960 * trigger WP_Customize_Manager::publish_changeset_values(). 2961 */ 2962 add_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5, 3 ); 2963 if ( $changeset_post_id ) { 2964 if ( $args['autosave'] && 'auto-draft' !== get_post_status( $changeset_post_id ) ) { 2965 // See _wp_translate_postdata() for why this is required as it will use the edit_post meta capability. 2966 add_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10, 4 ); 2967 2968 $post_array['post_ID'] = $post_array['ID']; 2969 $post_array['post_type'] = 'customize_changeset'; 2970 2971 $r = wp_create_post_autosave( wp_slash( $post_array ) ); 2972 2973 remove_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10 ); 2974 } else { 2975 $post_array['edit_date'] = true; // Prevent date clearing. 2976 2977 $r = wp_update_post( wp_slash( $post_array ), true ); 2978 2979 // Delete autosave revision for user when the changeset is updated. 2980 if ( ! empty( $args['user_id'] ) ) { 2981 $autosave_draft = wp_get_post_autosave( $changeset_post_id, $args['user_id'] ); 2982 if ( $autosave_draft ) { 2983 wp_delete_post( $autosave_draft->ID, true ); 2984 } 2985 } 2986 } 2987 } else { 2988 $r = wp_insert_post( wp_slash( $post_array ), true ); 2989 if ( ! is_wp_error( $r ) ) { 2990 $this->_changeset_post_id = $r; // Update cached post ID for the loaded changeset. 2991 } 2992 } 2993 remove_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5 ); 2994 2995 $this->_changeset_data = null; // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents. 2996 2997 remove_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ) ); 2998 2999 $response = array( 3000 'setting_validities' => $setting_validities, 3001 ); 3002 3003 if ( is_wp_error( $r ) ) { 3004 $response['changeset_post_save_failure'] = $r->get_error_code(); 3005 return new WP_Error( 'changeset_post_save_failure', '', $response ); 3006 } 3007 3008 return $response; 3009 } 3010 3011 /** 3012 * Preserves the initial JSON post_content passed to save into the post. 3013 * 3014 * This is needed to prevent KSES and other {@see 'content_save_pre'} filters 3015 * from corrupting JSON data. 3016 * 3017 * Note that WP_Customize_Manager::validate_setting_values() have already 3018 * run on the setting values being serialized as JSON into the post content 3019 * so it is pre-sanitized. 3020 * 3021 * Also, the sanitization logic is re-run through the respective 3022 * WP_Customize_Setting::sanitize() method when being read out of the 3023 * changeset, via WP_Customize_Manager::post_value(), and this sanitized 3024 * value will also be sent into WP_Customize_Setting::update() for 3025 * persisting to the DB. 3026 * 3027 * Multiple users can collaborate on a single changeset, where one user may 3028 * have the unfiltered_html capability but another may not. A user with 3029 * unfiltered_html may add a script tag to some field which needs to be kept 3030 * intact even when another user updates the changeset to modify another field 3031 * when they do not have unfiltered_html. 3032 * 3033 * @since 5.4.1 3034 * 3035 * @param array $data An array of slashed and processed post data. 3036 * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data. 3037 * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as originally passed to wp_insert_post(). 3038 * @return array Filtered post data. 3039 */ 3040 public function preserve_insert_changeset_post_content( $data, $postarr, $unsanitized_postarr ) { 3041 if ( 3042 isset( $data['post_type'] ) && 3043 isset( $unsanitized_postarr['post_content'] ) && 3044 'customize_changeset' === $data['post_type'] || 3045 ( 3046 'revision' === $data['post_type'] && 3047 ! empty( $data['post_parent'] ) && 3048 'customize_changeset' === get_post_type( $data['post_parent'] ) 3049 ) 3050 ) { 3051 $data['post_content'] = $unsanitized_postarr['post_content']; 3052 } 3053 return $data; 3054 } 3055 3056 /** 3057 * Trashes or deletes a changeset post. 3058 * 3059 * The following re-formulates the logic from `wp_trash_post()` as done in 3060 * `wp_publish_post()`. The reason for bypassing `wp_trash_post()` is that it 3061 * will mutate the `post_content` and the `post_name` when they should be 3062 * untouched. 3063 * 3064 * @since 4.9.0 3065 * 3066 * @see wp_trash_post() 3067 * @global wpdb $wpdb WordPress database abstraction object. 3068 * 3069 * @param int|WP_Post $post The changeset post. 3070 * @return mixed A WP_Post object for the trashed post or an empty value on failure. 3071 */ 3072 public function trash_changeset_post( $post ) { 3073 global $wpdb; 3074 3075 $post = get_post( $post ); 3076 3077 if ( ! ( $post instanceof WP_Post ) ) { 3078 return $post; 3079 } 3080 $post_id = $post->ID; 3081 3082 if ( ! EMPTY_TRASH_DAYS ) { 3083 return wp_delete_post( $post_id, true ); 3084 } 3085 3086 if ( 'trash' === get_post_status( $post ) ) { 3087 return false; 3088 } 3089 3090 $previous_status = $post->post_status; 3091 3092 /** This filter is documented in wp-includes/post.php */ 3093 $check = apply_filters( 'pre_trash_post', null, $post, $previous_status ); 3094 if ( null !== $check ) { 3095 return $check; 3096 } 3097 3098 /** This action is documented in wp-includes/post.php */ 3099 do_action( 'wp_trash_post', $post_id, $previous_status ); 3100 3101 add_post_meta( $post_id, '_wp_trash_meta_status', $previous_status ); 3102 add_post_meta( $post_id, '_wp_trash_meta_time', time() ); 3103 3104 $new_status = 'trash'; 3105 $wpdb->update( $wpdb->posts, array( 'post_status' => $new_status ), array( 'ID' => $post->ID ) ); 3106 clean_post_cache( $post->ID ); 3107 3108 $post->post_status = $new_status; 3109 wp_transition_post_status( $new_status, $previous_status, $post ); 3110 3111 /** This action is documented in wp-includes/post.php */ 3112 do_action( "edit_post_{$post->post_type}", $post->ID, $post ); 3113 3114 /** This action is documented in wp-includes/post.php */ 3115 do_action( 'edit_post', $post->ID, $post ); 3116 3117 /** This action is documented in wp-includes/post.php */ 3118 do_action( "save_post_{$post->post_type}", $post->ID, $post, true ); 3119 3120 /** This action is documented in wp-includes/post.php */ 3121 do_action( 'save_post', $post->ID, $post, true ); 3122 3123 /** This action is documented in wp-includes/post.php */ 3124 do_action( 'wp_insert_post', $post->ID, $post, true ); 3125 3126 wp_after_insert_post( get_post( $post_id ), true, $post ); 3127 3128 wp_trash_post_comments( $post_id ); 3129 3130 /** This action is documented in wp-includes/post.php */ 3131 do_action( 'trashed_post', $post_id, $previous_status ); 3132 3133 return $post; 3134 } 3135 3136 /** 3137 * Handles request to trash a changeset. 3138 * 3139 * @since 4.9.0 3140 */ 3141 public function handle_changeset_trash_request() { 3142 if ( ! is_user_logged_in() ) { 3143 wp_send_json_error( 'unauthenticated' ); 3144 } 3145 3146 if ( ! $this->is_preview() ) { 3147 wp_send_json_error( 'not_preview' ); 3148 } 3149 3150 if ( ! check_ajax_referer( 'trash_customize_changeset', 'nonce', false ) ) { 3151 wp_send_json_error( 3152 array( 3153 'code' => 'invalid_nonce', 3154 'message' => __( 'There was an authentication problem. Please reload and try again.' ), 3155 ) 3156 ); 3157 } 3158 3159 $changeset_post_id = $this->changeset_post_id(); 3160 3161 if ( ! $changeset_post_id ) { 3162 wp_send_json_error( 3163 array( 3164 'message' => __( 'No changes saved yet, so there is nothing to trash.' ), 3165 'code' => 'non_existent_changeset', 3166 ) 3167 ); 3168 } 3169 3170 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) { 3171 wp_send_json_error( 3172 array( 3173 'code' => 'changeset_trash_unauthorized', 3174 'message' => __( 'Unable to trash changes.' ), 3175 ) 3176 ); 3177 } 3178 3179 $lock_user = (int) wp_check_post_lock( $changeset_post_id ); 3180 3181 if ( $lock_user && get_current_user_id() !== $lock_user ) { 3182 wp_send_json_error( 3183 array( 3184 'code' => 'changeset_locked', 3185 'message' => __( 'Changeset is being edited by other user.' ), 3186 'lockUser' => $this->get_lock_user_data( $lock_user ), 3187 ) 3188 ); 3189 } 3190 3191 if ( 'trash' === get_post_status( $changeset_post_id ) ) { 3192 wp_send_json_error( 3193 array( 3194 'message' => __( 'Changes have already been trashed.' ), 3195 'code' => 'changeset_already_trashed', 3196 ) 3197 ); 3198 } 3199 3200 $r = $this->trash_changeset_post( $changeset_post_id ); 3201 if ( ! ( $r instanceof WP_Post ) ) { 3202 wp_send_json_error( 3203 array( 3204 'code' => 'changeset_trash_failure', 3205 'message' => __( 'Unable to trash changes.' ), 3206 ) 3207 ); 3208 } 3209 3210 wp_send_json_success( 3211 array( 3212 'message' => __( 'Changes trashed successfully.' ), 3213 ) 3214 ); 3215 } 3216 3217 /** 3218 * Re-maps 'edit_post' meta cap for a customize_changeset post to be the same as 'customize' maps. 3219 * 3220 * There is essentially a "meta meta" cap in play here, where 'edit_post' meta cap maps to 3221 * the 'customize' meta cap which then maps to 'edit_theme_options'. This is currently 3222 * required in core for `wp_create_post_autosave()` because it will call 3223 * `_wp_translate_postdata()` which in turn will check if a user can 'edit_post', but the 3224 * the caps for the customize_changeset post type are all mapping to the meta capability. 3225 * This should be able to be removed once #40922 is addressed in core. 3226 * 3227 * @since 4.9.0 3228 * 3229 * @link https://core.trac.wordpress.org/ticket/40922 3230 * @see WP_Customize_Manager::save_changeset_post() 3231 * @see _wp_translate_postdata() 3232 * 3233 * @param string[] $caps Array of the user's capabilities. 3234 * @param string $cap Capability name. 3235 * @param int $user_id The user ID. 3236 * @param array $args Adds the context to the cap. Typically the object ID. 3237 * @return array Capabilities. 3238 */ 3239 public function grant_edit_post_capability_for_changeset( $caps, $cap, $user_id, $args ) { 3240 if ( 'edit_post' === $cap && ! empty( $args[0] ) && 'customize_changeset' === get_post_type( $args[0] ) ) { 3241 $post_type_obj = get_post_type_object( 'customize_changeset' ); 3242 $caps = map_meta_cap( $post_type_obj->cap->$cap, $user_id ); 3243 } 3244 return $caps; 3245 } 3246 3247 /** 3248 * Marks the changeset post as being currently edited by the current user. 3249 * 3250 * @since 4.9.0 3251 * 3252 * @param int $changeset_post_id Changeset post ID. 3253 * @param bool $take_over Whether to take over the changeset. Default false. 3254 */ 3255 public function set_changeset_lock( $changeset_post_id, $take_over = false ) { 3256 if ( $changeset_post_id ) { 3257 $can_override = ! (bool) get_post_meta( $changeset_post_id, '_edit_lock', true ); 3258 3259 if ( $take_over ) { 3260 $can_override = true; 3261 } 3262 3263 if ( $can_override ) { 3264 $lock = sprintf( '%s:%s', time(), get_current_user_id() ); 3265 update_post_meta( $changeset_post_id, '_edit_lock', $lock ); 3266 } else { 3267 $this->refresh_changeset_lock( $changeset_post_id ); 3268 } 3269 } 3270 } 3271 3272 /** 3273 * Refreshes changeset lock with the current time if current user edited the changeset before. 3274 * 3275 * @since 4.9.0 3276 * 3277 * @param int $changeset_post_id Changeset post ID. 3278 */ 3279 public function refresh_changeset_lock( $changeset_post_id ) { 3280 if ( ! $changeset_post_id ) { 3281 return; 3282 } 3283 3284 $lock = get_post_meta( $changeset_post_id, '_edit_lock', true ); 3285 $lock = explode( ':', $lock ); 3286 3287 if ( $lock && ! empty( $lock[1] ) ) { 3288 $user_id = (int) $lock[1]; 3289 $current_user_id = get_current_user_id(); 3290 if ( $user_id === $current_user_id ) { 3291 $lock = sprintf( '%s:%s', time(), $user_id ); 3292 update_post_meta( $changeset_post_id, '_edit_lock', $lock ); 3293 } 3294 } 3295 } 3296 3297 /** 3298 * Filters heartbeat settings for the Customizer. 3299 * 3300 * @since 4.9.0 3301 * 3302 * @global string $pagenow The filename of the current screen. 3303 * 3304 * @param array $settings Current settings to filter. 3305 * @return array Heartbeat settings. 3306 */ 3307 public function add_customize_screen_to_heartbeat_settings( $settings ) { 3308 global $pagenow; 3309 3310 if ( 'customize.php' === $pagenow ) { 3311 $settings['screenId'] = 'customize'; 3312 } 3313 3314 return $settings; 3315 } 3316 3317 /** 3318 * Gets lock user data. 3319 * 3320 * @since 4.9.0 3321 * 3322 * @param int $user_id User ID. 3323 * @return array|null User data formatted for client. 3324 */ 3325 protected function get_lock_user_data( $user_id ) { 3326 if ( ! $user_id ) { 3327 return null; 3328 } 3329 3330 $lock_user = get_userdata( $user_id ); 3331 3332 if ( ! $lock_user ) { 3333 return null; 3334 } 3335 3336 $user_details = array( 3337 'id' => $lock_user->ID, 3338 'name' => $lock_user->display_name, 3339 ); 3340 3341 if ( get_option( 'show_avatars' ) ) { 3342 $user_details['avatar'] = get_avatar_url( $lock_user->ID, array( 'size' => 128 ) ); 3343 } 3344 3345 return $user_details; 3346 } 3347 3348 /** 3349 * Checks locked changeset with heartbeat API. 3350 * 3351 * @since 4.9.0 3352 * 3353 * @param array $response The Heartbeat response. 3354 * @param array $data The $_POST data sent. 3355 * @param string $screen_id The screen id. 3356 * @return array The Heartbeat response. 3357 */ 3358 public function check_changeset_lock_with_heartbeat( $response, $data, $screen_id ) { 3359 if ( isset( $data['changeset_uuid'] ) ) { 3360 $changeset_post_id = $this->find_changeset_post_id( $data['changeset_uuid'] ); 3361 } else { 3362 $changeset_post_id = $this->changeset_post_id(); 3363 } 3364 3365 if ( 3366 array_key_exists( 'check_changeset_lock', $data ) 3367 && 'customize' === $screen_id 3368 && $changeset_post_id 3369 && current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) 3370 ) { 3371 $lock_user_id = wp_check_post_lock( $changeset_post_id ); 3372 3373 if ( $lock_user_id ) { 3374 $response['customize_changeset_lock_user'] = $this->get_lock_user_data( $lock_user_id ); 3375 } else { 3376 3377 // Refreshing time will ensure that the user is sitting on customizer and has not closed the customizer tab. 3378 $this->refresh_changeset_lock( $changeset_post_id ); 3379 } 3380 } 3381 3382 return $response; 3383 } 3384 3385 /** 3386 * Removes changeset lock when take over request is sent via Ajax. 3387 * 3388 * @since 4.9.0 3389 * 3390 * @return never 3391 */ 3392 public function handle_override_changeset_lock_request() { 3393 if ( ! $this->is_preview() ) { 3394 wp_send_json_error( 'not_preview', 400 ); 3395 } 3396 3397 if ( ! check_ajax_referer( 'customize_override_changeset_lock', 'nonce', false ) ) { 3398 wp_send_json_error( 3399 array( 3400 'code' => 'invalid_nonce', 3401 'message' => __( 'Security check failed.' ), 3402 ) 3403 ); 3404 } 3405 3406 $changeset_post_id = $this->changeset_post_id(); 3407 3408 if ( empty( $changeset_post_id ) ) { 3409 wp_send_json_error( 3410 array( 3411 'code' => 'no_changeset_found_to_take_over', 3412 'message' => __( 'No changeset found to take over' ), 3413 ) 3414 ); 3415 } 3416 3417 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { 3418 wp_send_json_error( 3419 array( 3420 'code' => 'cannot_remove_changeset_lock', 3421 'message' => __( 'Sorry, you are not allowed to take over.' ), 3422 ) 3423 ); 3424 } 3425 3426 $this->set_changeset_lock( $changeset_post_id, true ); 3427 3428 wp_send_json_success( 'changeset_taken_over' ); 3429 } 3430 3431 /** 3432 * Determines whether a changeset revision should be made. 3433 * 3434 * @since 4.7.0 3435 * @var bool 3436 */ 3437 protected $store_changeset_revision; 3438 3439 /** 3440 * Filters whether a changeset has changed to create a new revision. 3441 * 3442 * Note that this will not be called while a changeset post remains in auto-draft status. 3443 * 3444 * @since 4.7.0 3445 * 3446 * @param bool $post_has_changed Whether the post has changed. 3447 * @param WP_Post $latest_revision The latest revision post object. 3448 * @param WP_Post $post The post object. 3449 * @return bool Whether a revision should be made. 3450 */ 3451 public function _filter_revision_post_has_changed( $post_has_changed, $latest_revision, $post ) { 3452 unset( $latest_revision ); 3453 if ( 'customize_changeset' === $post->post_type ) { 3454 $post_has_changed = $this->store_changeset_revision; 3455 } 3456 return $post_has_changed; 3457 } 3458 3459 /** 3460 * Publishes the values of a changeset. 3461 * 3462 * This will publish the values contained in a changeset, even changesets that do not 3463 * correspond to current manager instance. This is called by 3464 * `_wp_customize_publish_changeset()` when a customize_changeset post is 3465 * transitioned to the `publish` status. As such, this method should not be 3466 * called directly and instead `wp_publish_post()` should be used. 3467 * 3468 * Please note that if the settings in the changeset are for a non-activated 3469 * theme, the theme must first be switched to (via `switch_theme()`) before 3470 * invoking this method. 3471 * 3472 * @since 4.7.0 3473 * 3474 * @see _wp_customize_publish_changeset() 3475 * @global wpdb $wpdb WordPress database abstraction object. 3476 * 3477 * @param int $changeset_post_id ID for customize_changeset post. Defaults to the changeset for the current manager instance. 3478 * @return true|WP_Error True or error info. 3479 */ 3480 public function _publish_changeset_values( $changeset_post_id ) { 3481 global $wpdb; 3482 3483 $publishing_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); 3484 if ( is_wp_error( $publishing_changeset_data ) ) { 3485 return $publishing_changeset_data; 3486 } 3487 3488 $changeset_post = get_post( $changeset_post_id ); 3489 3490 /* 3491 * Temporarily override the changeset context so that it will be read 3492 * in calls to unsanitized_post_values() and so that it will be available 3493 * on the $wp_customize object passed to hooks during the save logic. 3494 */ 3495 $previous_changeset_post_id = $this->_changeset_post_id; 3496 $this->_changeset_post_id = $changeset_post_id; 3497 $previous_changeset_uuid = $this->_changeset_uuid; 3498 $this->_changeset_uuid = $changeset_post->post_name; 3499 $previous_changeset_data = $this->_changeset_data; 3500 $this->_changeset_data = $publishing_changeset_data; 3501 3502 // Parse changeset data to identify theme mod settings and user IDs associated with settings to be saved. 3503 $setting_user_ids = array(); 3504 $theme_mod_settings = array(); 3505 $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/'; 3506 $matches = array(); 3507 foreach ( $this->_changeset_data as $raw_setting_id => $setting_params ) { 3508 $actual_setting_id = null; 3509 $is_theme_mod_setting = ( 3510 isset( $setting_params['value'] ) 3511 && 3512 isset( $setting_params['type'] ) 3513 && 3514 'theme_mod' === $setting_params['type'] 3515 && 3516 preg_match( $namespace_pattern, $raw_setting_id, $matches ) 3517 ); 3518 if ( $is_theme_mod_setting ) { 3519 if ( ! isset( $theme_mod_settings[ $matches['stylesheet'] ] ) ) { 3520 $theme_mod_settings[ $matches['stylesheet'] ] = array(); 3521 } 3522 $theme_mod_settings[ $matches['stylesheet'] ][ $matches['setting_id'] ] = $setting_params; 3523 3524 if ( $this->get_stylesheet() === $matches['stylesheet'] ) { 3525 $actual_setting_id = $matches['setting_id']; 3526 } 3527 } else { 3528 $actual_setting_id = $raw_setting_id; 3529 } 3530 3531 // Keep track of the user IDs for settings actually for this theme. 3532 if ( $actual_setting_id && isset( $setting_params['user_id'] ) ) { 3533 $setting_user_ids[ $actual_setting_id ] = $setting_params['user_id']; 3534 } 3535 } 3536 3537 $changeset_setting_values = $this->unsanitized_post_values( 3538 array( 3539 'exclude_post_data' => true, 3540 'exclude_changeset' => false, 3541 ) 3542 ); 3543 $changeset_setting_ids = array_keys( $changeset_setting_values ); 3544 $this->add_dynamic_settings( $changeset_setting_ids ); 3545 3546 /** 3547 * Fires once the theme has switched in the Customizer, but before settings 3548 * have been saved. 3549 * 3550 * @since 3.4.0 3551 * 3552 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 3553 */ 3554 do_action( 'customize_save', $this ); 3555 3556 /* 3557 * Ensure that all settings will allow themselves to be saved. Note that 3558 * this is safe because the setting would have checked the capability 3559 * when the setting value was written into the changeset. So this is why 3560 * an additional capability check is not required here. 3561 */ 3562 $original_setting_capabilities = array(); 3563 foreach ( $changeset_setting_ids as $setting_id ) { 3564 $setting = $this->get_setting( $setting_id ); 3565 if ( $setting && ! isset( $setting_user_ids[ $setting_id ] ) ) { 3566 $original_setting_capabilities[ $setting->id ] = $setting->capability; 3567 $setting->capability = 'exist'; 3568 } 3569 } 3570 3571 $original_user_id = get_current_user_id(); 3572 foreach ( $changeset_setting_ids as $setting_id ) { 3573 $setting = $this->get_setting( $setting_id ); 3574 if ( $setting ) { 3575 /* 3576 * Set the current user to match the user who saved the value into 3577 * the changeset so that any filters that apply during the save 3578 * process will respect the original user's capabilities. This 3579 * will ensure, for example, that KSES won't strip unsafe HTML 3580 * when a scheduled changeset publishes via WP Cron. 3581 */ 3582 if ( isset( $setting_user_ids[ $setting_id ] ) ) { 3583 wp_set_current_user( $setting_user_ids[ $setting_id ] ); 3584 } else { 3585 wp_set_current_user( $original_user_id ); 3586 } 3587 3588 $setting->save(); 3589 } 3590 } 3591 wp_set_current_user( $original_user_id ); 3592 3593 // Update the stashed theme mod settings, removing the active theme's stashed settings, if activated. 3594 if ( did_action( 'switch_theme' ) ) { 3595 $other_theme_mod_settings = $theme_mod_settings; 3596 unset( $other_theme_mod_settings[ $this->get_stylesheet() ] ); 3597 $this->update_stashed_theme_mod_settings( $other_theme_mod_settings ); 3598 } 3599 3600 /** 3601 * Fires after Customize settings have been saved. 3602 * 3603 * @since 3.6.0 3604 * 3605 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 3606 */ 3607 do_action( 'customize_save_after', $this ); 3608 3609 // Restore original capabilities. 3610 foreach ( $original_setting_capabilities as $setting_id => $capability ) { 3611 $setting = $this->get_setting( $setting_id ); 3612 if ( $setting ) { 3613 $setting->capability = $capability; 3614 } 3615 } 3616 3617 // Restore original changeset data. 3618 $this->_changeset_data = $previous_changeset_data; 3619 $this->_changeset_post_id = $previous_changeset_post_id; 3620 $this->_changeset_uuid = $previous_changeset_uuid; 3621 3622 /* 3623 * Convert all autosave revisions into their own auto-drafts so that users can be prompted to 3624 * restore them when a changeset is published, but they had been locked out from including 3625 * their changes in the changeset. 3626 */ 3627 $revisions = wp_get_post_revisions( $changeset_post_id, array( 'check_enabled' => false ) ); 3628 foreach ( $revisions as $revision ) { 3629 if ( str_contains( $revision->post_name, "{$changeset_post_id}-autosave" ) ) { 3630 $wpdb->update( 3631 $wpdb->posts, 3632 array( 3633 'post_status' => 'auto-draft', 3634 'post_type' => 'customize_changeset', 3635 'post_name' => wp_generate_uuid4(), 3636 'post_parent' => 0, 3637 ), 3638 array( 3639 'ID' => $revision->ID, 3640 ) 3641 ); 3642 clean_post_cache( $revision->ID ); 3643 } 3644 } 3645 3646 return true; 3647 } 3648 3649 /** 3650 * Updates stashed theme mod settings. 3651 * 3652 * @since 4.7.0 3653 * 3654 * @param array $inactive_theme_mod_settings Mapping of stylesheet to arrays of theme mod settings. 3655 * @return array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes. 3656 */ 3657 protected function update_stashed_theme_mod_settings( $inactive_theme_mod_settings ) { 3658 $stashed_theme_mod_settings = get_option( 'customize_stashed_theme_mods' ); 3659 if ( empty( $stashed_theme_mod_settings ) ) { 3660 $stashed_theme_mod_settings = array(); 3661 } 3662 3663 // Delete any stashed theme mods for the active theme since they would have been loaded and saved upon activation. 3664 unset( $stashed_theme_mod_settings[ $this->get_stylesheet() ] ); 3665 3666 // Merge inactive theme mods with the stashed theme mod settings. 3667 foreach ( $inactive_theme_mod_settings as $stylesheet => $theme_mod_settings ) { 3668 if ( ! isset( $stashed_theme_mod_settings[ $stylesheet ] ) ) { 3669 $stashed_theme_mod_settings[ $stylesheet ] = array(); 3670 } 3671 3672 $stashed_theme_mod_settings[ $stylesheet ] = array_merge( 3673 $stashed_theme_mod_settings[ $stylesheet ], 3674 $theme_mod_settings 3675 ); 3676 } 3677 3678 $autoload = false; 3679 $result = update_option( 'customize_stashed_theme_mods', $stashed_theme_mod_settings, $autoload ); 3680 if ( ! $result ) { 3681 return false; 3682 } 3683 return $stashed_theme_mod_settings; 3684 } 3685 3686 /** 3687 * Refreshes nonces for the current preview. 3688 * 3689 * @since 4.2.0 3690 * 3691 * @return never 3692 */ 3693 public function refresh_nonces() { 3694 if ( ! $this->is_preview() ) { 3695 wp_send_json_error( 'not_preview' ); 3696 } 3697 3698 wp_send_json_success( $this->get_nonces() ); 3699 } 3700 3701 /** 3702 * Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. 3703 * 3704 * @since 4.9.0 3705 * 3706 * @return never 3707 */ 3708 public function handle_dismiss_autosave_or_lock_request() { 3709 // Calls to dismiss_user_auto_draft_changesets() and wp_get_post_autosave() require non-zero get_current_user_id(). 3710 if ( ! is_user_logged_in() ) { 3711 wp_send_json_error( 'unauthenticated', 401 ); 3712 } 3713 3714 if ( ! $this->is_preview() ) { 3715 wp_send_json_error( 'not_preview', 400 ); 3716 } 3717 3718 if ( ! check_ajax_referer( 'customize_dismiss_autosave_or_lock', 'nonce', false ) ) { 3719 wp_send_json_error( 'invalid_nonce', 403 ); 3720 } 3721 3722 $changeset_post_id = $this->changeset_post_id(); 3723 $dismiss_lock = ! empty( $_POST['dismiss_lock'] ); 3724 $dismiss_autosave = ! empty( $_POST['dismiss_autosave'] ); 3725 3726 if ( $dismiss_lock ) { 3727 if ( empty( $changeset_post_id ) && ! $dismiss_autosave ) { 3728 wp_send_json_error( 'no_changeset_to_dismiss_lock', 404 ); 3729 } 3730 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) && ! $dismiss_autosave ) { 3731 wp_send_json_error( 'cannot_remove_changeset_lock', 403 ); 3732 } 3733 3734 delete_post_meta( $changeset_post_id, '_edit_lock' ); 3735 3736 if ( ! $dismiss_autosave ) { 3737 wp_send_json_success( 'changeset_lock_dismissed' ); 3738 } 3739 } 3740 3741 if ( $dismiss_autosave ) { 3742 if ( empty( $changeset_post_id ) || 'auto-draft' === get_post_status( $changeset_post_id ) ) { 3743 $dismissed = $this->dismiss_user_auto_draft_changesets(); 3744 if ( $dismissed > 0 ) { 3745 wp_send_json_success( 'auto_draft_dismissed' ); 3746 } else { 3747 wp_send_json_error( 'no_auto_draft_to_delete', 404 ); 3748 } 3749 } else { 3750 $revision = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); 3751 3752 if ( $revision ) { 3753 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) { 3754 wp_send_json_error( 'cannot_delete_autosave_revision', 403 ); 3755 } 3756 3757 if ( ! wp_delete_post( $revision->ID, true ) ) { 3758 wp_send_json_error( 'autosave_revision_deletion_failure', 500 ); 3759 } else { 3760 wp_send_json_success( 'autosave_revision_deleted' ); 3761 } 3762 } else { 3763 wp_send_json_error( 'no_autosave_revision_to_delete', 404 ); 3764 } 3765 } 3766 } 3767 3768 wp_send_json_error( 'unknown_error', 500 ); 3769 } 3770 3771 /** 3772 * Adds a customize setting. 3773 * 3774 * @since 3.4.0 3775 * @since 4.5.0 Return added WP_Customize_Setting instance. 3776 * 3777 * @see WP_Customize_Setting::__construct() 3778 * @link https://developer.wordpress.org/themes/customize-api 3779 * 3780 * @param WP_Customize_Setting|string $id Customize Setting object, or ID. 3781 * @param array $args Optional. Array of properties for the new Setting object. 3782 * See WP_Customize_Setting::__construct() for information 3783 * on accepted arguments. Default empty array. 3784 * @return WP_Customize_Setting The instance of the setting that was added. 3785 */ 3786 public function add_setting( $id, $args = array() ) { 3787 if ( $id instanceof WP_Customize_Setting ) { 3788 $setting = $id; 3789 } else { 3790 $class = 'WP_Customize_Setting'; 3791 3792 /** This filter is documented in wp-includes/class-wp-customize-manager.php */ 3793 $args = apply_filters( 'customize_dynamic_setting_args', $args, $id ); 3794 3795 /** This filter is documented in wp-includes/class-wp-customize-manager.php */ 3796 $class = apply_filters( 'customize_dynamic_setting_class', $class, $id, $args ); 3797 3798 $setting = new $class( $this, $id, $args ); 3799 } 3800 3801 $this->settings[ $setting->id ] = $setting; 3802 return $setting; 3803 } 3804 3805 /** 3806 * Registers any dynamically-created settings, such as those from $_POST['customized'] 3807 * that have no corresponding setting created. 3808 * 3809 * This is a mechanism to "wake up" settings that have been dynamically created 3810 * on the front end and have been sent to WordPress in `$_POST['customized']`. When WP 3811 * loads, the dynamically-created settings then will get created and previewed 3812 * even though they are not directly created statically with code. 3813 * 3814 * @since 4.2.0 3815 * 3816 * @param array $setting_ids The setting IDs to add. 3817 * @return array The WP_Customize_Setting objects added. 3818 */ 3819 public function add_dynamic_settings( $setting_ids ) { 3820 $new_settings = array(); 3821 foreach ( $setting_ids as $setting_id ) { 3822 // Skip settings already created. 3823 if ( $this->get_setting( $setting_id ) ) { 3824 continue; 3825 } 3826 3827 $setting_args = false; 3828 $setting_class = 'WP_Customize_Setting'; 3829 3830 /** 3831 * Filters a dynamic setting's constructor args. 3832 * 3833 * For a dynamic setting to be registered, this filter must be employed 3834 * to override the default false value with an array of args to pass to 3835 * the WP_Customize_Setting constructor. 3836 * 3837 * @since 4.2.0 3838 * 3839 * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor. 3840 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. 3841 */ 3842 $setting_args = apply_filters( 'customize_dynamic_setting_args', $setting_args, $setting_id ); 3843 if ( false === $setting_args ) { 3844 continue; 3845 } 3846 3847 /** 3848 * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass. 3849 * 3850 * @since 4.2.0 3851 * 3852 * @param string $setting_class WP_Customize_Setting or a subclass. 3853 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. 3854 * @param array $setting_args WP_Customize_Setting or a subclass. 3855 */ 3856 $setting_class = apply_filters( 'customize_dynamic_setting_class', $setting_class, $setting_id, $setting_args ); 3857 3858 $setting = new $setting_class( $this, $setting_id, $setting_args ); 3859 3860 $this->add_setting( $setting ); 3861 $new_settings[] = $setting; 3862 } 3863 return $new_settings; 3864 } 3865 3866 /** 3867 * Retrieves a customize setting. 3868 * 3869 * @since 3.4.0 3870 * 3871 * @param string $id Customize Setting ID. 3872 * @return WP_Customize_Setting|null The setting, if set. 3873 */ 3874 public function get_setting( $id ) { 3875 if ( isset( $this->settings[ $id ] ) ) { 3876 return $this->settings[ $id ]; 3877 } 3878 } 3879 3880 /** 3881 * Removes a customize setting. 3882 * 3883 * Note that removing the setting doesn't destroy the WP_Customize_Setting instance or remove its filters. 3884 * 3885 * @since 3.4.0 3886 * 3887 * @param string $id Customize Setting ID. 3888 */ 3889 public function remove_setting( $id ) { 3890 unset( $this->settings[ $id ] ); 3891 } 3892 3893 /** 3894 * Adds a customize panel. 3895 * 3896 * @since 4.0.0 3897 * @since 4.5.0 Return added WP_Customize_Panel instance. 3898 * 3899 * @see WP_Customize_Panel::__construct() 3900 * 3901 * @param WP_Customize_Panel|string $id Customize Panel object, or ID. 3902 * @param array $args Optional. Array of properties for the new Panel object. 3903 * See WP_Customize_Panel::__construct() for information 3904 * on accepted arguments. Default empty array. 3905 * @return WP_Customize_Panel The instance of the panel that was added. 3906 */ 3907 public function add_panel( $id, $args = array() ) { 3908 if ( $id instanceof WP_Customize_Panel ) { 3909 $panel = $id; 3910 } else { 3911 $panel = new WP_Customize_Panel( $this, $id, $args ); 3912 } 3913 3914 $this->panels[ $panel->id ] = $panel; 3915 return $panel; 3916 } 3917 3918 /** 3919 * Retrieves a customize panel. 3920 * 3921 * @since 4.0.0 3922 * 3923 * @param string $id Panel ID to get. 3924 * @return WP_Customize_Panel|null Requested panel instance, if set. 3925 */ 3926 public function get_panel( $id ) { 3927 if ( isset( $this->panels[ $id ] ) ) { 3928 return $this->panels[ $id ]; 3929 } 3930 } 3931 3932 /** 3933 * Removes a customize panel. 3934 * 3935 * Note that removing the panel doesn't destroy the WP_Customize_Panel instance or remove its filters. 3936 * 3937 * @since 4.0.0 3938 * 3939 * @param string $id Panel ID to remove. 3940 */ 3941 public function remove_panel( $id ) { 3942 // Removing core components this way is _doing_it_wrong(). 3943 if ( in_array( $id, $this->components, true ) ) { 3944 _doing_it_wrong( 3945 __METHOD__, 3946 sprintf( 3947 /* translators: 1: Panel ID, 2: Link to 'customize_loaded_components' filter reference. */ 3948 __( 'Removing %1$s manually will cause PHP warnings. Use the %2$s filter instead.' ), 3949 $id, 3950 sprintf( 3951 '<a href="%1$s">%2$s</a>', 3952 esc_url( 'https://developer.wordpress.org/reference/hooks/customize_loaded_components/' ), 3953 '<code>customize_loaded_components</code>' 3954 ) 3955 ), 3956 '4.5.0' 3957 ); 3958 } 3959 unset( $this->panels[ $id ] ); 3960 } 3961 3962 /** 3963 * Registers a customize panel type. 3964 * 3965 * Registered types are eligible to be rendered via JS and created dynamically. 3966 * 3967 * @since 4.3.0 3968 * 3969 * @see WP_Customize_Panel 3970 * 3971 * @param string $panel Name of a custom panel which is a subclass of WP_Customize_Panel. 3972 */ 3973 public function register_panel_type( $panel ) { 3974 $this->registered_panel_types[] = $panel; 3975 } 3976 3977 /** 3978 * Renders JS templates for all registered panel types. 3979 * 3980 * @since 4.3.0 3981 */ 3982 public function render_panel_templates() { 3983 foreach ( $this->registered_panel_types as $panel_type ) { 3984 $panel = new $panel_type( $this, 'temp', array() ); 3985 $panel->print_template(); 3986 } 3987 } 3988 3989 /** 3990 * Adds a customize section. 3991 * 3992 * @since 3.4.0 3993 * @since 4.5.0 Return added WP_Customize_Section instance. 3994 * 3995 * @see WP_Customize_Section::__construct() 3996 * 3997 * @param WP_Customize_Section|string $id Customize Section object, or ID. 3998 * @param array $args Optional. Array of properties for the new Section object. 3999 * See WP_Customize_Section::__construct() for information 4000 * on accepted arguments. Default empty array. 4001 * @return WP_Customize_Section The instance of the section that was added. 4002 */ 4003 public function add_section( $id, $args = array() ) { 4004 if ( $id instanceof WP_Customize_Section ) { 4005 $section = $id; 4006 } else { 4007 $section = new WP_Customize_Section( $this, $id, $args ); 4008 } 4009 4010 $this->sections[ $section->id ] = $section; 4011 return $section; 4012 } 4013 4014 /** 4015 * Retrieves a customize section. 4016 * 4017 * @since 3.4.0 4018 * 4019 * @param string $id Section ID. 4020 * @return WP_Customize_Section|null The section, if set. 4021 */ 4022 public function get_section( $id ) { 4023 if ( isset( $this->sections[ $id ] ) ) { 4024 return $this->sections[ $id ]; 4025 } 4026 } 4027 4028 /** 4029 * Removes a customize section. 4030 * 4031 * Note that removing the section doesn't destroy the WP_Customize_Section instance or remove its filters. 4032 * 4033 * @since 3.4.0 4034 * 4035 * @param string $id Section ID. 4036 */ 4037 public function remove_section( $id ) { 4038 unset( $this->sections[ $id ] ); 4039 } 4040 4041 /** 4042 * Registers a customize section type. 4043 * 4044 * Registered types are eligible to be rendered via JS and created dynamically. 4045 * 4046 * @since 4.3.0 4047 * 4048 * @see WP_Customize_Section 4049 * 4050 * @param string $section Name of a custom section which is a subclass of WP_Customize_Section. 4051 */ 4052 public function register_section_type( $section ) { 4053 $this->registered_section_types[] = $section; 4054 } 4055 4056 /** 4057 * Renders JS templates for all registered section types. 4058 * 4059 * @since 4.3.0 4060 */ 4061 public function render_section_templates() { 4062 foreach ( $this->registered_section_types as $section_type ) { 4063 $section = new $section_type( $this, 'temp', array() ); 4064 $section->print_template(); 4065 } 4066 } 4067 4068 /** 4069 * Adds a customize control. 4070 * 4071 * @since 3.4.0 4072 * @since 4.5.0 Return added WP_Customize_Control instance. 4073 * 4074 * @see WP_Customize_Control::__construct() 4075 * 4076 * @param WP_Customize_Control|string $id Customize Control object, or ID. 4077 * @param array $args Optional. Array of properties for the new Control object. 4078 * See WP_Customize_Control::__construct() for information 4079 * on accepted arguments. Default empty array. 4080 * @return WP_Customize_Control The instance of the control that was added. 4081 */ 4082 public function add_control( $id, $args = array() ) { 4083 if ( $id instanceof WP_Customize_Control ) { 4084 $control = $id; 4085 } else { 4086 $control = new WP_Customize_Control( $this, $id, $args ); 4087 } 4088 4089 $this->controls[ $control->id ] = $control; 4090 return $control; 4091 } 4092 4093 /** 4094 * Retrieves a customize control. 4095 * 4096 * @since 3.4.0 4097 * 4098 * @param string $id ID of the control. 4099 * @return WP_Customize_Control|null The control object, if set. 4100 */ 4101 public function get_control( $id ) { 4102 if ( isset( $this->controls[ $id ] ) ) { 4103 return $this->controls[ $id ]; 4104 } 4105 } 4106 4107 /** 4108 * Removes a customize control. 4109 * 4110 * Note that removing the control doesn't destroy the WP_Customize_Control instance or remove its filters. 4111 * 4112 * @since 3.4.0 4113 * 4114 * @param string $id ID of the control. 4115 */ 4116 public function remove_control( $id ) { 4117 unset( $this->controls[ $id ] ); 4118 } 4119 4120 /** 4121 * Registers a customize control type. 4122 * 4123 * Registered types are eligible to be rendered via JS and created dynamically. 4124 * 4125 * @since 4.1.0 4126 * 4127 * @param string $control Name of a custom control which is a subclass of 4128 * WP_Customize_Control. 4129 */ 4130 public function register_control_type( $control ) { 4131 $this->registered_control_types[] = $control; 4132 } 4133 4134 /** 4135 * Renders JS templates for all registered control types. 4136 * 4137 * @since 4.1.0 4138 */ 4139 public function render_control_templates() { 4140 if ( $this->branching() ) { 4141 $l10n = array( 4142 /* translators: %s: User who is customizing the changeset in customizer. */ 4143 'locked' => __( '%s is already customizing this changeset. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ), 4144 /* translators: %s: User who is customizing the changeset in customizer. */ 4145 'locked_allow_override' => __( '%s is already customizing this changeset. Do you want to take over?' ), 4146 ); 4147 } else { 4148 $l10n = array( 4149 /* translators: %s: User who is customizing the changeset in customizer. */ 4150 'locked' => __( '%s is already customizing this site. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ), 4151 /* translators: %s: User who is customizing the changeset in customizer. */ 4152 'locked_allow_override' => __( '%s is already customizing this site. Do you want to take over?' ), 4153 ); 4154 } 4155 4156 foreach ( $this->registered_control_types as $control_type ) { 4157 $control = new $control_type( 4158 $this, 4159 'temp', 4160 array( 4161 'settings' => array(), 4162 ) 4163 ); 4164 $control->print_template(); 4165 } 4166 ?> 4167 4168 <script type="text/html" id="tmpl-customize-control-default-content"> 4169 <# 4170 var inputId = _.uniqueId( 'customize-control-default-input-' ); 4171 var descriptionId = _.uniqueId( 'customize-control-default-description-' ); 4172 var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : ''; 4173 #> 4174 <# switch ( data.type ) { 4175 case 'checkbox': #> 4176 <span class="customize-inside-control-row"> 4177 <input 4178 id="{{ inputId }}" 4179 {{{ describedByAttr }}} 4180 type="checkbox" 4181 value="{{ data.value }}" 4182 data-customize-setting-key-link="default" 4183 > 4184 <label for="{{ inputId }}"> 4185 {{ data.label }} 4186 </label> 4187 <# if ( data.description ) { #> 4188 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4189 <# } #> 4190 </span> 4191 <# 4192 break; 4193 case 'radio': 4194 if ( ! data.choices ) { 4195 return; 4196 } 4197 #> 4198 <# if ( data.label ) { #> 4199 <label for="{{ inputId }}" class="customize-control-title"> 4200 {{ data.label }} 4201 </label> 4202 <# } #> 4203 <# if ( data.description ) { #> 4204 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4205 <# } #> 4206 <# _.each( data.choices, function( val, key ) { #> 4207 <span class="customize-inside-control-row"> 4208 <# 4209 var value, text; 4210 if ( _.isObject( val ) ) { 4211 value = val.value; 4212 text = val.text; 4213 } else { 4214 value = key; 4215 text = val; 4216 } 4217 #> 4218 <input 4219 id="{{ inputId + '-' + value }}" 4220 type="radio" 4221 value="{{ value }}" 4222 name="{{ inputId }}" 4223 data-customize-setting-key-link="default" 4224 {{{ describedByAttr }}} 4225 > 4226 <label for="{{ inputId + '-' + value }}">{{ text }}</label> 4227 </span> 4228 <# } ); #> 4229 <# 4230 break; 4231 default: 4232 #> 4233 <# if ( data.label ) { #> 4234 <label for="{{ inputId }}" class="customize-control-title"> 4235 {{ data.label }} 4236 </label> 4237 <# } #> 4238 <# if ( data.description ) { #> 4239 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4240 <# } #> 4241 4242 <# 4243 var inputAttrs = { 4244 id: inputId, 4245 'data-customize-setting-key-link': 'default' 4246 }; 4247 if ( 'textarea' === data.type ) { 4248 inputAttrs.rows = '5'; 4249 } else if ( 'button' === data.type ) { 4250 inputAttrs['class'] = 'button button-secondary'; 4251 inputAttrs.type = 'button'; 4252 } else { 4253 inputAttrs.type = data.type; 4254 } 4255 if ( data.description ) { 4256 inputAttrs['aria-describedby'] = descriptionId; 4257 } 4258 _.extend( inputAttrs, data.input_attrs ); 4259 #> 4260 4261 <# if ( 'button' === data.type ) { #> 4262 <button 4263 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4264 {{{ key }}}="{{ value }}" 4265 <# } ); #> 4266 >{{ inputAttrs.value }}</button> 4267 <# } else if ( 'textarea' === data.type ) { #> 4268 <textarea 4269 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4270 {{{ key }}}="{{ value }}" 4271 <# }); #> 4272 >{{ inputAttrs.value }}</textarea> 4273 <# } else if ( 'select' === data.type ) { #> 4274 <# delete inputAttrs.type; #> 4275 <select 4276 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4277 {{{ key }}}="{{ value }}" 4278 <# }); #> 4279 > 4280 <# _.each( data.choices, function( val, key ) { #> 4281 <# 4282 var value, text; 4283 if ( _.isObject( val ) ) { 4284 value = val.value; 4285 text = val.text; 4286 } else { 4287 value = key; 4288 text = val; 4289 } 4290 #> 4291 <option value="{{ value }}">{{ text }}</option> 4292 <# } ); #> 4293 </select> 4294 <# } else { #> 4295 <input 4296 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4297 {{{ key }}}="{{ value }}" 4298 <# }); #> 4299 > 4300 <# } #> 4301 <# } #> 4302 </script> 4303 4304 <script type="text/html" id="tmpl-customize-notification"> 4305 <li class="notice notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> 4306 <div class="notification-message">{{{ data.message || data.code }}}</div> 4307 <# if ( data.dismissible ) { #> 4308 <button type="button" class="notice-dismiss"><span class="screen-reader-text"> 4309 <?php 4310 /* translators: Hidden accessibility text. */ 4311 _e( 'Dismiss' ); 4312 ?> 4313 </span></button> 4314 <# } #> 4315 </li> 4316 </script> 4317 4318 <script type="text/html" id="tmpl-customize-changeset-locked-notification"> 4319 <li class="notice notice-{{ data.type || 'info' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> 4320 <div class="notification-message customize-changeset-locked-message {{ data.lockUser.avatar ? 'has-avatar' : '' }}"> 4321 <# if ( data.lockUser.avatar ) { #> 4322 <img class="customize-changeset-locked-avatar" src="{{ data.lockUser.avatar }}" alt="{{ data.lockUser.name }}" /> 4323 <# } #> 4324 <p class="currently-editing"> 4325 <# if ( data.message ) { #> 4326 {{{ data.message }}} 4327 <# } else if ( data.allowOverride ) { #> 4328 <?php 4329 echo esc_html( sprintf( $l10n['locked_allow_override'], '{{ data.lockUser.name }}' ) ); 4330 ?> 4331 <# } else { #> 4332 <?php 4333 echo esc_html( sprintf( $l10n['locked'], '{{ data.lockUser.name }}' ) ); 4334 ?> 4335 <# } #> 4336 </p> 4337 <p class="notice notice-error notice-alt" hidden></p> 4338 <p class="action-buttons"> 4339 <# if ( data.returnUrl !== data.previewUrl ) { #> 4340 <a class="button customize-notice-go-back-button" href="{{ data.returnUrl }}"><?php _e( 'Go back' ); ?></a> 4341 <# } #> 4342 <a class="button customize-notice-preview-button" href="{{ data.frontendPreviewUrl }}"><?php echo esc_html_x( 'Preview', 'verb' ); ?></a> 4343 <# if ( data.allowOverride ) { #> 4344 <button class="button button-primary wp-tab-last customize-notice-take-over-button"><?php _e( 'Take over' ); ?></button> 4345 <# } #> 4346 </p> 4347 </div> 4348 </li> 4349 </script> 4350 4351 <script type="text/html" id="tmpl-customize-code-editor-lint-error-notification"> 4352 <li class="notice notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> 4353 <div class="notification-message">{{{ data.message || data.code }}}</div> 4354 4355 <p> 4356 <# var elementId = 'el-' + String( Math.random() ); #> 4357 <input id="{{ elementId }}" type="checkbox"> 4358 <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label> 4359 </p> 4360 </li> 4361 </script> 4362 4363 <?php 4364 /* The following template is obsolete in core but retained for plugins. */ 4365 ?> 4366 <script type="text/html" id="tmpl-customize-control-notifications"> 4367 <ul> 4368 <# _.each( data.notifications, function( notification ) { #> 4369 <li class="notice notice-{{ notification.type || 'info' }} {{ data.altNotice ? 'notice-alt' : '' }}" data-code="{{ notification.code }}" data-type="{{ notification.type }}">{{{ notification.message || notification.code }}}</li> 4370 <# } ); #> 4371 </ul> 4372 </script> 4373 4374 <script type="text/html" id="tmpl-customize-preview-link-control" > 4375 <# var elementPrefix = _.uniqueId( 'el' ) + '-' #> 4376 <p class="customize-control-title"> 4377 <?php esc_html_e( 'Share Preview Link' ); ?> 4378 </p> 4379 <p class="description customize-control-description"><?php esc_html_e( 'See how changes would look live on your website, and share the preview with people who can\'t access the Customizer.' ); ?></p> 4380 <div class="customize-control-notifications-container"></div> 4381 <div class="preview-link-wrapper"> 4382 <label for="{{ elementPrefix }}customize-preview-link-input" class="screen-reader-text"> 4383 <?php 4384 /* translators: Hidden accessibility text. */ 4385 esc_html_e( 'Preview Link' ); 4386 ?> 4387 </label> 4388 <a href="" target=""> 4389 <span class="preview-control-element" data-component="url"></span> 4390 <span class="screen-reader-text"> 4391 <?php 4392 /* translators: Hidden accessibility text. */ 4393 _e( '(opens in a new tab)' ); 4394 ?> 4395 </span> 4396 </a> 4397 <input id="{{ elementPrefix }}customize-preview-link-input" readonly tabindex="-1" class="preview-control-element" data-component="input"> 4398 <button class="customize-copy-preview-link preview-control-element button button-secondary" data-component="button" data-copy-text="<?php esc_attr_e( 'Copy' ); ?>" data-copied-text="<?php esc_attr_e( 'Copied' ); ?>" ><?php esc_html_e( 'Copy' ); ?></button> 4399 </div> 4400 </script> 4401 <script type="text/html" id="tmpl-customize-selected-changeset-status-control"> 4402 <# var inputId = _.uniqueId( 'customize-selected-changeset-status-control-input-' ); #> 4403 <# var descriptionId = _.uniqueId( 'customize-selected-changeset-status-control-description-' ); #> 4404 <# if ( data.label ) { #> 4405 <label for="{{ inputId }}" class="customize-control-title">{{ data.label }}</label> 4406 <# } #> 4407 <# if ( data.description ) { #> 4408 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4409 <# } #> 4410 <# _.each( data.choices, function( choice ) { #> 4411 <# var choiceId = inputId + '-' + choice.status; #> 4412 <span class="customize-inside-control-row"> 4413 <input id="{{ choiceId }}" type="radio" value="{{ choice.status }}" name="{{ inputId }}" data-customize-setting-key-link="default"> 4414 <label for="{{ choiceId }}">{{ choice.label }}</label> 4415 </span> 4416 <# } ); #> 4417 </script> 4418 <?php 4419 } 4420 4421 /** 4422 * Helper function to compare two objects by priority, ensuring sort stability via instance_number. 4423 * 4424 * @since 3.4.0 4425 * @deprecated 4.7.0 Use wp_list_sort() 4426 * 4427 * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a Object A. 4428 * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b Object B. 4429 * @return int 4430 */ 4431 protected function _cmp_priority( $a, $b ) { 4432 _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' ); 4433 4434 if ( $a->priority === $b->priority ) { 4435 return $a->instance_number - $b->instance_number; 4436 } else { 4437 return $a->priority - $b->priority; 4438 } 4439 } 4440 4441 /** 4442 * Prepares panels, sections, and controls. 4443 * 4444 * For each, check if required related components exist, 4445 * whether the user has the necessary capabilities, 4446 * and sort by priority. 4447 * 4448 * @since 3.4.0 4449 */ 4450 public function prepare_controls() { 4451 4452 $controls = array(); 4453 $this->controls = wp_list_sort( 4454 $this->controls, 4455 array( 4456 'priority' => 'ASC', 4457 'instance_number' => 'ASC', 4458 ), 4459 'ASC', 4460 true 4461 ); 4462 4463 foreach ( $this->controls as $id => $control ) { 4464 if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) { 4465 continue; 4466 } 4467 4468 $this->sections[ $control->section ]->controls[] = $control; 4469 $controls[ $id ] = $control; 4470 } 4471 $this->controls = $controls; 4472 4473 // Prepare sections. 4474 $this->sections = wp_list_sort( 4475 $this->sections, 4476 array( 4477 'priority' => 'ASC', 4478 'instance_number' => 'ASC', 4479 ), 4480 'ASC', 4481 true 4482 ); 4483 $sections = array(); 4484 4485 foreach ( $this->sections as $section ) { 4486 if ( ! $section->check_capabilities() ) { 4487 continue; 4488 } 4489 4490 $section->controls = wp_list_sort( 4491 $section->controls, 4492 array( 4493 'priority' => 'ASC', 4494 'instance_number' => 'ASC', 4495 ) 4496 ); 4497 4498 if ( ! $section->panel ) { 4499 // Top-level section. 4500 $sections[ $section->id ] = $section; 4501 } else { 4502 // This section belongs to a panel. 4503 if ( isset( $this->panels [ $section->panel ] ) ) { 4504 $this->panels[ $section->panel ]->sections[ $section->id ] = $section; 4505 } 4506 } 4507 } 4508 $this->sections = $sections; 4509 4510 // Prepare panels. 4511 $this->panels = wp_list_sort( 4512 $this->panels, 4513 array( 4514 'priority' => 'ASC', 4515 'instance_number' => 'ASC', 4516 ), 4517 'ASC', 4518 true 4519 ); 4520 $panels = array(); 4521 4522 foreach ( $this->panels as $panel ) { 4523 if ( ! $panel->check_capabilities() ) { 4524 continue; 4525 } 4526 4527 $panel->sections = wp_list_sort( 4528 $panel->sections, 4529 array( 4530 'priority' => 'ASC', 4531 'instance_number' => 'ASC', 4532 ), 4533 'ASC', 4534 true 4535 ); 4536 $panels[ $panel->id ] = $panel; 4537 } 4538 $this->panels = $panels; 4539 4540 // Sort panels and top-level sections together. 4541 $this->containers = array_merge( $this->panels, $this->sections ); 4542 $this->containers = wp_list_sort( 4543 $this->containers, 4544 array( 4545 'priority' => 'ASC', 4546 'instance_number' => 'ASC', 4547 ), 4548 'ASC', 4549 true 4550 ); 4551 } 4552 4553 /** 4554 * Enqueues scripts for customize controls. 4555 * 4556 * @since 3.4.0 4557 */ 4558 public function enqueue_control_scripts() { 4559 foreach ( $this->controls as $control ) { 4560 $control->enqueue(); 4561 } 4562 4563 if ( ! is_multisite() && ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) || current_user_can( 'delete_themes' ) ) ) { 4564 wp_enqueue_script( 'updates' ); 4565 wp_localize_script( 4566 'updates', 4567 '_wpUpdatesItemCounts', 4568 array( 4569 'totals' => wp_get_update_data(), 4570 ) 4571 ); 4572 } 4573 } 4574 4575 /** 4576 * Determines whether the user agent is iOS. 4577 * 4578 * @since 4.4.0 4579 * 4580 * @return bool Whether the user agent is iOS. 4581 */ 4582 public function is_ios() { 4583 return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] ); 4584 } 4585 4586 /** 4587 * Gets the template string for the Customizer pane document title. 4588 * 4589 * @since 4.4.0 4590 * 4591 * @return string The template string for the document title. 4592 */ 4593 public function get_document_title_template() { 4594 if ( $this->is_theme_active() ) { 4595 /* translators: %s: Document title from the preview. */ 4596 $document_title_tmpl = __( 'Customize: %s' ); 4597 } else { 4598 /* translators: %s: Document title from the preview. */ 4599 $document_title_tmpl = __( 'Live Preview: %s' ); 4600 } 4601 $document_title_tmpl = html_entity_decode( $document_title_tmpl, ENT_QUOTES, 'UTF-8' ); // Because exported to JS and assigned to document.title. 4602 return $document_title_tmpl; 4603 } 4604 4605 /** 4606 * Sets the initial URL to be previewed. 4607 * 4608 * URL is validated. 4609 * 4610 * @since 4.4.0 4611 * 4612 * @param string $preview_url URL to be previewed. 4613 */ 4614 public function set_preview_url( $preview_url ) { 4615 $preview_url = sanitize_url( $preview_url ); 4616 $this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) ); 4617 } 4618 4619 /** 4620 * Gets the initial URL to be previewed. 4621 * 4622 * @since 4.4.0 4623 * 4624 * @return string URL being previewed. 4625 */ 4626 public function get_preview_url() { 4627 if ( empty( $this->preview_url ) ) { 4628 $preview_url = home_url( '/' ); 4629 } else { 4630 $preview_url = $this->preview_url; 4631 } 4632 return $preview_url; 4633 } 4634 4635 /** 4636 * Determines whether the admin and the frontend are on different domains. 4637 * 4638 * @since 4.7.0 4639 * 4640 * @return bool Whether cross-domain. 4641 */ 4642 public function is_cross_domain() { 4643 $admin_origin = wp_parse_url( admin_url() ); 4644 $home_origin = wp_parse_url( home_url() ); 4645 $cross_domain = ( strtolower( $admin_origin['host'] ) !== strtolower( $home_origin['host'] ) ); 4646 return $cross_domain; 4647 } 4648 4649 /** 4650 * Gets URLs allowed to be previewed. 4651 * 4652 * If the front end and the admin are served from the same domain, load the 4653 * preview over ssl if the Customizer is being loaded over ssl. This avoids 4654 * insecure content warnings. This is not attempted if the admin and front end 4655 * are on different domains to avoid the case where the front end doesn't have 4656 * ssl certs. Domain mapping plugins can allow other urls in these conditions 4657 * using the customize_allowed_urls filter. 4658 * 4659 * @since 4.7.0 4660 * 4661 * @return array Allowed URLs. 4662 */ 4663 public function get_allowed_urls() { 4664 $allowed_urls = array( home_url( '/' ) ); 4665 4666 if ( is_ssl() && ! $this->is_cross_domain() ) { 4667 $allowed_urls[] = home_url( '/', 'https' ); 4668 } 4669 4670 /** 4671 * Filters the list of URLs allowed to be clicked and followed in the Customizer preview. 4672 * 4673 * @since 3.4.0 4674 * 4675 * @param string[] $allowed_urls An array of allowed URLs. 4676 */ 4677 $allowed_urls = array_unique( apply_filters( 'customize_allowed_urls', $allowed_urls ) ); 4678 4679 return $allowed_urls; 4680 } 4681 4682 /** 4683 * Gets messenger channel. 4684 * 4685 * @since 4.7.0 4686 * 4687 * @return string Messenger channel. 4688 */ 4689 public function get_messenger_channel() { 4690 return $this->messenger_channel; 4691 } 4692 4693 /** 4694 * Sets URL to link the user to when closing the Customizer. 4695 * 4696 * URL is validated. 4697 * 4698 * @since 4.4.0 4699 * 4700 * @param string $return_url URL for return link. 4701 */ 4702 public function set_return_url( $return_url ) { 4703 $return_url = sanitize_url( $return_url ); 4704 $return_url = remove_query_arg( wp_removable_query_args(), $return_url ); 4705 $return_url = wp_validate_redirect( $return_url ); 4706 $this->return_url = $return_url; 4707 } 4708 4709 /** 4710 * Gets URL to link the user to when closing the Customizer. 4711 * 4712 * @since 4.4.0 4713 * 4714 * @global array $_registered_pages 4715 * 4716 * @return string URL for link to close Customizer. 4717 */ 4718 public function get_return_url() { 4719 global $_registered_pages; 4720 4721 $referer = wp_get_referer(); 4722 $excluded_referer_basenames = array( 'customize.php', 'wp-login.php' ); 4723 4724 if ( $this->return_url ) { 4725 $return_url = $this->return_url; 4726 4727 $return_url_basename = wp_basename( parse_url( $this->return_url, PHP_URL_PATH ) ); 4728 $return_url_query = parse_url( $this->return_url, PHP_URL_QUERY ); 4729 4730 if ( 'themes.php' === $return_url_basename && $return_url_query ) { 4731 parse_str( $return_url_query, $query_vars ); 4732 4733 /* 4734 * If the return URL is a page added by a theme to the Appearance menu via add_submenu_page(), 4735 * verify that it belongs to the active theme, otherwise fall back to the Themes screen. 4736 */ 4737 if ( isset( $query_vars['page'] ) && ! isset( $_registered_pages[ "appearance_page_{$query_vars['page']}" ] ) ) { 4738 $return_url = admin_url( 'themes.php' ); 4739 } 4740 } 4741 } elseif ( $referer && ! in_array( wp_basename( parse_url( $referer, PHP_URL_PATH ) ), $excluded_referer_basenames, true ) ) { 4742 $return_url = $referer; 4743 } elseif ( $this->preview_url ) { 4744 $return_url = $this->preview_url; 4745 } else { 4746 $return_url = home_url( '/' ); 4747 } 4748 4749 return $return_url; 4750 } 4751 4752 /** 4753 * Sets the autofocused constructs. 4754 * 4755 * @since 4.4.0 4756 * 4757 * @param array $autofocus { 4758 * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. 4759 * 4760 * @type string $control ID for control to be autofocused. 4761 * @type string $section ID for section to be autofocused. 4762 * @type string $panel ID for panel to be autofocused. 4763 * } 4764 */ 4765 public function set_autofocus( $autofocus ) { 4766 $this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' ); 4767 } 4768 4769 /** 4770 * Gets the autofocused constructs. 4771 * 4772 * @since 4.4.0 4773 * 4774 * @return string[] { 4775 * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. 4776 * 4777 * @type string $control ID for control to be autofocused. 4778 * @type string $section ID for section to be autofocused. 4779 * @type string $panel ID for panel to be autofocused. 4780 * } 4781 */ 4782 public function get_autofocus() { 4783 return $this->autofocus; 4784 } 4785 4786 /** 4787 * Gets nonces for the Customizer. 4788 * 4789 * @since 4.5.0 4790 * 4791 * @return array Nonces. 4792 */ 4793 public function get_nonces() { 4794 $nonces = array( 4795 'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ), 4796 'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ), 4797 'switch_themes' => wp_create_nonce( 'switch_themes' ), 4798 'dismiss_autosave_or_lock' => wp_create_nonce( 'customize_dismiss_autosave_or_lock' ), 4799 'override_lock' => wp_create_nonce( 'customize_override_changeset_lock' ), 4800 'trash' => wp_create_nonce( 'trash_customize_changeset' ), 4801 ); 4802 4803 /** 4804 * Filters nonces for Customizer. 4805 * 4806 * @since 4.2.0 4807 * 4808 * @param string[] $nonces Array of refreshed nonces for save and 4809 * preview actions. 4810 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 4811 */ 4812 $nonces = apply_filters( 'customize_refresh_nonces', $nonces, $this ); 4813 4814 return $nonces; 4815 } 4816 4817 /** 4818 * Prints JavaScript settings for parent window. 4819 * 4820 * @since 4.4.0 4821 */ 4822 public function customize_pane_settings() { 4823 4824 $login_url = add_query_arg( 4825 array( 4826 'interim-login' => 1, 4827 'customize-login' => 1, 4828 ), 4829 wp_login_url() 4830 ); 4831 4832 // Ensure dirty flags are set for modified settings. 4833 foreach ( array_keys( $this->unsanitized_post_values() ) as $setting_id ) { 4834 $setting = $this->get_setting( $setting_id ); 4835 if ( $setting ) { 4836 $setting->dirty = true; 4837 } 4838 } 4839 4840 $autosave_revision_post = null; 4841 $autosave_autodraft_post = null; 4842 $changeset_post_id = $this->changeset_post_id(); 4843 if ( ! $this->saved_starter_content_changeset && ! $this->autosaved() ) { 4844 if ( $changeset_post_id ) { 4845 if ( is_user_logged_in() ) { 4846 $autosave_revision_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); 4847 } 4848 } else { 4849 $autosave_autodraft_posts = $this->get_changeset_posts( 4850 array( 4851 'posts_per_page' => 1, 4852 'post_status' => 'auto-draft', 4853 'exclude_restore_dismissed' => true, 4854 ) 4855 ); 4856 if ( ! empty( $autosave_autodraft_posts ) ) { 4857 $autosave_autodraft_post = array_shift( $autosave_autodraft_posts ); 4858 } 4859 } 4860 } 4861 4862 $current_user_can_publish = current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ); 4863 4864 // @todo Include all of the status labels here from script-loader.php, and then allow it to be filtered. 4865 $status_choices = array(); 4866 if ( $current_user_can_publish ) { 4867 $status_choices[] = array( 4868 'status' => 'publish', 4869 'label' => __( 'Publish' ), 4870 ); 4871 } 4872 $status_choices[] = array( 4873 'status' => 'draft', 4874 'label' => __( 'Save Draft' ), 4875 ); 4876 if ( $current_user_can_publish ) { 4877 $status_choices[] = array( 4878 'status' => 'future', 4879 'label' => _x( 'Schedule', 'customizer changeset action/button label' ), 4880 ); 4881 } 4882 4883 // Prepare Customizer settings to pass to JavaScript. 4884 $changeset_post = null; 4885 if ( $changeset_post_id ) { 4886 $changeset_post = get_post( $changeset_post_id ); 4887 } 4888 4889 // Determine initial date to be at present or future, not past. 4890 $current_time = current_time( 'mysql', false ); 4891 $initial_date = $current_time; 4892 if ( $changeset_post ) { 4893 $initial_date = get_the_time( 'Y-m-d H:i:s', $changeset_post->ID ); 4894 if ( $initial_date < $current_time ) { 4895 $initial_date = $current_time; 4896 } 4897 } 4898 4899 $lock_user_id = false; 4900 if ( $this->changeset_post_id() ) { 4901 $lock_user_id = wp_check_post_lock( $this->changeset_post_id() ); 4902 } 4903 4904 $settings = array( 4905 'changeset' => array( 4906 'uuid' => $this->changeset_uuid(), 4907 'branching' => $this->branching(), 4908 'autosaved' => $this->autosaved(), 4909 'hasAutosaveRevision' => ! empty( $autosave_revision_post ), 4910 'latestAutoDraftUuid' => $autosave_autodraft_post ? $autosave_autodraft_post->post_name : null, 4911 'status' => $changeset_post ? $changeset_post->post_status : '', 4912 'currentUserCanPublish' => $current_user_can_publish, 4913 'publishDate' => $initial_date, 4914 'statusChoices' => $status_choices, 4915 'lockUser' => $lock_user_id ? $this->get_lock_user_data( $lock_user_id ) : null, 4916 ), 4917 'initialServerDate' => $current_time, 4918 'dateFormat' => get_option( 'date_format' ), 4919 'timeFormat' => get_option( 'time_format' ), 4920 'initialServerTimestamp' => floor( microtime( true ) * 1000 ), 4921 'initialClientTimestamp' => -1, // To be set with JS below. 4922 'timeouts' => array( 4923 'windowRefresh' => 250, 4924 'changesetAutoSave' => AUTOSAVE_INTERVAL * 1000, 4925 'keepAliveCheck' => 2500, 4926 'reflowPaneContents' => 100, 4927 'previewFrameSensitivity' => 2000, 4928 ), 4929 'theme' => array( 4930 'stylesheet' => $this->get_stylesheet(), 4931 'active' => $this->is_theme_active(), 4932 '_canInstall' => current_user_can( 'install_themes' ), 4933 ), 4934 'url' => array( 4935 'preview' => sanitize_url( $this->get_preview_url() ), 4936 'return' => sanitize_url( $this->get_return_url() ), 4937 'parent' => sanitize_url( admin_url() ), 4938 'activated' => sanitize_url( home_url( '/' ) ), 4939 'ajax' => sanitize_url( admin_url( 'admin-ajax.php', 'relative' ) ), 4940 'allowed' => array_map( 'sanitize_url', $this->get_allowed_urls() ), 4941 'isCrossDomain' => $this->is_cross_domain(), 4942 'home' => sanitize_url( home_url( '/' ) ), 4943 'login' => sanitize_url( $login_url ), 4944 ), 4945 'browser' => array( 4946 'mobile' => wp_is_mobile(), 4947 'ios' => $this->is_ios(), 4948 ), 4949 'panels' => array(), 4950 'sections' => array(), 4951 'nonce' => $this->get_nonces(), 4952 'autofocus' => $this->get_autofocus(), 4953 'documentTitleTmpl' => $this->get_document_title_template(), 4954 'previewableDevices' => $this->get_previewable_devices(), 4955 'l10n' => array( 4956 'confirmDeleteTheme' => __( 'Are you sure you want to delete this theme?' ), 4957 /* translators: %d: Number of theme search results, which cannot currently consider singular vs. plural forms. */ 4958 'themeSearchResults' => __( '%d themes found' ), 4959 /* translators: %d: Number of themes being displayed, which cannot currently consider singular vs. plural forms. */ 4960 'announceThemeCount' => __( 'Displaying %d themes' ), 4961 /* translators: %s: Theme name. */ 4962 'announceThemeDetails' => __( 'Showing details for theme: %s' ), 4963 ), 4964 ); 4965 4966 // Temporarily disable installation in Customizer. See #42184. 4967 $filesystem_method = get_filesystem_method(); 4968 ob_start(); 4969 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); 4970 ob_end_clean(); 4971 if ( 'direct' !== $filesystem_method && ! $filesystem_credentials_are_stored ) { 4972 $settings['theme']['_filesystemCredentialsNeeded'] = true; 4973 } 4974 4975 // Prepare Customize Section objects to pass to JavaScript. 4976 foreach ( $this->sections() as $id => $section ) { 4977 if ( $section->check_capabilities() ) { 4978 $settings['sections'][ $id ] = $section->json(); 4979 } 4980 } 4981 4982 // Prepare Customize Panel objects to pass to JavaScript. 4983 foreach ( $this->panels() as $panel_id => $panel ) { 4984 if ( $panel->check_capabilities() ) { 4985 $settings['panels'][ $panel_id ] = $panel->json(); 4986 foreach ( $panel->sections as $section_id => $section ) { 4987 if ( $section->check_capabilities() ) { 4988 $settings['sections'][ $section_id ] = $section->json(); 4989 } 4990 } 4991 } 4992 } 4993 4994 ob_start(); 4995 ?> 4996 <script> 4997 var _wpCustomizeSettings = <?php echo wp_json_encode( $settings, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); ?>; 4998 _wpCustomizeSettings.initialClientTimestamp = _.now(); 4999 _wpCustomizeSettings.controls = {}; 5000 _wpCustomizeSettings.settings = {}; 5001 <?php 5002 5003 // Serialize settings one by one to improve memory usage. 5004 echo "(function ( s ){\n"; 5005 foreach ( $this->settings() as $setting ) { 5006 if ( $setting->check_capabilities() ) { 5007 printf( 5008 "s[%s] = %s;\n", 5009 wp_json_encode( $setting->id, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ), 5010 wp_json_encode( $setting->json(), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ) 5011 ); 5012 } 5013 } 5014 echo "})( _wpCustomizeSettings.settings );\n"; 5015 5016 // Serialize controls one by one to improve memory usage. 5017 echo "(function ( c ){\n"; 5018 foreach ( $this->controls() as $control ) { 5019 if ( $control->check_capabilities() ) { 5020 printf( 5021 "c[%s] = %s;\n", 5022 wp_json_encode( $control->id, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ), 5023 wp_json_encode( $control->json(), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ) 5024 ); 5025 } 5026 } 5027 echo "})( _wpCustomizeSettings.controls );\n"; 5028 ?> 5029 </script> 5030 <?php 5031 wp_print_inline_script_tag( wp_remove_surrounding_empty_script_tags( ob_get_clean() ) . "\n//# sourceURL=" . rawurlencode( __METHOD__ ) ); 5032 } 5033 5034 /** 5035 * Returns a list of devices to allow previewing. 5036 * 5037 * @since 4.5.0 5038 * 5039 * @return array List of devices with labels and default setting. 5040 */ 5041 public function get_previewable_devices() { 5042 $devices = array( 5043 'desktop' => array( 5044 'label' => __( 'Desktop' ), 5045 'default' => true, 5046 ), 5047 'tablet' => array( 5048 'label' => __( 'Tablet' ), 5049 ), 5050 'mobile' => array( 5051 'label' => __( 'Mobile' ), 5052 ), 5053 ); 5054 5055 /** 5056 * Filters the available devices to allow previewing in the Customizer. 5057 * 5058 * @since 4.5.0 5059 * 5060 * @see WP_Customize_Manager::get_previewable_devices() 5061 * 5062 * @param array $devices List of devices with labels and default setting. 5063 */ 5064 $devices = apply_filters( 'customize_previewable_devices', $devices ); 5065 5066 return $devices; 5067 } 5068 5069 /** 5070 * Registers some default controls. 5071 * 5072 * @since 3.4.0 5073 */ 5074 public function register_controls() { 5075 5076 /* Themes (controls are loaded via ajax) */ 5077 5078 $this->add_panel( 5079 new WP_Customize_Themes_Panel( 5080 $this, 5081 'themes', 5082 array( 5083 'title' => $this->theme()->display( 'Name' ), 5084 'description' => ( 5085 '<p>' . __( 'Looking for a theme? You can search or browse the WordPress.org theme directory, install and preview themes, then activate them right here.' ) . '</p>' . 5086 '<p>' . __( 'While previewing a new theme, you can continue to tailor things like widgets and menus, and explore theme-specific options.' ) . '</p>' 5087 ), 5088 'capability' => 'switch_themes', 5089 'priority' => 0, 5090 ) 5091 ) 5092 ); 5093 5094 $this->add_section( 5095 new WP_Customize_Themes_Section( 5096 $this, 5097 'installed_themes', 5098 array( 5099 'title' => __( 'Installed themes' ), 5100 'action' => 'installed', 5101 'capability' => 'switch_themes', 5102 'panel' => 'themes', 5103 'priority' => 0, 5104 ) 5105 ) 5106 ); 5107 5108 if ( ! is_multisite() ) { 5109 $this->add_section( 5110 new WP_Customize_Themes_Section( 5111 $this, 5112 'wporg_themes', 5113 array( 5114 'title' => __( 'WordPress.org themes' ), 5115 'action' => 'wporg', 5116 'filter_type' => 'remote', 5117 'capability' => 'install_themes', 5118 'panel' => 'themes', 5119 'priority' => 5, 5120 ) 5121 ) 5122 ); 5123 } 5124 5125 // Themes Setting (unused - the theme is considerably more fundamental to the Customizer experience). 5126 $this->add_setting( 5127 new WP_Customize_Filter_Setting( 5128 $this, 5129 'active_theme', 5130 array( 5131 'capability' => 'switch_themes', 5132 ) 5133 ) 5134 ); 5135 5136 /* Site Identity */ 5137 5138 $this->add_section( 5139 'title_tagline', 5140 array( 5141 'title' => __( 'Site Identity' ), 5142 'priority' => 20, 5143 ) 5144 ); 5145 5146 $this->add_setting( 5147 'blogname', 5148 array( 5149 'default' => get_option( 'blogname' ), 5150 'type' => 'option', 5151 'capability' => 'manage_options', 5152 ) 5153 ); 5154 5155 $this->add_control( 5156 'blogname', 5157 array( 5158 'label' => __( 'Site Title' ), 5159 'section' => 'title_tagline', 5160 ) 5161 ); 5162 5163 $this->add_setting( 5164 'blogdescription', 5165 array( 5166 'default' => get_option( 'blogdescription' ), 5167 'type' => 'option', 5168 'capability' => 'manage_options', 5169 ) 5170 ); 5171 5172 $this->add_control( 5173 'blogdescription', 5174 array( 5175 'label' => __( 'Tagline' ), 5176 'section' => 'title_tagline', 5177 ) 5178 ); 5179 5180 // Add a setting to hide header text if the theme doesn't support custom headers. 5181 if ( ! current_theme_supports( 'custom-header', 'header-text' ) ) { 5182 $this->add_setting( 5183 'header_text', 5184 array( 5185 'theme_supports' => array( 'custom-logo', 'header-text' ), 5186 'default' => 1, 5187 'sanitize_callback' => 'absint', 5188 ) 5189 ); 5190 5191 $this->add_control( 5192 'header_text', 5193 array( 5194 'label' => __( 'Display Site Title and Tagline' ), 5195 'section' => 'title_tagline', 5196 'settings' => 'header_text', 5197 'type' => 'checkbox', 5198 ) 5199 ); 5200 } 5201 5202 $this->add_setting( 5203 'site_icon', 5204 array( 5205 'type' => 'option', 5206 'capability' => 'manage_options', 5207 'transport' => 'postMessage', // Previewed with JS in the Customizer controls window. 5208 ) 5209 ); 5210 5211 $this->add_control( 5212 new WP_Customize_Site_Icon_Control( 5213 $this, 5214 'site_icon', 5215 array( 5216 'label' => __( 'Site Icon' ), 5217 'description' => sprintf( 5218 /* translators: 1: pixel value for icon size. 2: pixel value for icon size. */ 5219 '<p>' . __( 'The Site Icon is what you see in browser tabs, bookmark bars, and within the WordPress mobile apps. It should be square and at least <strong>%1$s by %2$s</strong> pixels.' ) . '</p>', 5220 512, 5221 512 5222 ), 5223 'section' => 'title_tagline', 5224 'priority' => 60, 5225 'height' => 512, 5226 'width' => 512, 5227 ) 5228 ) 5229 ); 5230 5231 $this->add_setting( 5232 'custom_logo', 5233 array( 5234 'theme_supports' => array( 'custom-logo' ), 5235 'transport' => 'postMessage', 5236 ) 5237 ); 5238 5239 $custom_logo_args = get_theme_support( 'custom-logo' ); 5240 $this->add_control( 5241 new WP_Customize_Cropped_Image_Control( 5242 $this, 5243 'custom_logo', 5244 array( 5245 'label' => __( 'Logo' ), 5246 'section' => 'title_tagline', 5247 'priority' => 8, 5248 'height' => $custom_logo_args[0]['height'] ?? null, 5249 'width' => $custom_logo_args[0]['width'] ?? null, 5250 'flex_height' => $custom_logo_args[0]['flex-height'] ?? null, 5251 'flex_width' => $custom_logo_args[0]['flex-width'] ?? null, 5252 'button_labels' => array( 5253 'select' => __( 'Select logo' ), 5254 'change' => __( 'Change logo' ), 5255 'remove' => __( 'Remove' ), 5256 'default' => __( 'Default' ), 5257 'placeholder' => __( 'No logo selected' ), 5258 'frame_title' => __( 'Select logo' ), 5259 'frame_button' => __( 'Choose logo' ), 5260 ), 5261 ) 5262 ) 5263 ); 5264 5265 $this->selective_refresh->add_partial( 5266 'custom_logo', 5267 array( 5268 'settings' => array( 'custom_logo' ), 5269 'selector' => '.custom-logo-link', 5270 'render_callback' => array( $this, '_render_custom_logo_partial' ), 5271 'container_inclusive' => true, 5272 ) 5273 ); 5274 5275 /* Colors */ 5276 5277 $this->add_section( 5278 'colors', 5279 array( 5280 'title' => __( 'Colors' ), 5281 'priority' => 40, 5282 ) 5283 ); 5284 5285 $this->add_setting( 5286 'header_textcolor', 5287 array( 5288 'theme_supports' => array( 'custom-header', 'header-text' ), 5289 'default' => get_theme_support( 'custom-header', 'default-text-color' ), 5290 5291 'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ), 5292 'sanitize_js_callback' => 'maybe_hash_hex_color', 5293 ) 5294 ); 5295 5296 // Input type: checkbox, with custom value. 5297 $this->add_control( 5298 'display_header_text', 5299 array( 5300 'settings' => 'header_textcolor', 5301 'label' => __( 'Display Site Title and Tagline' ), 5302 'section' => 'title_tagline', 5303 'type' => 'checkbox', 5304 'priority' => 40, 5305 ) 5306 ); 5307 5308 $this->add_control( 5309 new WP_Customize_Color_Control( 5310 $this, 5311 'header_textcolor', 5312 array( 5313 'label' => __( 'Header Text Color' ), 5314 'section' => 'colors', 5315 ) 5316 ) 5317 ); 5318 5319 // Input type: color, with sanitize_callback. 5320 $this->add_setting( 5321 'background_color', 5322 array( 5323 'default' => get_theme_support( 'custom-background', 'default-color' ), 5324 'theme_supports' => 'custom-background', 5325 5326 'sanitize_callback' => 'sanitize_hex_color_no_hash', 5327 'sanitize_js_callback' => 'maybe_hash_hex_color', 5328 ) 5329 ); 5330 5331 $this->add_control( 5332 new WP_Customize_Color_Control( 5333 $this, 5334 'background_color', 5335 array( 5336 'label' => __( 'Background Color' ), 5337 'section' => 'colors', 5338 ) 5339 ) 5340 ); 5341 5342 /* Custom Header */ 5343 5344 if ( current_theme_supports( 'custom-header', 'video' ) ) { 5345 $title = __( 'Header Media' ); 5346 $description = '<p>' . __( 'If you add a video, the image will be used as a fallback while the video loads.' ) . '</p>'; 5347 5348 $width = absint( get_theme_support( 'custom-header', 'width' ) ); 5349 $height = absint( get_theme_support( 'custom-header', 'height' ) ); 5350 if ( $width && $height ) { 5351 $control_description = sprintf( 5352 /* translators: 1: .mp4, 2: Header size in pixels. */ 5353 __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends dimensions of %2$s pixels.' ), 5354 '<code>.mp4</code>', 5355 sprintf( '<strong>%s × %s</strong>', $width, $height ) 5356 ); 5357 } elseif ( $width ) { 5358 $control_description = sprintf( 5359 /* translators: 1: .mp4, 2: Header width in pixels. */ 5360 __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a width of %2$s pixels.' ), 5361 '<code>.mp4</code>', 5362 sprintf( '<strong>%s</strong>', $width ) 5363 ); 5364 } else { 5365 $control_description = sprintf( 5366 /* translators: 1: .mp4, 2: Header height in pixels. */ 5367 __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a height of %2$s pixels.' ), 5368 '<code>.mp4</code>', 5369 sprintf( '<strong>%s</strong>', $height ) 5370 ); 5371 } 5372 } else { 5373 $title = __( 'Header Image' ); 5374 $description = ''; 5375 $control_description = ''; 5376 } 5377 5378 $this->add_section( 5379 'header_image', 5380 array( 5381 'title' => $title, 5382 'description' => $description, 5383 'theme_supports' => 'custom-header', 5384 'priority' => 60, 5385 ) 5386 ); 5387 5388 $this->add_setting( 5389 'header_video', 5390 array( 5391 'theme_supports' => array( 'custom-header', 'video' ), 5392 'transport' => 'postMessage', 5393 'sanitize_callback' => 'absint', 5394 'validate_callback' => array( $this, '_validate_header_video' ), 5395 ) 5396 ); 5397 5398 $this->add_setting( 5399 'external_header_video', 5400 array( 5401 'theme_supports' => array( 'custom-header', 'video' ), 5402 'transport' => 'postMessage', 5403 'sanitize_callback' => array( $this, '_sanitize_external_header_video' ), 5404 'validate_callback' => array( $this, '_validate_external_header_video' ), 5405 ) 5406 ); 5407 5408 $this->add_setting( 5409 new WP_Customize_Filter_Setting( 5410 $this, 5411 'header_image', 5412 array( 5413 'default' => sprintf( get_theme_support( 'custom-header', 'default-image' ), get_template_directory_uri(), get_stylesheet_directory_uri() ), 5414 'theme_supports' => 'custom-header', 5415 ) 5416 ) 5417 ); 5418 5419 $this->add_setting( 5420 new WP_Customize_Header_Image_Setting( 5421 $this, 5422 'header_image_data', 5423 array( 5424 'theme_supports' => 'custom-header', 5425 ) 5426 ) 5427 ); 5428 5429 /* 5430 * Switch image settings to postMessage when video support is enabled since 5431 * it entails that the_custom_header_markup() will be used, and thus selective 5432 * refresh can be utilized. 5433 */ 5434 if ( current_theme_supports( 'custom-header', 'video' ) ) { 5435 $this->get_setting( 'header_image' )->transport = 'postMessage'; 5436 $this->get_setting( 'header_image_data' )->transport = 'postMessage'; 5437 } 5438 5439 $this->add_control( 5440 new WP_Customize_Media_Control( 5441 $this, 5442 'header_video', 5443 array( 5444 'theme_supports' => array( 'custom-header', 'video' ), 5445 'label' => __( 'Header Video' ), 5446 'description' => $control_description, 5447 'section' => 'header_image', 5448 'mime_type' => 'video', 5449 'active_callback' => 'is_header_video_active', 5450 ) 5451 ) 5452 ); 5453 5454 $this->add_control( 5455 'external_header_video', 5456 array( 5457 'theme_supports' => array( 'custom-header', 'video' ), 5458 'type' => 'url', 5459 'description' => __( 'Or, enter a YouTube URL:' ), 5460 'section' => 'header_image', 5461 'active_callback' => 'is_header_video_active', 5462 ) 5463 ); 5464 5465 $this->add_control( new WP_Customize_Header_Image_Control( $this ) ); 5466 5467 $this->selective_refresh->add_partial( 5468 'custom_header', 5469 array( 5470 'selector' => '#wp-custom-header', 5471 'render_callback' => 'the_custom_header_markup', 5472 'settings' => array( 'header_video', 'external_header_video', 'header_image' ), // The image is used as a video fallback here. 5473 'container_inclusive' => true, 5474 ) 5475 ); 5476 5477 /* Custom Background */ 5478 5479 $this->add_section( 5480 'background_image', 5481 array( 5482 'title' => __( 'Background Image' ), 5483 'theme_supports' => 'custom-background', 5484 'priority' => 80, 5485 ) 5486 ); 5487 5488 $this->add_setting( 5489 'background_image', 5490 array( 5491 'default' => get_theme_support( 'custom-background', 'default-image' ), 5492 'theme_supports' => 'custom-background', 5493 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5494 ) 5495 ); 5496 5497 $this->add_setting( 5498 new WP_Customize_Background_Image_Setting( 5499 $this, 5500 'background_image_thumb', 5501 array( 5502 'theme_supports' => 'custom-background', 5503 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5504 ) 5505 ) 5506 ); 5507 5508 $this->add_control( new WP_Customize_Background_Image_Control( $this ) ); 5509 5510 $this->add_setting( 5511 'background_preset', 5512 array( 5513 'default' => get_theme_support( 'custom-background', 'default-preset' ), 5514 'theme_supports' => 'custom-background', 5515 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5516 ) 5517 ); 5518 5519 $this->add_control( 5520 'background_preset', 5521 array( 5522 'label' => _x( 'Preset', 'Background Preset' ), 5523 'section' => 'background_image', 5524 'type' => 'select', 5525 'choices' => array( 5526 'default' => _x( 'Default', 'Default Preset' ), 5527 'fill' => __( 'Fill Screen' ), 5528 'fit' => __( 'Fit to Screen' ), 5529 'repeat' => _x( 'Repeat', 'Repeat Image' ), 5530 'custom' => _x( 'Custom', 'Custom Preset' ), 5531 ), 5532 ) 5533 ); 5534 5535 $this->add_setting( 5536 'background_position_x', 5537 array( 5538 'default' => get_theme_support( 'custom-background', 'default-position-x' ), 5539 'theme_supports' => 'custom-background', 5540 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5541 ) 5542 ); 5543 5544 $this->add_setting( 5545 'background_position_y', 5546 array( 5547 'default' => get_theme_support( 'custom-background', 'default-position-y' ), 5548 'theme_supports' => 'custom-background', 5549 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5550 ) 5551 ); 5552 5553 $this->add_control( 5554 new WP_Customize_Background_Position_Control( 5555 $this, 5556 'background_position', 5557 array( 5558 'label' => __( 'Image Position' ), 5559 'section' => 'background_image', 5560 'settings' => array( 5561 'x' => 'background_position_x', 5562 'y' => 'background_position_y', 5563 ), 5564 ) 5565 ) 5566 ); 5567 5568 $this->add_setting( 5569 'background_size', 5570 array( 5571 'default' => get_theme_support( 'custom-background', 'default-size' ), 5572 'theme_supports' => 'custom-background', 5573 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5574 ) 5575 ); 5576 5577 $this->add_control( 5578 'background_size', 5579 array( 5580 'label' => __( 'Image Size' ), 5581 'section' => 'background_image', 5582 'type' => 'select', 5583 'choices' => array( 5584 'auto' => _x( 'Original', 'Original Size' ), 5585 'contain' => __( 'Fit to Screen' ), 5586 'cover' => __( 'Fill Screen' ), 5587 ), 5588 ) 5589 ); 5590 5591 $this->add_setting( 5592 'background_repeat', 5593 array( 5594 'default' => get_theme_support( 'custom-background', 'default-repeat' ), 5595 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5596 'theme_supports' => 'custom-background', 5597 ) 5598 ); 5599 5600 $this->add_control( 5601 'background_repeat', 5602 array( 5603 'label' => __( 'Repeat Background Image' ), 5604 'section' => 'background_image', 5605 'type' => 'checkbox', 5606 ) 5607 ); 5608 5609 $this->add_setting( 5610 'background_attachment', 5611 array( 5612 'default' => get_theme_support( 'custom-background', 'default-attachment' ), 5613 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 5614 'theme_supports' => 'custom-background', 5615 ) 5616 ); 5617 5618 $this->add_control( 5619 'background_attachment', 5620 array( 5621 'label' => __( 'Scroll with Page' ), 5622 'section' => 'background_image', 5623 'type' => 'checkbox', 5624 ) 5625 ); 5626 5627 /* 5628 * If the theme is using the default background callback, we can update 5629 * the background CSS using postMessage. 5630 */ 5631 if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) { 5632 foreach ( array( 'color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment' ) as $prop ) { 5633 $this->get_setting( 'background_' . $prop )->transport = 'postMessage'; 5634 } 5635 } 5636 5637 /* 5638 * Static Front Page 5639 * See also https://core.trac.wordpress.org/ticket/19627 which introduces the static-front-page theme_support. 5640 * The following replicates behavior from options-reading.php. 5641 */ 5642 5643 $this->add_section( 5644 'static_front_page', 5645 array( 5646 'title' => __( 'Homepage Settings' ), 5647 'priority' => 120, 5648 'description' => __( 'You can choose what’s displayed on the homepage of your site. It can be posts in reverse chronological order (classic blog), or a fixed/static page. To set a static homepage, you first need to create two Pages. One will become the homepage, and the other will be where your posts are displayed.' ), 5649 'active_callback' => array( $this, 'has_published_pages' ), 5650 ) 5651 ); 5652 5653 $this->add_setting( 5654 'show_on_front', 5655 array( 5656 'default' => get_option( 'show_on_front' ), 5657 'capability' => 'manage_options', 5658 'type' => 'option', 5659 ) 5660 ); 5661 5662 $this->add_control( 5663 'show_on_front', 5664 array( 5665 'label' => __( 'Your homepage displays' ), 5666 'section' => 'static_front_page', 5667 'type' => 'radio', 5668 'choices' => array( 5669 'posts' => __( 'Your latest posts' ), 5670 'page' => __( 'A static page' ), 5671 ), 5672 ) 5673 ); 5674 5675 $this->add_setting( 5676 'page_on_front', 5677 array( 5678 'type' => 'option', 5679 'capability' => 'manage_options', 5680 ) 5681 ); 5682 5683 $this->add_control( 5684 'page_on_front', 5685 array( 5686 'label' => __( 'Homepage' ), 5687 'section' => 'static_front_page', 5688 'type' => 'dropdown-pages', 5689 'allow_addition' => true, 5690 ) 5691 ); 5692 5693 $this->add_setting( 5694 'page_for_posts', 5695 array( 5696 'type' => 'option', 5697 'capability' => 'manage_options', 5698 ) 5699 ); 5700 5701 $this->add_control( 5702 'page_for_posts', 5703 array( 5704 'label' => __( 'Posts page' ), 5705 'section' => 'static_front_page', 5706 'type' => 'dropdown-pages', 5707 'allow_addition' => true, 5708 ) 5709 ); 5710 5711 /* Custom CSS */ 5712 $section_description = '<p>'; 5713 $section_description .= __( 'Add your own CSS code here to customize the appearance and layout of your site.' ); 5714 $section_description .= sprintf( 5715 ' <a href="%1$s" class="external-link" target="_blank">%2$s<span class="screen-reader-text"> %3$s</span></a>', 5716 esc_url( __( 'https://developer.wordpress.org/advanced-administration/wordpress/css/' ) ), 5717 __( 'Learn more about CSS' ), 5718 /* translators: Hidden accessibility text. */ 5719 __( '(opens in a new tab)' ) 5720 ); 5721 $section_description .= '</p>'; 5722 5723 $section_description .= '<p id="editor-keyboard-trap-help-1">' . __( 'When using a keyboard to navigate:' ) . '</p>'; 5724 $section_description .= '<ul>'; 5725 $section_description .= '<li id="editor-keyboard-trap-help-2">' . __( 'In the editing area, the Tab key enters a tab character.' ) . '</li>'; 5726 $section_description .= '<li id="editor-keyboard-trap-help-3">' . __( 'To move away from this area, press the Esc key followed by the Tab key.' ) . '</li>'; 5727 $section_description .= '<li id="editor-keyboard-trap-help-4">' . __( 'Screen reader users: when in forms mode, you may need to press the Esc key twice.' ) . '</li>'; 5728 $section_description .= '</ul>'; 5729 5730 if ( 'false' !== wp_get_current_user()->syntax_highlighting ) { 5731 $section_description .= '<p>'; 5732 $section_description .= sprintf( 5733 /* translators: 1: Link to user profile, 2: Additional link attributes, 3: Accessibility text. */ 5734 __( 'The edit field automatically highlights code syntax. You can disable this in your <a href="%1$s" %2$s>user profile%3$s</a> to work in plain text mode.' ), 5735 esc_url( get_edit_profile_url() ), 5736 'class="external-link" target="_blank"', 5737 sprintf( 5738 '<span class="screen-reader-text"> %s</span>', 5739 /* translators: Hidden accessibility text. */ 5740 __( '(opens in a new tab)' ) 5741 ) 5742 ); 5743 $section_description .= '</p>'; 5744 } 5745 5746 $section_description .= '<p class="section-description-buttons">'; 5747 $section_description .= '<button type="button" class="button-link section-description-close">' . __( 'Close' ) . '</button>'; 5748 $section_description .= '</p>'; 5749 5750 $this->add_section( 5751 'custom_css', 5752 array( 5753 'title' => __( 'Additional CSS' ), 5754 'priority' => 200, 5755 'description_hidden' => true, 5756 'description' => $section_description, 5757 ) 5758 ); 5759 5760 $custom_css_setting = new WP_Customize_Custom_CSS_Setting( 5761 $this, 5762 sprintf( 'custom_css[%s]', get_stylesheet() ), 5763 array( 5764 'capability' => 'edit_css', 5765 'default' => '', 5766 ) 5767 ); 5768 $this->add_setting( $custom_css_setting ); 5769 5770 $this->add_control( 5771 new WP_Customize_Code_Editor_Control( 5772 $this, 5773 'custom_css', 5774 array( 5775 'label' => __( 'CSS code' ), 5776 'section' => 'custom_css', 5777 'settings' => array( 'default' => $custom_css_setting->id ), 5778 'code_type' => 'text/css', 5779 'input_attrs' => array( 5780 'aria-describedby' => 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4', 5781 ), 5782 ) 5783 ) 5784 ); 5785 } 5786 5787 /** 5788 * Returns whether there are published pages. 5789 * 5790 * Used as active callback for static front page section and controls. 5791 * 5792 * @since 4.7.0 5793 * 5794 * @return bool Whether there are published (or to be published) pages. 5795 */ 5796 public function has_published_pages() { 5797 5798 $setting = $this->get_setting( 'nav_menus_created_posts' ); 5799 if ( $setting ) { 5800 foreach ( $setting->value() as $post_id ) { 5801 if ( 'page' === get_post_type( $post_id ) ) { 5802 return true; 5803 } 5804 } 5805 } 5806 5807 return 0 !== count( 5808 get_pages( 5809 array( 5810 'number' => 1, 5811 'hierarchical' => 0, 5812 ) 5813 ) 5814 ); 5815 } 5816 5817 /** 5818 * Adds settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets 5819 * 5820 * @since 4.2.0 5821 * 5822 * @see add_dynamic_settings() 5823 */ 5824 public function register_dynamic_settings() { 5825 $setting_ids = array_keys( $this->unsanitized_post_values() ); 5826 $this->add_dynamic_settings( $setting_ids ); 5827 } 5828 5829 /** 5830 * Loads themes into the theme browsing/installation UI. 5831 * 5832 * @since 4.9.0 5833 * 5834 * @return never 5835 */ 5836 public function handle_load_themes_request() { 5837 check_ajax_referer( 'switch_themes', 'nonce' ); 5838 5839 if ( ! current_user_can( 'switch_themes' ) ) { 5840 wp_die( -1 ); 5841 } 5842 5843 if ( empty( $_POST['theme_action'] ) ) { 5844 wp_send_json_error( 'missing_theme_action' ); 5845 } 5846 $theme_action = sanitize_key( $_POST['theme_action'] ); 5847 $themes = array(); 5848 $args = array(); 5849 5850 // Define query filters based on user input. 5851 if ( ! array_key_exists( 'search', $_POST ) ) { 5852 $args['search'] = ''; 5853 } else { 5854 $args['search'] = sanitize_text_field( wp_unslash( $_POST['search'] ) ); 5855 } 5856 5857 if ( ! array_key_exists( 'tags', $_POST ) ) { 5858 $args['tag'] = ''; 5859 } else { 5860 $args['tag'] = array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['tags'] ) ); 5861 } 5862 5863 if ( ! array_key_exists( 'page', $_POST ) ) { 5864 $args['page'] = 1; 5865 } else { 5866 $args['page'] = absint( $_POST['page'] ); 5867 } 5868 5869 require_once ABSPATH . 'wp-admin/includes/theme.php'; 5870 5871 if ( 'installed' === $theme_action ) { 5872 5873 // Load all installed themes from wp_prepare_themes_for_js(). 5874 $themes = array( 'themes' => array() ); 5875 foreach ( wp_prepare_themes_for_js() as $theme ) { 5876 $theme['type'] = 'installed'; 5877 $theme['active'] = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme['id'] ); 5878 $themes['themes'][] = $theme; 5879 } 5880 } elseif ( 'wporg' === $theme_action ) { 5881 5882 // Load WordPress.org themes from the .org API and normalize data to match installed theme objects. 5883 if ( ! current_user_can( 'install_themes' ) ) { 5884 wp_die( -1 ); 5885 } 5886 5887 // Arguments for all queries. 5888 $wporg_args = array( 5889 'per_page' => 100, 5890 'fields' => array( 5891 'reviews_url' => true, // Explicitly request the reviews URL to be linked from the customizer. 5892 ), 5893 ); 5894 5895 $args = array_merge( $wporg_args, $args ); 5896 5897 if ( '' === $args['search'] && '' === $args['tag'] ) { 5898 $args['browse'] = 'new'; // Sort by latest themes by default. 5899 } 5900 5901 // Load themes from the .org API. 5902 $themes = themes_api( 'query_themes', $args ); 5903 if ( is_wp_error( $themes ) ) { 5904 wp_send_json_error(); 5905 } 5906 5907 // This list matches the allowed tags in wp-admin/includes/theme-install.php. 5908 $themes_allowedtags = array_fill_keys( 5909 array( 'a', 'abbr', 'acronym', 'code', 'pre', 'em', 'strong', 'div', 'p', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'img' ), 5910 array() 5911 ); 5912 $themes_allowedtags['a'] = array_fill_keys( array( 'href', 'title', 'target' ), true ); 5913 $themes_allowedtags['acronym']['title'] = true; 5914 $themes_allowedtags['abbr']['title'] = true; 5915 $themes_allowedtags['img'] = array_fill_keys( array( 'src', 'class', 'alt' ), true ); 5916 5917 // Prepare a list of installed themes to check against before the loop. 5918 $installed_themes = array(); 5919 $wp_themes = wp_get_themes(); 5920 foreach ( $wp_themes as $theme ) { 5921 $installed_themes[] = $theme->get_stylesheet(); 5922 } 5923 $update_php = network_admin_url( 'update.php?action=install-theme' ); 5924 5925 // Set up properties for themes available on WordPress.org. 5926 foreach ( $themes->themes as &$theme ) { 5927 $theme->install_url = add_query_arg( 5928 array( 5929 'theme' => $theme->slug, 5930 '_wpnonce' => wp_create_nonce( 'install-theme_' . $theme->slug ), 5931 ), 5932 $update_php 5933 ); 5934 5935 $theme->name = wp_kses( $theme->name, $themes_allowedtags ); 5936 $theme->version = wp_kses( $theme->version, $themes_allowedtags ); 5937 $theme->description = wp_kses( $theme->description, $themes_allowedtags ); 5938 $theme->stars = wp_star_rating( 5939 array( 5940 'rating' => $theme->rating, 5941 'type' => 'percent', 5942 'number' => $theme->num_ratings, 5943 'echo' => false, 5944 ) 5945 ); 5946 $theme->num_ratings = number_format_i18n( $theme->num_ratings ); 5947 $theme->preview_url = set_url_scheme( $theme->preview_url ); 5948 5949 // Handle themes that are already installed as installed themes. 5950 if ( in_array( $theme->slug, $installed_themes, true ) ) { 5951 $theme->type = 'installed'; 5952 } else { 5953 $theme->type = $theme_action; 5954 } 5955 5956 // Set active based on customized theme. 5957 $theme->active = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme->slug ); 5958 5959 // Map available theme properties to installed theme properties. 5960 $theme->id = $theme->slug; 5961 $theme->screenshot = array( $theme->screenshot_url ); 5962 $theme->authorAndUri = wp_kses( $theme->author['display_name'], $themes_allowedtags ); 5963 $theme->compatibleWP = is_wp_version_compatible( $theme->requires ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName 5964 $theme->compatiblePHP = is_php_version_compatible( $theme->requires_php ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName 5965 5966 if ( isset( $theme->parent ) ) { 5967 $theme->parent = $theme->parent['slug']; 5968 } else { 5969 $theme->parent = false; 5970 } 5971 unset( $theme->slug ); 5972 unset( $theme->screenshot_url ); 5973 unset( $theme->author ); 5974 } // End foreach(). 5975 } // End if(). 5976 5977 /** 5978 * Filters the theme data loaded in the customizer. 5979 * 5980 * This allows theme data to be loading from an external source, 5981 * or modification of data loaded from `wp_prepare_themes_for_js()` 5982 * or WordPress.org via `themes_api()`. 5983 * 5984 * @since 4.9.0 5985 * 5986 * @see wp_prepare_themes_for_js() 5987 * @see themes_api() 5988 * @see WP_Customize_Manager::__construct() 5989 * 5990 * @param array|stdClass $themes Nested array or object of theme data. 5991 * @param array $args List of arguments, such as page, search term, and tags to query for. 5992 * @param WP_Customize_Manager $manager Instance of Customize manager. 5993 */ 5994 $themes = apply_filters( 'customize_load_themes', $themes, $args, $this ); 5995 5996 wp_send_json_success( $themes ); 5997 } 5998 5999 6000 /** 6001 * Callback for validating the header_textcolor value. 6002 * 6003 * Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash(). 6004 * Returns default text color if hex color is empty. 6005 * 6006 * @since 3.4.0 6007 * 6008 * @param string $color 6009 * @return mixed 6010 */ 6011 public function _sanitize_header_textcolor( $color ) { 6012 if ( 'blank' === $color ) { 6013 return 'blank'; 6014 } 6015 6016 $color = sanitize_hex_color_no_hash( $color ); 6017 if ( empty( $color ) ) { 6018 $color = get_theme_support( 'custom-header', 'default-text-color' ); 6019 } 6020 6021 return $color; 6022 } 6023 6024 /** 6025 * Callback for validating a background setting value. 6026 * 6027 * @since 4.7.0 6028 * 6029 * @param string $value Repeat value. 6030 * @param WP_Customize_Setting $setting Setting. 6031 * @return string|WP_Error Background value or validation error. 6032 */ 6033 public function _sanitize_background_setting( $value, $setting ) { 6034 if ( 'background_repeat' === $setting->id ) { 6035 if ( ! in_array( $value, array( 'repeat-x', 'repeat-y', 'repeat', 'no-repeat' ), true ) ) { 6036 return new WP_Error( 'invalid_value', __( 'Invalid value for background repeat.' ) ); 6037 } 6038 } elseif ( 'background_attachment' === $setting->id ) { 6039 if ( ! in_array( $value, array( 'fixed', 'scroll' ), true ) ) { 6040 return new WP_Error( 'invalid_value', __( 'Invalid value for background attachment.' ) ); 6041 } 6042 } elseif ( 'background_position_x' === $setting->id ) { 6043 if ( ! in_array( $value, array( 'left', 'center', 'right' ), true ) ) { 6044 return new WP_Error( 'invalid_value', __( 'Invalid value for background position X.' ) ); 6045 } 6046 } elseif ( 'background_position_y' === $setting->id ) { 6047 if ( ! in_array( $value, array( 'top', 'center', 'bottom' ), true ) ) { 6048 return new WP_Error( 'invalid_value', __( 'Invalid value for background position Y.' ) ); 6049 } 6050 } elseif ( 'background_size' === $setting->id ) { 6051 if ( ! in_array( $value, array( 'auto', 'contain', 'cover' ), true ) ) { 6052 return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) ); 6053 } 6054 } elseif ( 'background_preset' === $setting->id ) { 6055 if ( ! in_array( $value, array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) { 6056 return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) ); 6057 } 6058 } elseif ( 'background_image' === $setting->id || 'background_image_thumb' === $setting->id ) { 6059 $value = empty( $value ) ? '' : sanitize_url( $value ); 6060 } else { 6061 return new WP_Error( 'unrecognized_setting', __( 'Unrecognized background setting.' ) ); 6062 } 6063 return $value; 6064 } 6065 6066 /** 6067 * Exports header video settings to facilitate selective refresh. 6068 * 6069 * @since 4.7.0 6070 * 6071 * @param array $response Response. 6072 * @param WP_Customize_Selective_Refresh $selective_refresh Selective refresh component. 6073 * @param array $partials Array of partials. 6074 * @return array 6075 */ 6076 public function export_header_video_settings( $response, $selective_refresh, $partials ) { 6077 if ( isset( $partials['custom_header'] ) ) { 6078 $response['custom_header_settings'] = get_header_video_settings(); 6079 } 6080 6081 return $response; 6082 } 6083 6084 /** 6085 * Callback for validating the header_video value. 6086 * 6087 * Ensures that the selected video is less than 8MB and provides an error message. 6088 * 6089 * @since 4.7.0 6090 * 6091 * @param WP_Error $validity 6092 * @param mixed $value 6093 * @return mixed 6094 */ 6095 public function _validate_header_video( $validity, $value ) { 6096 $video = get_attached_file( absint( $value ) ); 6097 if ( $video ) { 6098 $size = filesize( $video ); 6099 if ( $size > 8 * MB_IN_BYTES ) { 6100 $validity->add( 6101 'size_too_large', 6102 __( 'This video file is too large to use as a header video. Try a shorter video or optimize the compression settings and re-upload a file that is less than 8MB. Or, upload your video to YouTube and link it with the option below.' ) 6103 ); 6104 } 6105 if ( ! str_ends_with( $video, '.mp4' ) && ! str_ends_with( $video, '.mov' ) ) { // Check for .mp4 or .mov format, which (assuming h.264 encoding) are the only cross-browser-supported formats. 6106 $validity->add( 6107 'invalid_file_type', 6108 sprintf( 6109 /* translators: 1: .mp4, 2: .mov */ 6110 __( 'Only %1$s or %2$s files may be used for header video. Please convert your video file and try again, or, upload your video to YouTube and link it with the option below.' ), 6111 '<code>.mp4</code>', 6112 '<code>.mov</code>' 6113 ) 6114 ); 6115 } 6116 } 6117 return $validity; 6118 } 6119 6120 /** 6121 * Callback for validating the external_header_video value. 6122 * 6123 * Ensures that the provided URL is supported. 6124 * 6125 * @since 4.7.0 6126 * 6127 * @param WP_Error $validity 6128 * @param mixed $value 6129 * @return mixed 6130 */ 6131 public function _validate_external_header_video( $validity, $value ) { 6132 $video = sanitize_url( $value ); 6133 if ( $video ) { 6134 if ( ! preg_match( '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#', $video ) ) { 6135 $validity->add( 'invalid_url', __( 'Please enter a valid YouTube URL.' ) ); 6136 } 6137 } 6138 return $validity; 6139 } 6140 6141 /** 6142 * Callback for sanitizing the external_header_video value. 6143 * 6144 * @since 4.7.1 6145 * 6146 * @param string $value URL. 6147 * @return string Sanitized URL. 6148 */ 6149 public function _sanitize_external_header_video( $value ) { 6150 return sanitize_url( trim( $value ) ); 6151 } 6152 6153 /** 6154 * Callback for rendering the custom logo, used in the custom_logo partial. 6155 * 6156 * This method exists because the partial object and context data are passed 6157 * into a partial's render_callback so we cannot use get_custom_logo() as 6158 * the render_callback directly since it expects a blog ID as the first 6159 * argument. 6160 * 6161 * @see WP_Customize_Manager::register_controls() 6162 * 6163 * @since 4.5.0 6164 * 6165 * @return string Custom logo. 6166 */ 6167 public function _render_custom_logo_partial() { 6168 return get_custom_logo(); 6169 } 6170 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Fri Jul 24 08:20:19 2026 | Cross-referenced by PHPXref |