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