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