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