[ Index ] |
WordPress 5.4.1 |
[ Index ] [ Classes ] [ Functions ] [ Variables ] [ Constants ] [ Statistics ] |
[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 final class WP_Customize_Manager { 24 /** 25 * An instance of the theme being previewed. 26 * 27 * @since 3.4.0 28 * @var WP_Theme 29 */ 30 protected $theme; 31 32 /** 33 * The directory name of the previously active theme (within the theme_root). 34 * 35 * @since 3.4.0 36 * @var string 37 */ 38 protected $original_stylesheet; 39 40 /** 41 * Whether this is a Customizer pageload. 42 * 43 * @since 3.4.0 44 * @var bool 45 */ 46 protected $previewing = false; 47 48 /** 49 * Methods and properties dealing with managing widgets in the Customizer. 50 * 51 * @since 3.9.0 52 * @var WP_Customize_Widgets 53 */ 54 public $widgets; 55 56 /** 57 * Methods and properties dealing with managing nav menus in the Customizer. 58 * 59 * @since 4.3.0 60 * @var WP_Customize_Nav_Menus 61 */ 62 public $nav_menus; 63 64 /** 65 * Methods and properties dealing with selective refresh in the Customizer preview. 66 * 67 * @since 4.5.0 68 * @var WP_Customize_Selective_Refresh 69 */ 70 public $selective_refresh; 71 72 /** 73 * Registered instances of WP_Customize_Setting. 74 * 75 * @since 3.4.0 76 * @var array 77 */ 78 protected $settings = array(); 79 80 /** 81 * Sorted top-level instances of WP_Customize_Panel and WP_Customize_Section. 82 * 83 * @since 4.0.0 84 * @var array 85 */ 86 protected $containers = array(); 87 88 /** 89 * Registered instances of WP_Customize_Panel. 90 * 91 * @since 4.0.0 92 * @var array 93 */ 94 protected $panels = array(); 95 96 /** 97 * List of core components. 98 * 99 * @since 4.5.0 100 * @var array 101 */ 102 protected $components = array( 'widgets', 'nav_menus' ); 103 104 /** 105 * Registered instances of WP_Customize_Section. 106 * 107 * @since 3.4.0 108 * @var array 109 */ 110 protected $sections = array(); 111 112 /** 113 * Registered instances of WP_Customize_Control. 114 * 115 * @since 3.4.0 116 * @var array 117 */ 118 protected $controls = array(); 119 120 /** 121 * Panel types that may be rendered from JS templates. 122 * 123 * @since 4.3.0 124 * @var array 125 */ 126 protected $registered_panel_types = array(); 127 128 /** 129 * Section types that may be rendered from JS templates. 130 * 131 * @since 4.3.0 132 * @var array 133 */ 134 protected $registered_section_types = array(); 135 136 /** 137 * Control types that may be rendered from JS templates. 138 * 139 * @since 4.1.0 140 * @var array 141 */ 142 protected $registered_control_types = array(); 143 144 /** 145 * Initial URL being previewed. 146 * 147 * @since 4.4.0 148 * @var string 149 */ 150 protected $preview_url; 151 152 /** 153 * URL to link the user to when closing the Customizer. 154 * 155 * @since 4.4.0 156 * @var string 157 */ 158 protected $return_url; 159 160 /** 161 * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. 162 * 163 * @since 4.4.0 164 * @var array 165 */ 166 protected $autofocus = array(); 167 168 /** 169 * Messenger channel. 170 * 171 * @since 4.7.0 172 * @var string 173 */ 174 protected $messenger_channel; 175 176 /** 177 * Whether the autosave revision of the changeset should be loaded. 178 * 179 * @since 4.9.0 180 * @var bool 181 */ 182 protected $autosaved = false; 183 184 /** 185 * Whether the changeset branching is allowed. 186 * 187 * @since 4.9.0 188 * @var bool 189 */ 190 protected $branching = true; 191 192 /** 193 * Whether settings should be previewed. 194 * 195 * @since 4.9.0 196 * @var bool 197 */ 198 protected $settings_previewed = true; 199 200 /** 201 * Whether a starter content changeset was saved. 202 * 203 * @since 4.9.0 204 * @var bool 205 */ 206 protected $saved_starter_content_changeset = false; 207 208 /** 209 * Unsanitized values for Customize Settings parsed from $_POST['customized']. 210 * 211 * @var array 212 */ 213 private $_post_values; 214 215 /** 216 * Changeset UUID. 217 * 218 * @since 4.7.0 219 * @var string 220 */ 221 private $_changeset_uuid; 222 223 /** 224 * Changeset post ID. 225 * 226 * @since 4.7.0 227 * @var int|false 228 */ 229 private $_changeset_post_id; 230 231 /** 232 * Changeset data loaded from a customize_changeset post. 233 * 234 * @since 4.7.0 235 * @var array|null 236 */ 237 private $_changeset_data; 238 239 /** 240 * Constructor. 241 * 242 * @since 3.4.0 243 * @since 4.7.0 Added `$args` parameter. 244 * 245 * @param array $args { 246 * Args. 247 * 248 * @type null|string|false $changeset_uuid Changeset UUID, the `post_name` for the customize_changeset post containing the customized state. 249 * Defaults to `null` resulting in a UUID to be immediately generated. If `false` is provided, then 250 * then the changeset UUID will be determined during `after_setup_theme`: when the 251 * `customize_changeset_branching` filter returns false, then the default UUID will be that 252 * of the most recent `customize_changeset` post that has a status other than 'auto-draft', 253 * 'publish', or 'trash'. Otherwise, if changeset branching is enabled, then a random UUID will be used. 254 * @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params. 255 * @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param. 256 * @type bool $settings_previewed If settings should be previewed. Defaults to true. 257 * @type bool $branching If changeset branching is allowed; otherwise, changesets are linear. Defaults to true. 258 * @type bool $autosaved If data from a changeset's autosaved revision should be loaded if it exists. Defaults to false. 259 * } 260 */ 261 public function __construct( $args = array() ) { 262 263 $args = array_merge( 264 array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed', 'autosaved', 'branching' ), null ), 265 $args 266 ); 267 268 // Note that the UUID format will be validated in the setup_theme() method. 269 if ( ! isset( $args['changeset_uuid'] ) ) { 270 $args['changeset_uuid'] = wp_generate_uuid4(); 271 } 272 273 // The theme and messenger_channel should be supplied via $args, 274 // but they are also looked at in the $_REQUEST global here for back-compat. 275 if ( ! isset( $args['theme'] ) ) { 276 if ( isset( $_REQUEST['customize_theme'] ) ) { 277 $args['theme'] = wp_unslash( $_REQUEST['customize_theme'] ); 278 } elseif ( isset( $_REQUEST['theme'] ) ) { // Deprecated. 279 $args['theme'] = wp_unslash( $_REQUEST['theme'] ); 280 } 281 } 282 if ( ! isset( $args['messenger_channel'] ) && isset( $_REQUEST['customize_messenger_channel'] ) ) { 283 $args['messenger_channel'] = sanitize_key( wp_unslash( $_REQUEST['customize_messenger_channel'] ) ); 284 } 285 286 $this->original_stylesheet = get_stylesheet(); 287 $this->theme = wp_get_theme( 0 === validate_file( $args['theme'] ) ? $args['theme'] : null ); 288 $this->messenger_channel = $args['messenger_channel']; 289 $this->_changeset_uuid = $args['changeset_uuid']; 290 291 foreach ( array( 'settings_previewed', 'autosaved', 'branching' ) as $key ) { 292 if ( isset( $args[ $key ] ) ) { 293 $this->$key = (bool) $args[ $key ]; 294 } 295 } 296 297 require_once ABSPATH . WPINC . '/class-wp-customize-setting.php'; 298 require_once ABSPATH . WPINC . '/class-wp-customize-panel.php'; 299 require_once ABSPATH . WPINC . '/class-wp-customize-section.php'; 300 require_once ABSPATH . WPINC . '/class-wp-customize-control.php'; 301 302 require_once ABSPATH . WPINC . '/customize/class-wp-customize-color-control.php'; 303 require_once ABSPATH . WPINC . '/customize/class-wp-customize-media-control.php'; 304 require_once ABSPATH . WPINC . '/customize/class-wp-customize-upload-control.php'; 305 require_once ABSPATH . WPINC . '/customize/class-wp-customize-image-control.php'; 306 require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-control.php'; 307 require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-position-control.php'; 308 require_once ABSPATH . WPINC . '/customize/class-wp-customize-cropped-image-control.php'; 309 require_once ABSPATH . WPINC . '/customize/class-wp-customize-site-icon-control.php'; 310 require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-control.php'; 311 require_once ABSPATH . WPINC . '/customize/class-wp-customize-theme-control.php'; 312 require_once ABSPATH . WPINC . '/customize/class-wp-customize-code-editor-control.php'; 313 require_once ABSPATH . WPINC . '/customize/class-wp-widget-area-customize-control.php'; 314 require_once ABSPATH . WPINC . '/customize/class-wp-widget-form-customize-control.php'; 315 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-control.php'; 316 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-control.php'; 317 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-location-control.php'; 318 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-name-control.php'; 319 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-locations-control.php'; 320 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-auto-add-control.php'; 321 322 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menus-panel.php'; 323 324 require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-panel.php'; 325 require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-section.php'; 326 require_once ABSPATH . WPINC . '/customize/class-wp-customize-sidebar-section.php'; 327 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-section.php'; 328 329 require_once ABSPATH . WPINC . '/customize/class-wp-customize-custom-css-setting.php'; 330 require_once ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php'; 331 require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php'; 332 require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php'; 333 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php'; 334 require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php'; 335 336 /** 337 * Filters the core Customizer components to load. 338 * 339 * This allows Core components to be excluded from being instantiated by 340 * filtering them out of the array. Note that this filter generally runs 341 * during the {@see 'plugins_loaded'} action, so it cannot be added 342 * in a theme. 343 * 344 * @since 4.4.0 345 * 346 * @see WP_Customize_Manager::__construct() 347 * 348 * @param string[] $components Array of core components to load. 349 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 350 */ 351 $components = apply_filters( 'customize_loaded_components', $this->components, $this ); 352 353 require_once ABSPATH . WPINC . '/customize/class-wp-customize-selective-refresh.php'; 354 $this->selective_refresh = new WP_Customize_Selective_Refresh( $this ); 355 356 if ( in_array( 'widgets', $components, true ) ) { 357 require_once ABSPATH . WPINC . '/class-wp-customize-widgets.php'; 358 $this->widgets = new WP_Customize_Widgets( $this ); 359 } 360 361 if ( in_array( 'nav_menus', $components, true ) ) { 362 require_once ABSPATH . WPINC . '/class-wp-customize-nav-menus.php'; 363 $this->nav_menus = new WP_Customize_Nav_Menus( $this ); 364 } 365 366 add_action( 'setup_theme', array( $this, 'setup_theme' ) ); 367 add_action( 'wp_loaded', array( $this, 'wp_loaded' ) ); 368 369 // Do not spawn cron (especially the alternate cron) while running the Customizer. 370 remove_action( 'init', 'wp_cron' ); 371 372 // Do not run update checks when rendering the controls. 373 remove_action( 'admin_init', '_maybe_update_core' ); 374 remove_action( 'admin_init', '_maybe_update_plugins' ); 375 remove_action( 'admin_init', '_maybe_update_themes' ); 376 377 add_action( 'wp_ajax_customize_save', array( $this, 'save' ) ); 378 add_action( 'wp_ajax_customize_trash', array( $this, 'handle_changeset_trash_request' ) ); 379 add_action( 'wp_ajax_customize_refresh_nonces', array( $this, 'refresh_nonces' ) ); 380 add_action( 'wp_ajax_customize_load_themes', array( $this, 'handle_load_themes_request' ) ); 381 add_filter( 'heartbeat_settings', array( $this, 'add_customize_screen_to_heartbeat_settings' ) ); 382 add_filter( 'heartbeat_received', array( $this, 'check_changeset_lock_with_heartbeat' ), 10, 3 ); 383 add_action( 'wp_ajax_customize_override_changeset_lock', array( $this, 'handle_override_changeset_lock_request' ) ); 384 add_action( 'wp_ajax_customize_dismiss_autosave_or_lock', array( $this, 'handle_dismiss_autosave_or_lock_request' ) ); 385 386 add_action( 'customize_register', array( $this, 'register_controls' ) ); 387 add_action( 'customize_register', array( $this, 'register_dynamic_settings' ), 11 ); // Allow code to create settings first. 388 add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) ); 389 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) ); 390 391 // Render Common, Panel, Section, and Control templates. 392 add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_panel_templates' ), 1 ); 393 add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_section_templates' ), 1 ); 394 add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_control_templates' ), 1 ); 395 396 // Export header video settings with the partial response. 397 add_filter( 'customize_render_partials_response', array( $this, 'export_header_video_settings' ), 10, 3 ); 398 399 // Export the settings to JS via the _wpCustomizeSettings variable. 400 add_action( 'customize_controls_print_footer_scripts', array( $this, 'customize_pane_settings' ), 1000 ); 401 402 // Add theme update notices. 403 if ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) ) { 404 require_once ABSPATH . 'wp-admin/includes/update.php'; 405 add_action( 'customize_controls_print_footer_scripts', 'wp_print_admin_notice_templates' ); 406 } 407 } 408 409 /** 410 * Return true if it's an Ajax request. 411 * 412 * @since 3.4.0 413 * @since 4.2.0 Added `$action` param. 414 * 415 * @param string|null $action Whether the supplied Ajax action is being run. 416 * @return bool True if it's an Ajax request, false otherwise. 417 */ 418 public function doing_ajax( $action = null ) { 419 if ( ! wp_doing_ajax() ) { 420 return false; 421 } 422 423 if ( ! $action ) { 424 return true; 425 } else { 426 /* 427 * Note: we can't just use doing_action( "wp_ajax_{$action}" ) because we need 428 * to check before admin-ajax.php gets to that point. 429 */ 430 return isset( $_REQUEST['action'] ) && wp_unslash( $_REQUEST['action'] ) === $action; 431 } 432 } 433 434 /** 435 * Custom wp_die wrapper. Returns either the standard message for UI 436 * or the Ajax message. 437 * 438 * @since 3.4.0 439 * 440 * @param string|WP_Error $ajax_message Ajax return. 441 * @param string $message Optional. UI message. 442 */ 443 protected function wp_die( $ajax_message, $message = null ) { 444 if ( $this->doing_ajax() ) { 445 wp_die( $ajax_message ); 446 } 447 448 if ( ! $message ) { 449 $message = __( 'Something went wrong.' ); 450 } 451 452 if ( $this->messenger_channel ) { 453 ob_start(); 454 wp_enqueue_scripts(); 455 wp_print_scripts( array( 'customize-base' ) ); 456 457 $settings = array( 458 'messengerArgs' => array( 459 'channel' => $this->messenger_channel, 460 'url' => wp_customize_url(), 461 ), 462 'error' => $ajax_message, 463 ); 464 ?> 465 <script> 466 ( function( api, settings ) { 467 var preview = new api.Messenger( settings.messengerArgs ); 468 preview.send( 'iframe-loading-error', settings.error ); 469 } )( wp.customize, <?php echo wp_json_encode( $settings ); ?> ); 470 </script> 471 <?php 472 $message .= ob_get_clean(); 473 } 474 475 wp_die( $message ); 476 } 477 478 /** 479 * Return the Ajax wp_die() handler if it's a customized request. 480 * 481 * @since 3.4.0 482 * @deprecated 4.7.0 483 * 484 * @return callable Die handler. 485 */ 486 public function wp_die_handler() { 487 _deprecated_function( __METHOD__, '4.7.0' ); 488 489 if ( $this->doing_ajax() || isset( $_POST['customized'] ) ) { 490 return '_ajax_wp_die_handler'; 491 } 492 493 return '_default_wp_die_handler'; 494 } 495 496 /** 497 * Start preview and customize theme. 498 * 499 * Check if customize query variable exist. Init filters to filter the current theme. 500 * 501 * @since 3.4.0 502 * 503 * @global string $pagenow 504 */ 505 public function setup_theme() { 506 global $pagenow; 507 508 // Check permissions for customize.php access since this method is called before customize.php can run any code. 509 if ( 'customize.php' === $pagenow && ! current_user_can( 'customize' ) ) { 510 if ( ! is_user_logged_in() ) { 511 auth_redirect(); 512 } else { 513 wp_die( 514 '<h1>' . __( 'You need a higher level of permission.' ) . '</h1>' . 515 '<p>' . __( 'Sorry, you are not allowed to customize this site.' ) . '</p>', 516 403 517 ); 518 } 519 return; 520 } 521 522 // If a changeset was provided is invalid. 523 if ( isset( $this->_changeset_uuid ) && false !== $this->_changeset_uuid && ! wp_is_uuid( $this->_changeset_uuid ) ) { 524 $this->wp_die( -1, __( 'Invalid changeset UUID' ) ); 525 } 526 527 /* 528 * Clear incoming post data if the user lacks a CSRF token (nonce). Note that the customizer 529 * application will inject the customize_preview_nonce query parameter into all Ajax requests. 530 * For similar behavior elsewhere in WordPress, see rest_cookie_check_errors() which logs out 531 * a user when a valid nonce isn't present. 532 */ 533 $has_post_data_nonce = ( 534 check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce', false ) 535 || 536 check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce', false ) 537 || 538 check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'customize_preview_nonce', false ) 539 ); 540 if ( ! current_user_can( 'customize' ) || ! $has_post_data_nonce ) { 541 unset( $_POST['customized'] ); 542 unset( $_REQUEST['customized'] ); 543 } 544 545 /* 546 * If unauthenticated then require a valid changeset UUID to load the preview. 547 * In this way, the UUID serves as a secret key. If the messenger channel is present, 548 * then send unauthenticated code to prompt re-auth. 549 */ 550 if ( ! current_user_can( 'customize' ) && ! $this->changeset_post_id() ) { 551 $this->wp_die( $this->messenger_channel ? 0 : -1, __( 'Non-existent changeset UUID.' ) ); 552 } 553 554 if ( ! headers_sent() ) { 555 send_origin_headers(); 556 } 557 558 // Hide the admin bar if we're embedded in the customizer iframe. 559 if ( $this->messenger_channel ) { 560 show_admin_bar( false ); 561 } 562 563 if ( $this->is_theme_active() ) { 564 // Once the theme is loaded, we'll validate it. 565 add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) ); 566 } else { 567 // If the requested theme is not the active theme and the user doesn't have 568 // the switch_themes cap, bail. 569 if ( ! current_user_can( 'switch_themes' ) ) { 570 $this->wp_die( -1, __( 'Sorry, you are not allowed to edit theme options on this site.' ) ); 571 } 572 573 // If the theme has errors while loading, bail. 574 if ( $this->theme()->errors() ) { 575 $this->wp_die( -1, $this->theme()->errors()->get_error_message() ); 576 } 577 578 // If the theme isn't allowed per multisite settings, bail. 579 if ( ! $this->theme()->is_allowed() ) { 580 $this->wp_die( -1, __( 'The requested theme does not exist.' ) ); 581 } 582 } 583 584 // Make sure changeset UUID is established immediately after the theme is loaded. 585 add_action( 'after_setup_theme', array( $this, 'establish_loaded_changeset' ), 5 ); 586 587 /* 588 * Import theme starter content for fresh installations when landing in the customizer. 589 * Import starter content at after_setup_theme:100 so that any 590 * add_theme_support( 'starter-content' ) calls will have been made. 591 */ 592 if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) { 593 add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 ); 594 } 595 596 $this->start_previewing_theme(); 597 } 598 599 /** 600 * Establish the loaded changeset. 601 * 602 * This method runs right at after_setup_theme and applies the 'customize_changeset_branching' filter to determine 603 * whether concurrent changesets are allowed. Then if the Customizer is not initialized with a `changeset_uuid` param, 604 * this method will determine which UUID should be used. If changeset branching is disabled, then the most saved 605 * changeset will be loaded by default. Otherwise, if there are no existing saved changesets or if changeset branching is 606 * enabled, then a new UUID will be generated. 607 * 608 * @since 4.9.0 609 * @global string $pagenow 610 */ 611 public function establish_loaded_changeset() { 612 global $pagenow; 613 614 if ( empty( $this->_changeset_uuid ) ) { 615 $changeset_uuid = null; 616 617 if ( ! $this->branching() && $this->is_theme_active() ) { 618 $unpublished_changeset_posts = $this->get_changeset_posts( 619 array( 620 'post_status' => array_diff( get_post_stati(), array( 'auto-draft', 'publish', 'trash', 'inherit', 'private' ) ), 621 'exclude_restore_dismissed' => false, 622 'author' => 'any', 623 'posts_per_page' => 1, 624 'order' => 'DESC', 625 'orderby' => 'date', 626 ) 627 ); 628 $unpublished_changeset_post = array_shift( $unpublished_changeset_posts ); 629 if ( ! empty( $unpublished_changeset_post ) && wp_is_uuid( $unpublished_changeset_post->post_name ) ) { 630 $changeset_uuid = $unpublished_changeset_post->post_name; 631 } 632 } 633 634 // If no changeset UUID has been set yet, then generate a new one. 635 if ( empty( $changeset_uuid ) ) { 636 $changeset_uuid = wp_generate_uuid4(); 637 } 638 639 $this->_changeset_uuid = $changeset_uuid; 640 } 641 642 if ( is_admin() && 'customize.php' === $pagenow ) { 643 $this->set_changeset_lock( $this->changeset_post_id() ); 644 } 645 } 646 647 /** 648 * Callback to validate a theme once it is loaded 649 * 650 * @since 3.4.0 651 */ 652 public function after_setup_theme() { 653 $doing_ajax_or_is_customized = ( $this->doing_ajax() || isset( $_POST['customized'] ) ); 654 if ( ! $doing_ajax_or_is_customized && ! validate_current_theme() ) { 655 wp_redirect( 'themes.php?broken=true' ); 656 exit; 657 } 658 } 659 660 /** 661 * If the theme to be previewed isn't the active theme, add filter callbacks 662 * to swap it out at runtime. 663 * 664 * @since 3.4.0 665 */ 666 public function start_previewing_theme() { 667 // Bail if we're already previewing. 668 if ( $this->is_preview() ) { 669 return; 670 } 671 672 $this->previewing = true; 673 674 if ( ! $this->is_theme_active() ) { 675 add_filter( 'template', array( $this, 'get_template' ) ); 676 add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); 677 add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); 678 679 // @link: https://core.trac.wordpress.org/ticket/20027 680 add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); 681 add_filter( 'pre_option_template', array( $this, 'get_template' ) ); 682 683 // Handle custom theme roots. 684 add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); 685 add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); 686 } 687 688 /** 689 * Fires once the Customizer theme preview has started. 690 * 691 * @since 3.4.0 692 * 693 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 694 */ 695 do_action( 'start_previewing_theme', $this ); 696 } 697 698 /** 699 * Stop previewing the selected theme. 700 * 701 * Removes filters to change the current theme. 702 * 703 * @since 3.4.0 704 */ 705 public function stop_previewing_theme() { 706 if ( ! $this->is_preview() ) { 707 return; 708 } 709 710 $this->previewing = false; 711 712 if ( ! $this->is_theme_active() ) { 713 remove_filter( 'template', array( $this, 'get_template' ) ); 714 remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); 715 remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); 716 717 // @link: https://core.trac.wordpress.org/ticket/20027 718 remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); 719 remove_filter( 'pre_option_template', array( $this, 'get_template' ) ); 720 721 // Handle custom theme roots. 722 remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); 723 remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); 724 } 725 726 /** 727 * Fires once the Customizer theme preview has stopped. 728 * 729 * @since 3.4.0 730 * 731 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 732 */ 733 do_action( 'stop_previewing_theme', $this ); 734 } 735 736 /** 737 * Gets whether settings are or will be previewed. 738 * 739 * @since 4.9.0 740 * @see WP_Customize_Setting::preview() 741 * 742 * @return bool 743 */ 744 public function settings_previewed() { 745 return $this->settings_previewed; 746 } 747 748 /** 749 * Gets whether data from a changeset's autosaved revision should be loaded if it exists. 750 * 751 * @since 4.9.0 752 * @see WP_Customize_Manager::changeset_data() 753 * 754 * @return bool Is using autosaved changeset revision. 755 */ 756 public function autosaved() { 757 return $this->autosaved; 758 } 759 760 /** 761 * Whether the changeset branching is allowed. 762 * 763 * @since 4.9.0 764 * @see WP_Customize_Manager::establish_loaded_changeset() 765 * 766 * @return bool Is changeset branching. 767 */ 768 public function branching() { 769 770 /** 771 * Filters whether or not changeset branching is allowed. 772 * 773 * By default in core, when changeset branching is not allowed, changesets will operate 774 * linearly in that only one saved changeset will exist at a time (with a 'draft' or 775 * 'future' status). This makes the Customizer operate in a way that is similar to going to 776 * "edit" to one existing post: all users will be making changes to the same post, and autosave 777 * revisions will be made for that post. 778 * 779 * By contrast, when changeset branching is allowed, then the model is like users going 780 * to "add new" for a page and each user makes changes independently of each other since 781 * they are all operating on their own separate pages, each getting their own separate 782 * initial auto-drafts and then once initially saved, autosave revisions on top of that 783 * user's specific post. 784 * 785 * Since linear changesets are deemed to be more suitable for the majority of WordPress users, 786 * they are the default. For WordPress sites that have heavy site management in the Customizer 787 * by multiple users then branching changesets should be enabled by means of this filter. 788 * 789 * @since 4.9.0 790 * 791 * @param bool $allow_branching Whether branching is allowed. If `false`, the default, 792 * then only one saved changeset exists at a time. 793 * @param WP_Customize_Manager $wp_customize Manager instance. 794 */ 795 $this->branching = apply_filters( 'customize_changeset_branching', $this->branching, $this ); 796 797 return $this->branching; 798 } 799 800 /** 801 * Get the changeset UUID. 802 * 803 * @since 4.7.0 804 * @see WP_Customize_Manager::establish_loaded_changeset() 805 * 806 * @return string UUID. 807 */ 808 public function changeset_uuid() { 809 if ( empty( $this->_changeset_uuid ) ) { 810 $this->establish_loaded_changeset(); 811 } 812 return $this->_changeset_uuid; 813 } 814 815 /** 816 * Get the theme being customized. 817 * 818 * @since 3.4.0 819 * 820 * @return WP_Theme 821 */ 822 public function theme() { 823 if ( ! $this->theme ) { 824 $this->theme = wp_get_theme(); 825 } 826 return $this->theme; 827 } 828 829 /** 830 * Get the registered settings. 831 * 832 * @since 3.4.0 833 * 834 * @return array 835 */ 836 public function settings() { 837 return $this->settings; 838 } 839 840 /** 841 * Get the registered controls. 842 * 843 * @since 3.4.0 844 * 845 * @return array 846 */ 847 public function controls() { 848 return $this->controls; 849 } 850 851 /** 852 * Get the registered containers. 853 * 854 * @since 4.0.0 855 * 856 * @return array 857 */ 858 public function containers() { 859 return $this->containers; 860 } 861 862 /** 863 * Get the registered sections. 864 * 865 * @since 3.4.0 866 * 867 * @return array 868 */ 869 public function sections() { 870 return $this->sections; 871 } 872 873 /** 874 * Get the registered panels. 875 * 876 * @since 4.0.0 877 * 878 * @return array Panels. 879 */ 880 public function panels() { 881 return $this->panels; 882 } 883 884 /** 885 * Checks if the current theme is active. 886 * 887 * @since 3.4.0 888 * 889 * @return bool 890 */ 891 public function is_theme_active() { 892 return $this->get_stylesheet() == $this->original_stylesheet; 893 } 894 895 /** 896 * Register styles/scripts and initialize the preview of each setting 897 * 898 * @since 3.4.0 899 */ 900 public function wp_loaded() { 901 902 // Unconditionally register core types for panels, sections, and controls 903 // in case plugin unhooks all customize_register actions. 904 $this->register_panel_type( 'WP_Customize_Panel' ); 905 $this->register_panel_type( 'WP_Customize_Themes_Panel' ); 906 $this->register_section_type( 'WP_Customize_Section' ); 907 $this->register_section_type( 'WP_Customize_Sidebar_Section' ); 908 $this->register_section_type( 'WP_Customize_Themes_Section' ); 909 $this->register_control_type( 'WP_Customize_Color_Control' ); 910 $this->register_control_type( 'WP_Customize_Media_Control' ); 911 $this->register_control_type( 'WP_Customize_Upload_Control' ); 912 $this->register_control_type( 'WP_Customize_Image_Control' ); 913 $this->register_control_type( 'WP_Customize_Background_Image_Control' ); 914 $this->register_control_type( 'WP_Customize_Background_Position_Control' ); 915 $this->register_control_type( 'WP_Customize_Cropped_Image_Control' ); 916 $this->register_control_type( 'WP_Customize_Site_Icon_Control' ); 917 $this->register_control_type( 'WP_Customize_Theme_Control' ); 918 $this->register_control_type( 'WP_Customize_Code_Editor_Control' ); 919 $this->register_control_type( 'WP_Customize_Date_Time_Control' ); 920 921 /** 922 * Fires once WordPress has loaded, allowing scripts and styles to be initialized. 923 * 924 * @since 3.4.0 925 * 926 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 927 */ 928 do_action( 'customize_register', $this ); 929 930 if ( $this->settings_previewed() ) { 931 foreach ( $this->settings as $setting ) { 932 $setting->preview(); 933 } 934 } 935 936 if ( $this->is_preview() && ! is_admin() ) { 937 $this->customize_preview_init(); 938 } 939 } 940 941 /** 942 * Prevents Ajax requests from following redirects when previewing a theme 943 * by issuing a 200 response instead of a 30x. 944 * 945 * Instead, the JS will sniff out the location header. 946 * 947 * @since 3.4.0 948 * @deprecated 4.7.0 949 * 950 * @param int $status Status. 951 * @return int 952 */ 953 public function wp_redirect_status( $status ) { 954 _deprecated_function( __FUNCTION__, '4.7.0' ); 955 956 if ( $this->is_preview() && ! is_admin() ) { 957 return 200; 958 } 959 960 return $status; 961 } 962 963 /** 964 * Find the changeset post ID for a given changeset UUID. 965 * 966 * @since 4.7.0 967 * 968 * @param string $uuid Changeset UUID. 969 * @return int|null Returns post ID on success and null on failure. 970 */ 971 public function find_changeset_post_id( $uuid ) { 972 $cache_group = 'customize_changeset_post'; 973 $changeset_post_id = wp_cache_get( $uuid, $cache_group ); 974 if ( $changeset_post_id && 'customize_changeset' === get_post_type( $changeset_post_id ) ) { 975 return $changeset_post_id; 976 } 977 978 $changeset_post_query = new WP_Query( 979 array( 980 'post_type' => 'customize_changeset', 981 'post_status' => get_post_stati(), 982 'name' => $uuid, 983 'posts_per_page' => 1, 984 'no_found_rows' => true, 985 'cache_results' => true, 986 'update_post_meta_cache' => false, 987 'update_post_term_cache' => false, 988 'lazy_load_term_meta' => false, 989 ) 990 ); 991 if ( ! empty( $changeset_post_query->posts ) ) { 992 // Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed. 993 $changeset_post_id = $changeset_post_query->posts[0]->ID; 994 wp_cache_set( $uuid, $changeset_post_id, $cache_group ); 995 return $changeset_post_id; 996 } 997 998 return null; 999 } 1000 1001 /** 1002 * Get changeset posts. 1003 * 1004 * @since 4.9.0 1005 * 1006 * @param array $args { 1007 * Args to pass into `get_posts()` to query changesets. 1008 * 1009 * @type int $posts_per_page Number of posts to return. Defaults to -1 (all posts). 1010 * @type int $author Post author. Defaults to current user. 1011 * @type string $post_status Status of changeset. Defaults to 'auto-draft'. 1012 * @type bool $exclude_restore_dismissed Whether to exclude changeset auto-drafts that have been dismissed. Defaults to true. 1013 * } 1014 * @return WP_Post[] Auto-draft changesets. 1015 */ 1016 protected function get_changeset_posts( $args = array() ) { 1017 $default_args = array( 1018 'exclude_restore_dismissed' => true, 1019 'posts_per_page' => -1, 1020 'post_type' => 'customize_changeset', 1021 'post_status' => 'auto-draft', 1022 'order' => 'DESC', 1023 'orderby' => 'date', 1024 'no_found_rows' => true, 1025 'cache_results' => true, 1026 'update_post_meta_cache' => false, 1027 'update_post_term_cache' => false, 1028 'lazy_load_term_meta' => false, 1029 ); 1030 if ( get_current_user_id() ) { 1031 $default_args['author'] = get_current_user_id(); 1032 } 1033 $args = array_merge( $default_args, $args ); 1034 1035 if ( ! empty( $args['exclude_restore_dismissed'] ) ) { 1036 unset( $args['exclude_restore_dismissed'] ); 1037 $args['meta_query'] = array( 1038 array( 1039 'key' => '_customize_restore_dismissed', 1040 'compare' => 'NOT EXISTS', 1041 ), 1042 ); 1043 } 1044 1045 return get_posts( $args ); 1046 } 1047 1048 /** 1049 * Dismiss all of the current user's auto-drafts (other than the present one). 1050 * 1051 * @since 4.9.0 1052 * @return int The number of auto-drafts that were dismissed. 1053 */ 1054 protected function dismiss_user_auto_draft_changesets() { 1055 $changeset_autodraft_posts = $this->get_changeset_posts( 1056 array( 1057 'post_status' => 'auto-draft', 1058 'exclude_restore_dismissed' => true, 1059 'posts_per_page' => -1, 1060 ) 1061 ); 1062 $dismissed = 0; 1063 foreach ( $changeset_autodraft_posts as $autosave_autodraft_post ) { 1064 if ( $autosave_autodraft_post->ID === $this->changeset_post_id() ) { 1065 continue; 1066 } 1067 if ( update_post_meta( $autosave_autodraft_post->ID, '_customize_restore_dismissed', true ) ) { 1068 $dismissed++; 1069 } 1070 } 1071 return $dismissed; 1072 } 1073 1074 /** 1075 * Get the changeset post id for the loaded changeset. 1076 * 1077 * @since 4.7.0 1078 * 1079 * @return int|null Post ID on success or null if there is no post yet saved. 1080 */ 1081 public function changeset_post_id() { 1082 if ( ! isset( $this->_changeset_post_id ) ) { 1083 $post_id = $this->find_changeset_post_id( $this->changeset_uuid() ); 1084 if ( ! $post_id ) { 1085 $post_id = false; 1086 } 1087 $this->_changeset_post_id = $post_id; 1088 } 1089 if ( false === $this->_changeset_post_id ) { 1090 return null; 1091 } 1092 return $this->_changeset_post_id; 1093 } 1094 1095 /** 1096 * Get the data stored in a changeset post. 1097 * 1098 * @since 4.7.0 1099 * 1100 * @param int $post_id Changeset post ID. 1101 * @return array|WP_Error Changeset data or WP_Error on error. 1102 */ 1103 protected function get_changeset_post_data( $post_id ) { 1104 if ( ! $post_id ) { 1105 return new WP_Error( 'empty_post_id' ); 1106 } 1107 $changeset_post = get_post( $post_id ); 1108 if ( ! $changeset_post ) { 1109 return new WP_Error( 'missing_post' ); 1110 } 1111 if ( 'revision' === $changeset_post->post_type ) { 1112 if ( 'customize_changeset' !== get_post_type( $changeset_post->post_parent ) ) { 1113 return new WP_Error( 'wrong_post_type' ); 1114 } 1115 } elseif ( 'customize_changeset' !== $changeset_post->post_type ) { 1116 return new WP_Error( 'wrong_post_type' ); 1117 } 1118 $changeset_data = json_decode( $changeset_post->post_content, true ); 1119 $last_error = json_last_error(); 1120 if ( $last_error ) { 1121 return new WP_Error( 'json_parse_error', '', $last_error ); 1122 } 1123 if ( ! is_array( $changeset_data ) ) { 1124 return new WP_Error( 'expected_array' ); 1125 } 1126 return $changeset_data; 1127 } 1128 1129 /** 1130 * Get changeset data. 1131 * 1132 * @since 4.7.0 1133 * @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. 1134 * 1135 * @return array Changeset data. 1136 */ 1137 public function changeset_data() { 1138 if ( isset( $this->_changeset_data ) ) { 1139 return $this->_changeset_data; 1140 } 1141 $changeset_post_id = $this->changeset_post_id(); 1142 if ( ! $changeset_post_id ) { 1143 $this->_changeset_data = array(); 1144 } else { 1145 if ( $this->autosaved() && is_user_logged_in() ) { 1146 $autosave_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); 1147 if ( $autosave_post ) { 1148 $data = $this->get_changeset_post_data( $autosave_post->ID ); 1149 if ( ! is_wp_error( $data ) ) { 1150 $this->_changeset_data = $data; 1151 } 1152 } 1153 } 1154 1155 // Load data from the changeset if it was not loaded from an autosave. 1156 if ( ! isset( $this->_changeset_data ) ) { 1157 $data = $this->get_changeset_post_data( $changeset_post_id ); 1158 if ( ! is_wp_error( $data ) ) { 1159 $this->_changeset_data = $data; 1160 } else { 1161 $this->_changeset_data = array(); 1162 } 1163 } 1164 } 1165 return $this->_changeset_data; 1166 } 1167 1168 /** 1169 * Starter content setting IDs. 1170 * 1171 * @since 4.7.0 1172 * @var array 1173 */ 1174 protected $pending_starter_content_settings_ids = array(); 1175 1176 /** 1177 * Import theme starter content into the customized state. 1178 * 1179 * @since 4.7.0 1180 * 1181 * @param array $starter_content Starter content. Defaults to `get_theme_starter_content()`. 1182 */ 1183 function import_theme_starter_content( $starter_content = array() ) { 1184 if ( empty( $starter_content ) ) { 1185 $starter_content = get_theme_starter_content(); 1186 } 1187 1188 $changeset_data = array(); 1189 if ( $this->changeset_post_id() ) { 1190 /* 1191 * Don't re-import starter content into a changeset saved persistently. 1192 * This will need to be revisited in the future once theme switching 1193 * is allowed with drafted/scheduled changesets, since switching to 1194 * another theme could result in more starter content being applied. 1195 * However, when doing an explicit save it is currently possible for 1196 * nav menus and nav menu items specifically to lose their starter_content 1197 * flags, thus resulting in duplicates being created since they fail 1198 * to get re-used. See #40146. 1199 */ 1200 if ( 'auto-draft' !== get_post_status( $this->changeset_post_id() ) ) { 1201 return; 1202 } 1203 1204 $changeset_data = $this->get_changeset_post_data( $this->changeset_post_id() ); 1205 } 1206 1207 $sidebars_widgets = isset( $starter_content['widgets'] ) && ! empty( $this->widgets ) ? $starter_content['widgets'] : array(); 1208 $attachments = isset( $starter_content['attachments'] ) && ! empty( $this->nav_menus ) ? $starter_content['attachments'] : array(); 1209 $posts = isset( $starter_content['posts'] ) && ! empty( $this->nav_menus ) ? $starter_content['posts'] : array(); 1210 $options = isset( $starter_content['options'] ) ? $starter_content['options'] : array(); 1211 $nav_menus = isset( $starter_content['nav_menus'] ) && ! empty( $this->nav_menus ) ? $starter_content['nav_menus'] : array(); 1212 $theme_mods = isset( $starter_content['theme_mods'] ) ? $starter_content['theme_mods'] : array(); 1213 1214 // Widgets. 1215 $max_widget_numbers = array(); 1216 foreach ( $sidebars_widgets as $sidebar_id => $widgets ) { 1217 $sidebar_widget_ids = array(); 1218 foreach ( $widgets as $widget ) { 1219 list( $id_base, $instance ) = $widget; 1220 1221 if ( ! isset( $max_widget_numbers[ $id_base ] ) ) { 1222 1223 // When $settings is an array-like object, get an intrinsic array for use with array_keys(). 1224 $settings = get_option( "widget_{$id_base}", array() ); 1225 if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) { 1226 $settings = $settings->getArrayCopy(); 1227 } 1228 1229 // Find the max widget number for this type. 1230 $widget_numbers = array_keys( $settings ); 1231 if ( count( $widget_numbers ) > 0 ) { 1232 $widget_numbers[] = 1; 1233 $max_widget_numbers[ $id_base ] = max( ...$widget_numbers ); 1234 } else { 1235 $max_widget_numbers[ $id_base ] = 1; 1236 } 1237 } 1238 $max_widget_numbers[ $id_base ] += 1; 1239 1240 $widget_id = sprintf( '%s-%d', $id_base, $max_widget_numbers[ $id_base ] ); 1241 $setting_id = sprintf( 'widget_%s[%d]', $id_base, $max_widget_numbers[ $id_base ] ); 1242 1243 $setting_value = $this->widgets->sanitize_widget_js_instance( $instance ); 1244 if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { 1245 $this->set_post_value( $setting_id, $setting_value ); 1246 $this->pending_starter_content_settings_ids[] = $setting_id; 1247 } 1248 $sidebar_widget_ids[] = $widget_id; 1249 } 1250 1251 $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id ); 1252 if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { 1253 $this->set_post_value( $setting_id, $sidebar_widget_ids ); 1254 $this->pending_starter_content_settings_ids[] = $setting_id; 1255 } 1256 } 1257 1258 $starter_content_auto_draft_post_ids = array(); 1259 if ( ! empty( $changeset_data['nav_menus_created_posts']['value'] ) ) { 1260 $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, $changeset_data['nav_menus_created_posts']['value'] ); 1261 } 1262 1263 // Make an index of all the posts needed and what their slugs are. 1264 $needed_posts = array(); 1265 $attachments = $this->prepare_starter_content_attachments( $attachments ); 1266 foreach ( $attachments as $attachment ) { 1267 $key = 'attachment:' . $attachment['post_name']; 1268 $needed_posts[ $key ] = true; 1269 } 1270 foreach ( array_keys( $posts ) as $post_symbol ) { 1271 if ( empty( $posts[ $post_symbol ]['post_name'] ) && empty( $posts[ $post_symbol ]['post_title'] ) ) { 1272 unset( $posts[ $post_symbol ] ); 1273 continue; 1274 } 1275 if ( empty( $posts[ $post_symbol ]['post_name'] ) ) { 1276 $posts[ $post_symbol ]['post_name'] = sanitize_title( $posts[ $post_symbol ]['post_title'] ); 1277 } 1278 if ( empty( $posts[ $post_symbol ]['post_type'] ) ) { 1279 $posts[ $post_symbol ]['post_type'] = 'post'; 1280 } 1281 $needed_posts[ $posts[ $post_symbol ]['post_type'] . ':' . $posts[ $post_symbol ]['post_name'] ] = true; 1282 } 1283 $all_post_slugs = array_merge( 1284 wp_list_pluck( $attachments, 'post_name' ), 1285 wp_list_pluck( $posts, 'post_name' ) 1286 ); 1287 1288 /* 1289 * Obtain all post types referenced in starter content to use in query. 1290 * This is needed because 'any' will not account for post types not yet registered. 1291 */ 1292 $post_types = array_filter( array_merge( array( 'attachment' ), wp_list_pluck( $posts, 'post_type' ) ) ); 1293 1294 // Re-use auto-draft starter content posts referenced in the current customized state. 1295 $existing_starter_content_posts = array(); 1296 if ( ! empty( $starter_content_auto_draft_post_ids ) ) { 1297 $existing_posts_query = new WP_Query( 1298 array( 1299 'post__in' => $starter_content_auto_draft_post_ids, 1300 'post_status' => 'auto-draft', 1301 'post_type' => $post_types, 1302 'posts_per_page' => -1, 1303 ) 1304 ); 1305 foreach ( $existing_posts_query->posts as $existing_post ) { 1306 $post_name = $existing_post->post_name; 1307 if ( empty( $post_name ) ) { 1308 $post_name = get_post_meta( $existing_post->ID, '_customize_draft_post_name', true ); 1309 } 1310 $existing_starter_content_posts[ $existing_post->post_type . ':' . $post_name ] = $existing_post; 1311 } 1312 } 1313 1314 // Re-use non-auto-draft posts. 1315 if ( ! empty( $all_post_slugs ) ) { 1316 $existing_posts_query = new WP_Query( 1317 array( 1318 'post_name__in' => $all_post_slugs, 1319 'post_status' => array_diff( get_post_stati(), array( 'auto-draft' ) ), 1320 'post_type' => 'any', 1321 'posts_per_page' => -1, 1322 ) 1323 ); 1324 foreach ( $existing_posts_query->posts as $existing_post ) { 1325 $key = $existing_post->post_type . ':' . $existing_post->post_name; 1326 if ( isset( $needed_posts[ $key ] ) && ! isset( $existing_starter_content_posts[ $key ] ) ) { 1327 $existing_starter_content_posts[ $key ] = $existing_post; 1328 } 1329 } 1330 } 1331 1332 // Attachments are technically posts but handled differently. 1333 if ( ! empty( $attachments ) ) { 1334 1335 $attachment_ids = array(); 1336 1337 foreach ( $attachments as $symbol => $attachment ) { 1338 $file_array = array( 1339 'name' => $attachment['file_name'], 1340 ); 1341 $file_path = $attachment['file_path']; 1342 $attachment_id = null; 1343 $attached_file = null; 1344 if ( isset( $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ] ) ) { 1345 $attachment_post = $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ]; 1346 $attachment_id = $attachment_post->ID; 1347 $attached_file = get_attached_file( $attachment_id ); 1348 if ( empty( $attached_file ) || ! file_exists( $attached_file ) ) { 1349 $attachment_id = null; 1350 $attached_file = null; 1351 } elseif ( $this->get_stylesheet() !== get_post_meta( $attachment_post->ID, '_starter_content_theme', true ) ) { 1352 1353 // Re-generate attachment metadata since it was previously generated for a different theme. 1354 $metadata = wp_generate_attachment_metadata( $attachment_post->ID, $attached_file ); 1355 wp_update_attachment_metadata( $attachment_id, $metadata ); 1356 update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() ); 1357 } 1358 } 1359 1360 // Insert the attachment auto-draft because it doesn't yet exist or the attached file is gone. 1361 if ( ! $attachment_id ) { 1362 1363 // Copy file to temp location so that original file won't get deleted from theme after sideloading. 1364 $temp_file_name = wp_tempnam( wp_basename( $file_path ) ); 1365 if ( $temp_file_name && copy( $file_path, $temp_file_name ) ) { 1366 $file_array['tmp_name'] = $temp_file_name; 1367 } 1368 if ( empty( $file_array['tmp_name'] ) ) { 1369 continue; 1370 } 1371 1372 $attachment_post_data = array_merge( 1373 wp_array_slice_assoc( $attachment, array( 'post_title', 'post_content', 'post_excerpt' ) ), 1374 array( 1375 'post_status' => 'auto-draft', // So attachment will be garbage collected in a week if changeset is never published. 1376 ) 1377 ); 1378 1379 $attachment_id = media_handle_sideload( $file_array, 0, null, $attachment_post_data ); 1380 if ( is_wp_error( $attachment_id ) ) { 1381 continue; 1382 } 1383 update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() ); 1384 update_post_meta( $attachment_id, '_customize_draft_post_name', $attachment['post_name'] ); 1385 } 1386 1387 $attachment_ids[ $symbol ] = $attachment_id; 1388 } 1389 $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, array_values( $attachment_ids ) ); 1390 } 1391 1392 // Posts & pages. 1393 if ( ! empty( $posts ) ) { 1394 foreach ( array_keys( $posts ) as $post_symbol ) { 1395 if ( empty( $posts[ $post_symbol ]['post_type'] ) || empty( $posts[ $post_symbol ]['post_name'] ) ) { 1396 continue; 1397 } 1398 $post_type = $posts[ $post_symbol ]['post_type']; 1399 if ( ! empty( $posts[ $post_symbol ]['post_name'] ) ) { 1400 $post_name = $posts[ $post_symbol ]['post_name']; 1401 } elseif ( ! empty( $posts[ $post_symbol ]['post_title'] ) ) { 1402 $post_name = sanitize_title( $posts[ $post_symbol ]['post_title'] ); 1403 } else { 1404 continue; 1405 } 1406 1407 // Use existing auto-draft post if one already exists with the same type and name. 1408 if ( isset( $existing_starter_content_posts[ $post_type . ':' . $post_name ] ) ) { 1409 $posts[ $post_symbol ]['ID'] = $existing_starter_content_posts[ $post_type . ':' . $post_name ]->ID; 1410 continue; 1411 } 1412 1413 // Translate the featured image symbol. 1414 if ( ! empty( $posts[ $post_symbol ]['thumbnail'] ) 1415 && preg_match( '/^{{(?P<symbol>.+)}}$/', $posts[ $post_symbol ]['thumbnail'], $matches ) 1416 && isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1417 $posts[ $post_symbol ]['meta_input']['_thumbnail_id'] = $attachment_ids[ $matches['symbol'] ]; 1418 } 1419 1420 if ( ! empty( $posts[ $post_symbol ]['template'] ) ) { 1421 $posts[ $post_symbol ]['meta_input']['_wp_page_template'] = $posts[ $post_symbol ]['template']; 1422 } 1423 1424 $r = $this->nav_menus->insert_auto_draft_post( $posts[ $post_symbol ] ); 1425 if ( $r instanceof WP_Post ) { 1426 $posts[ $post_symbol ]['ID'] = $r->ID; 1427 } 1428 } 1429 1430 $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, wp_list_pluck( $posts, 'ID' ) ); 1431 } 1432 1433 // The nav_menus_created_posts setting is why nav_menus component is dependency for adding posts. 1434 if ( ! empty( $this->nav_menus ) && ! empty( $starter_content_auto_draft_post_ids ) ) { 1435 $setting_id = 'nav_menus_created_posts'; 1436 $this->set_post_value( $setting_id, array_unique( array_values( $starter_content_auto_draft_post_ids ) ) ); 1437 $this->pending_starter_content_settings_ids[] = $setting_id; 1438 } 1439 1440 // Nav menus. 1441 $placeholder_id = -1; 1442 $reused_nav_menu_setting_ids = array(); 1443 foreach ( $nav_menus as $nav_menu_location => $nav_menu ) { 1444 1445 $nav_menu_term_id = null; 1446 $nav_menu_setting_id = null; 1447 $matches = array(); 1448 1449 // Look for an existing placeholder menu with starter content to re-use. 1450 foreach ( $changeset_data as $setting_id => $setting_params ) { 1451 $can_reuse = ( 1452 ! empty( $setting_params['starter_content'] ) 1453 && 1454 ! in_array( $setting_id, $reused_nav_menu_setting_ids, true ) 1455 && 1456 preg_match( '#^nav_menu\[(?P<nav_menu_id>-?\d+)\]$#', $setting_id, $matches ) 1457 ); 1458 if ( $can_reuse ) { 1459 $nav_menu_term_id = intval( $matches['nav_menu_id'] ); 1460 $nav_menu_setting_id = $setting_id; 1461 $reused_nav_menu_setting_ids[] = $setting_id; 1462 break; 1463 } 1464 } 1465 1466 if ( ! $nav_menu_term_id ) { 1467 while ( isset( $changeset_data[ sprintf( 'nav_menu[%d]', $placeholder_id ) ] ) ) { 1468 $placeholder_id--; 1469 } 1470 $nav_menu_term_id = $placeholder_id; 1471 $nav_menu_setting_id = sprintf( 'nav_menu[%d]', $placeholder_id ); 1472 } 1473 1474 $this->set_post_value( 1475 $nav_menu_setting_id, 1476 array( 1477 'name' => isset( $nav_menu['name'] ) ? $nav_menu['name'] : $nav_menu_location, 1478 ) 1479 ); 1480 $this->pending_starter_content_settings_ids[] = $nav_menu_setting_id; 1481 1482 // @todo Add support for menu_item_parent. 1483 $position = 0; 1484 foreach ( $nav_menu['items'] as $nav_menu_item ) { 1485 $nav_menu_item_setting_id = sprintf( 'nav_menu_item[%d]', $placeholder_id-- ); 1486 if ( ! isset( $nav_menu_item['position'] ) ) { 1487 $nav_menu_item['position'] = $position++; 1488 } 1489 $nav_menu_item['nav_menu_term_id'] = $nav_menu_term_id; 1490 1491 if ( isset( $nav_menu_item['object_id'] ) ) { 1492 if ( 'post_type' === $nav_menu_item['type'] && preg_match( '/^{{(?P<symbol>.+)}}$/', $nav_menu_item['object_id'], $matches ) && isset( $posts[ $matches['symbol'] ] ) ) { 1493 $nav_menu_item['object_id'] = $posts[ $matches['symbol'] ]['ID']; 1494 if ( empty( $nav_menu_item['title'] ) ) { 1495 $original_object = get_post( $nav_menu_item['object_id'] ); 1496 $nav_menu_item['title'] = $original_object->post_title; 1497 } 1498 } else { 1499 continue; 1500 } 1501 } else { 1502 $nav_menu_item['object_id'] = 0; 1503 } 1504 1505 if ( empty( $changeset_data[ $nav_menu_item_setting_id ] ) || ! empty( $changeset_data[ $nav_menu_item_setting_id ]['starter_content'] ) ) { 1506 $this->set_post_value( $nav_menu_item_setting_id, $nav_menu_item ); 1507 $this->pending_starter_content_settings_ids[] = $nav_menu_item_setting_id; 1508 } 1509 } 1510 1511 $setting_id = sprintf( 'nav_menu_locations[%s]', $nav_menu_location ); 1512 if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { 1513 $this->set_post_value( $setting_id, $nav_menu_term_id ); 1514 $this->pending_starter_content_settings_ids[] = $setting_id; 1515 } 1516 } 1517 1518 // Options. 1519 foreach ( $options as $name => $value ) { 1520 1521 // Serialize the value to check for post symbols. 1522 $value = maybe_serialize( $value ); 1523 1524 if ( is_serialized( $value ) ) { 1525 if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) { 1526 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1527 $symbol_match = $posts[ $matches['symbol'] ]['ID']; 1528 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1529 $symbol_match = $attachment_ids[ $matches['symbol'] ]; 1530 } 1531 1532 // If we have any symbol matches, update the values. 1533 if ( isset( $symbol_match ) ) { 1534 // Replace found string matches with post IDs. 1535 $value = str_replace( $matches[0], "i:{$symbol_match}", $value ); 1536 } else { 1537 continue; 1538 } 1539 } 1540 } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) { 1541 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1542 $value = $posts[ $matches['symbol'] ]['ID']; 1543 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1544 $value = $attachment_ids[ $matches['symbol'] ]; 1545 } else { 1546 continue; 1547 } 1548 } 1549 1550 // Unserialize values after checking for post symbols, so they can be properly referenced. 1551 $value = maybe_unserialize( $value ); 1552 1553 if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) { 1554 $this->set_post_value( $name, $value ); 1555 $this->pending_starter_content_settings_ids[] = $name; 1556 } 1557 } 1558 1559 // Theme mods. 1560 foreach ( $theme_mods as $name => $value ) { 1561 1562 // Serialize the value to check for post symbols. 1563 $value = maybe_serialize( $value ); 1564 1565 // Check if value was serialized. 1566 if ( is_serialized( $value ) ) { 1567 if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) { 1568 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1569 $symbol_match = $posts[ $matches['symbol'] ]['ID']; 1570 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1571 $symbol_match = $attachment_ids[ $matches['symbol'] ]; 1572 } 1573 1574 // If we have any symbol matches, update the values. 1575 if ( isset( $symbol_match ) ) { 1576 // Replace found string matches with post IDs. 1577 $value = str_replace( $matches[0], "i:{$symbol_match}", $value ); 1578 } else { 1579 continue; 1580 } 1581 } 1582 } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) { 1583 if ( isset( $posts[ $matches['symbol'] ] ) ) { 1584 $value = $posts[ $matches['symbol'] ]['ID']; 1585 } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { 1586 $value = $attachment_ids[ $matches['symbol'] ]; 1587 } else { 1588 continue; 1589 } 1590 } 1591 1592 // Unserialize values after checking for post symbols, so they can be properly referenced. 1593 $value = maybe_unserialize( $value ); 1594 1595 // Handle header image as special case since setting has a legacy format. 1596 if ( 'header_image' === $name ) { 1597 $name = 'header_image_data'; 1598 $metadata = wp_get_attachment_metadata( $value ); 1599 if ( empty( $metadata ) ) { 1600 continue; 1601 } 1602 $value = array( 1603 'attachment_id' => $value, 1604 'url' => wp_get_attachment_url( $value ), 1605 'height' => $metadata['height'], 1606 'width' => $metadata['width'], 1607 ); 1608 } elseif ( 'background_image' === $name ) { 1609 $value = wp_get_attachment_url( $value ); 1610 } 1611 1612 if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) { 1613 $this->set_post_value( $name, $value ); 1614 $this->pending_starter_content_settings_ids[] = $name; 1615 } 1616 } 1617 1618 if ( ! empty( $this->pending_starter_content_settings_ids ) ) { 1619 if ( did_action( 'customize_register' ) ) { 1620 $this->_save_starter_content_changeset(); 1621 } else { 1622 add_action( 'customize_register', array( $this, '_save_starter_content_changeset' ), 1000 ); 1623 } 1624 } 1625 } 1626 1627 /** 1628 * Prepare starter content attachments. 1629 * 1630 * Ensure that the attachments are valid and that they have slugs and file name/path. 1631 * 1632 * @since 4.7.0 1633 * 1634 * @param array $attachments Attachments. 1635 * @return array Prepared attachments. 1636 */ 1637 protected function prepare_starter_content_attachments( $attachments ) { 1638 $prepared_attachments = array(); 1639 if ( empty( $attachments ) ) { 1640 return $prepared_attachments; 1641 } 1642 1643 // Such is The WordPress Way. 1644 require_once ABSPATH . 'wp-admin/includes/file.php'; 1645 require_once ABSPATH . 'wp-admin/includes/media.php'; 1646 require_once ABSPATH . 'wp-admin/includes/image.php'; 1647 1648 foreach ( $attachments as $symbol => $attachment ) { 1649 1650 // A file is required and URLs to files are not currently allowed. 1651 if ( empty( $attachment['file'] ) || preg_match( '#^https?://$#', $attachment['file'] ) ) { 1652 continue; 1653 } 1654 1655 $file_path = null; 1656 if ( file_exists( $attachment['file'] ) ) { 1657 $file_path = $attachment['file']; // Could be absolute path to file in plugin. 1658 } elseif ( is_child_theme() && file_exists( get_stylesheet_directory() . '/' . $attachment['file'] ) ) { 1659 $file_path = get_stylesheet_directory() . '/' . $attachment['file']; 1660 } elseif ( file_exists( get_template_directory() . '/' . $attachment['file'] ) ) { 1661 $file_path = get_template_directory() . '/' . $attachment['file']; 1662 } else { 1663 continue; 1664 } 1665 $file_name = wp_basename( $attachment['file'] ); 1666 1667 // Skip file types that are not recognized. 1668 $checked_filetype = wp_check_filetype( $file_name ); 1669 if ( empty( $checked_filetype['type'] ) ) { 1670 continue; 1671 } 1672 1673 // Ensure post_name is set since not automatically derived from post_title for new auto-draft posts. 1674 if ( empty( $attachment['post_name'] ) ) { 1675 if ( ! empty( $attachment['post_title'] ) ) { 1676 $attachment['post_name'] = sanitize_title( $attachment['post_title'] ); 1677 } else { 1678 $attachment['post_name'] = sanitize_title( preg_replace( '/\.\w+$/', '', $file_name ) ); 1679 } 1680 } 1681 1682 $attachment['file_name'] = $file_name; 1683 $attachment['file_path'] = $file_path; 1684 $prepared_attachments[ $symbol ] = $attachment; 1685 } 1686 return $prepared_attachments; 1687 } 1688 1689 /** 1690 * Save starter content changeset. 1691 * 1692 * @since 4.7.0 1693 */ 1694 public function _save_starter_content_changeset() { 1695 1696 if ( empty( $this->pending_starter_content_settings_ids ) ) { 1697 return; 1698 } 1699 1700 $this->save_changeset_post( 1701 array( 1702 'data' => array_fill_keys( $this->pending_starter_content_settings_ids, array( 'starter_content' => true ) ), 1703 'starter_content' => true, 1704 ) 1705 ); 1706 $this->saved_starter_content_changeset = true; 1707 1708 $this->pending_starter_content_settings_ids = array(); 1709 } 1710 1711 /** 1712 * Get dirty pre-sanitized setting values in the current customized state. 1713 * 1714 * The returned array consists of a merge of three sources: 1715 * 1. If the theme is not currently active, then the base array is any stashed 1716 * theme mods that were modified previously but never published. 1717 * 2. The values from the current changeset, if it exists. 1718 * 3. If the user can customize, the values parsed from the incoming 1719 * `$_POST['customized']` JSON data. 1720 * 4. Any programmatically-set post values via `WP_Customize_Manager::set_post_value()`. 1721 * 1722 * The name "unsanitized_post_values" is a carry-over from when the customized 1723 * state was exclusively sourced from `$_POST['customized']`. Nevertheless, 1724 * the value returned will come from the current changeset post and from the 1725 * incoming post data. 1726 * 1727 * @since 4.1.1 1728 * @since 4.7.0 Added `$args` parameter and merging with changeset values and stashed theme mods. 1729 * 1730 * @param array $args { 1731 * Args. 1732 * 1733 * @type bool $exclude_changeset Whether the changeset values should also be excluded. Defaults to false. 1734 * @type bool $exclude_post_data Whether the post input values should also be excluded. Defaults to false when lacking the customize capability. 1735 * } 1736 * @return array 1737 */ 1738 public function unsanitized_post_values( $args = array() ) { 1739 $args = array_merge( 1740 array( 1741 'exclude_changeset' => false, 1742 'exclude_post_data' => ! current_user_can( 'customize' ), 1743 ), 1744 $args 1745 ); 1746 1747 $values = array(); 1748 1749 // Let default values be from the stashed theme mods if doing a theme switch and if no changeset is present. 1750 if ( ! $this->is_theme_active() ) { 1751 $stashed_theme_mods = get_option( 'customize_stashed_theme_mods' ); 1752 $stylesheet = $this->get_stylesheet(); 1753 if ( isset( $stashed_theme_mods[ $stylesheet ] ) ) { 1754 $values = array_merge( $values, wp_list_pluck( $stashed_theme_mods[ $stylesheet ], 'value' ) ); 1755 } 1756 } 1757 1758 if ( ! $args['exclude_changeset'] ) { 1759 foreach ( $this->changeset_data() as $setting_id => $setting_params ) { 1760 if ( ! array_key_exists( 'value', $setting_params ) ) { 1761 continue; 1762 } 1763 if ( isset( $setting_params['type'] ) && 'theme_mod' === $setting_params['type'] ) { 1764 1765 // Ensure that theme mods values are only used if they were saved under the current theme. 1766 $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/'; 1767 if ( preg_match( $namespace_pattern, $setting_id, $matches ) && $this->get_stylesheet() === $matches['stylesheet'] ) { 1768 $values[ $matches['setting_id'] ] = $setting_params['value']; 1769 } 1770 } else { 1771 $values[ $setting_id ] = $setting_params['value']; 1772 } 1773 } 1774 } 1775 1776 if ( ! $args['exclude_post_data'] ) { 1777 if ( ! isset( $this->_post_values ) ) { 1778 if ( isset( $_POST['customized'] ) ) { 1779 $post_values = json_decode( wp_unslash( $_POST['customized'] ), true ); 1780 } else { 1781 $post_values = array(); 1782 } 1783 if ( is_array( $post_values ) ) { 1784 $this->_post_values = $post_values; 1785 } else { 1786 $this->_post_values = array(); 1787 } 1788 } 1789 $values = array_merge( $values, $this->_post_values ); 1790 } 1791 return $values; 1792 } 1793 1794 /** 1795 * Returns the sanitized value for a given setting from the current customized state. 1796 * 1797 * The name "post_value" is a carry-over from when the customized state was exclusively 1798 * sourced from `$_POST['customized']`. Nevertheless, the value returned will come 1799 * from the current changeset post and from the incoming post data. 1800 * 1801 * @since 3.4.0 1802 * @since 4.1.1 Introduced the `$default` parameter. 1803 * @since 4.6.0 `$default` is now returned early when the setting post value is invalid. 1804 * 1805 * @see WP_REST_Server::dispatch() 1806 * @see WP_REST_Request::sanitize_params() 1807 * @see WP_REST_Request::has_valid_params() 1808 * 1809 * @param WP_Customize_Setting $setting A WP_Customize_Setting derived object. 1810 * @param mixed $default Value returned $setting has no post value (added in 4.2.0) 1811 * or the post value is invalid (added in 4.6.0). 1812 * @return string|mixed $post_value Sanitized value or the $default provided. 1813 */ 1814 public function post_value( $setting, $default = null ) { 1815 $post_values = $this->unsanitized_post_values(); 1816 if ( ! array_key_exists( $setting->id, $post_values ) ) { 1817 return $default; 1818 } 1819 $value = $post_values[ $setting->id ]; 1820 $valid = $setting->validate( $value ); 1821 if ( is_wp_error( $valid ) ) { 1822 return $default; 1823 } 1824 $value = $setting->sanitize( $value ); 1825 if ( is_null( $value ) || is_wp_error( $value ) ) { 1826 return $default; 1827 } 1828 return $value; 1829 } 1830 1831 /** 1832 * Override a setting's value in the current customized state. 1833 * 1834 * The name "post_value" is a carry-over from when the customized state was 1835 * exclusively sourced from `$_POST['customized']`. 1836 * 1837 * @since 4.2.0 1838 * 1839 * @param string $setting_id ID for the WP_Customize_Setting instance. 1840 * @param mixed $value Post value. 1841 */ 1842 public function set_post_value( $setting_id, $value ) { 1843 $this->unsanitized_post_values(); // Populate _post_values from $_POST['customized']. 1844 $this->_post_values[ $setting_id ] = $value; 1845 1846 /** 1847 * Announce when a specific setting's unsanitized post value has been set. 1848 * 1849 * Fires when the WP_Customize_Manager::set_post_value() method is called. 1850 * 1851 * The dynamic portion of the hook name, `$setting_id`, refers to the setting ID. 1852 * 1853 * @since 4.4.0 1854 * 1855 * @param mixed $value Unsanitized setting post value. 1856 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 1857 */ 1858 do_action( "customize_post_value_set_{$setting_id}", $value, $this ); 1859 1860 /** 1861 * Announce when any setting's unsanitized post value has been set. 1862 * 1863 * Fires when the WP_Customize_Manager::set_post_value() method is called. 1864 * 1865 * This is useful for `WP_Customize_Setting` instances to watch 1866 * in order to update a cached previewed value. 1867 * 1868 * @since 4.4.0 1869 * 1870 * @param string $setting_id Setting ID. 1871 * @param mixed $value Unsanitized setting post value. 1872 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 1873 */ 1874 do_action( 'customize_post_value_set', $setting_id, $value, $this ); 1875 } 1876 1877 /** 1878 * Print JavaScript settings. 1879 * 1880 * @since 3.4.0 1881 */ 1882 public function customize_preview_init() { 1883 1884 /* 1885 * Now that Customizer previews are loaded into iframes via GET requests 1886 * and natural URLs with transaction UUIDs added, we need to ensure that 1887 * the responses are never cached by proxies. In practice, this will not 1888 * be needed if the user is logged-in anyway. But if anonymous access is 1889 * allowed then the auth cookies would not be sent and WordPress would 1890 * not send no-cache headers by default. 1891 */ 1892 if ( ! headers_sent() ) { 1893 nocache_headers(); 1894 header( 'X-Robots: noindex, nofollow, noarchive' ); 1895 } 1896 add_action( 'wp_head', 'wp_no_robots' ); 1897 add_filter( 'wp_headers', array( $this, 'filter_iframe_security_headers' ) ); 1898 1899 /* 1900 * If preview is being served inside the customizer preview iframe, and 1901 * if the user doesn't have customize capability, then it is assumed 1902 * that the user's session has expired and they need to re-authenticate. 1903 */ 1904 if ( $this->messenger_channel && ! current_user_can( 'customize' ) ) { 1905 $this->wp_die( -1, __( 'Unauthorized. You may remove the customize_messenger_channel param to preview as frontend.' ) ); 1906 return; 1907 } 1908 1909 $this->prepare_controls(); 1910 1911 add_filter( 'wp_redirect', array( $this, 'add_state_query_params' ) ); 1912 1913 wp_enqueue_script( 'customize-preview' ); 1914 wp_enqueue_style( 'customize-preview' ); 1915 add_action( 'wp_head', array( $this, 'customize_preview_loading_style' ) ); 1916 add_action( 'wp_head', array( $this, 'remove_frameless_preview_messenger_channel' ) ); 1917 add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 ); 1918 add_filter( 'get_edit_post_link', '__return_empty_string' ); 1919 1920 /** 1921 * Fires once the Customizer preview has initialized and JavaScript 1922 * settings have been printed. 1923 * 1924 * @since 3.4.0 1925 * 1926 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 1927 */ 1928 do_action( 'customize_preview_init', $this ); 1929 } 1930 1931 /** 1932 * Filter the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer. 1933 * 1934 * @since 4.7.0 1935 * 1936 * @param array $headers Headers. 1937 * @return array Headers. 1938 */ 1939 public function filter_iframe_security_headers( $headers ) { 1940 $headers['X-Frame-Options'] = 'SAMEORIGIN'; 1941 $headers['Content-Security-Policy'] = "frame-ancestors 'self'"; 1942 return $headers; 1943 } 1944 1945 /** 1946 * Add customize state query params to a given URL if preview is allowed. 1947 * 1948 * @since 4.7.0 1949 * @see wp_redirect() 1950 * @see WP_Customize_Manager::get_allowed_url() 1951 * 1952 * @param string $url URL. 1953 * @return string URL. 1954 */ 1955 public function add_state_query_params( $url ) { 1956 $parsed_original_url = wp_parse_url( $url ); 1957 $is_allowed = false; 1958 foreach ( $this->get_allowed_urls() as $allowed_url ) { 1959 $parsed_allowed_url = wp_parse_url( $allowed_url ); 1960 $is_allowed = ( 1961 $parsed_allowed_url['scheme'] === $parsed_original_url['scheme'] 1962 && 1963 $parsed_allowed_url['host'] === $parsed_original_url['host'] 1964 && 1965 0 === strpos( $parsed_original_url['path'], $parsed_allowed_url['path'] ) 1966 ); 1967 if ( $is_allowed ) { 1968 break; 1969 } 1970 } 1971 1972 if ( $is_allowed ) { 1973 $query_params = array( 1974 'customize_changeset_uuid' => $this->changeset_uuid(), 1975 ); 1976 if ( ! $this->is_theme_active() ) { 1977 $query_params['customize_theme'] = $this->get_stylesheet(); 1978 } 1979 if ( $this->messenger_channel ) { 1980 $query_params['customize_messenger_channel'] = $this->messenger_channel; 1981 } 1982 $url = add_query_arg( $query_params, $url ); 1983 } 1984 1985 return $url; 1986 } 1987 1988 /** 1989 * Prevent sending a 404 status when returning the response for the customize 1990 * preview, since it causes the jQuery Ajax to fail. Send 200 instead. 1991 * 1992 * @since 4.0.0 1993 * @deprecated 4.7.0 1994 */ 1995 public function customize_preview_override_404_status() { 1996 _deprecated_function( __METHOD__, '4.7.0' ); 1997 } 1998 1999 /** 2000 * Print base element for preview frame. 2001 * 2002 * @since 3.4.0 2003 * @deprecated 4.7.0 2004 */ 2005 public function customize_preview_base() { 2006 _deprecated_function( __METHOD__, '4.7.0' ); 2007 } 2008 2009 /** 2010 * Print a workaround to handle HTML5 tags in IE < 9. 2011 * 2012 * @since 3.4.0 2013 * @deprecated 4.7.0 Customizer no longer supports IE8, so all supported browsers recognize HTML5. 2014 */ 2015 public function customize_preview_html5() { 2016 _deprecated_function( __FUNCTION__, '4.7.0' ); 2017 } 2018 2019 /** 2020 * Print CSS for loading indicators for the Customizer preview. 2021 * 2022 * @since 4.2.0 2023 */ 2024 public function customize_preview_loading_style() { 2025 ?> 2026 <style> 2027 body.wp-customizer-unloading { 2028 opacity: 0.25; 2029 cursor: progress !important; 2030 -webkit-transition: opacity 0.5s; 2031 transition: opacity 0.5s; 2032 } 2033 body.wp-customizer-unloading * { 2034 pointer-events: none !important; 2035 } 2036 form.customize-unpreviewable, 2037 form.customize-unpreviewable input, 2038 form.customize-unpreviewable select, 2039 form.customize-unpreviewable button, 2040 a.customize-unpreviewable, 2041 area.customize-unpreviewable { 2042 cursor: not-allowed !important; 2043 } 2044 </style> 2045 <?php 2046 } 2047 2048 /** 2049 * Remove customize_messenger_channel query parameter from the preview window when it is not in an iframe. 2050 * 2051 * This ensures that the admin bar will be shown. It also ensures that link navigation will 2052 * work as expected since the parent frame is not being sent the URL to navigate to. 2053 * 2054 * @since 4.7.0 2055 */ 2056 public function remove_frameless_preview_messenger_channel() { 2057 if ( ! $this->messenger_channel ) { 2058 return; 2059 } 2060 ?> 2061 <script> 2062 ( function() { 2063 var urlParser, oldQueryParams, newQueryParams, i; 2064 if ( parent !== window ) { 2065 return; 2066 } 2067 urlParser = document.createElement( 'a' ); 2068 urlParser.href = location.href; 2069 oldQueryParams = urlParser.search.substr( 1 ).split( /&/ ); 2070 newQueryParams = []; 2071 for ( i = 0; i < oldQueryParams.length; i += 1 ) { 2072 if ( ! /^customize_messenger_channel=/.test( oldQueryParams[ i ] ) ) { 2073 newQueryParams.push( oldQueryParams[ i ] ); 2074 } 2075 } 2076 urlParser.search = newQueryParams.join( '&' ); 2077 if ( urlParser.search !== location.search ) { 2078 location.replace( urlParser.href ); 2079 } 2080 } )(); 2081 </script> 2082 <?php 2083 } 2084 2085 /** 2086 * Print JavaScript settings for preview frame. 2087 * 2088 * @since 3.4.0 2089 */ 2090 public function customize_preview_settings() { 2091 $post_values = $this->unsanitized_post_values( array( 'exclude_changeset' => true ) ); 2092 $setting_validities = $this->validate_setting_values( $post_values ); 2093 $exported_setting_validities = array_map( array( $this, 'prepare_setting_validity_for_js' ), $setting_validities ); 2094 2095 // Note that the REQUEST_URI is not passed into home_url() since this breaks subdirectory installations. 2096 $self_url = empty( $_SERVER['REQUEST_URI'] ) ? home_url( '/' ) : esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ); 2097 $state_query_params = array( 2098 'customize_theme', 2099 'customize_changeset_uuid', 2100 'customize_messenger_channel', 2101 ); 2102 $self_url = remove_query_arg( $state_query_params, $self_url ); 2103 2104 $allowed_urls = $this->get_allowed_urls(); 2105 $allowed_hosts = array(); 2106 foreach ( $allowed_urls as $allowed_url ) { 2107 $parsed = wp_parse_url( $allowed_url ); 2108 if ( empty( $parsed['host'] ) ) { 2109 continue; 2110 } 2111 $host = $parsed['host']; 2112 if ( ! empty( $parsed['port'] ) ) { 2113 $host .= ':' . $parsed['port']; 2114 } 2115 $allowed_hosts[] = $host; 2116 } 2117 2118 $switched_locale = switch_to_locale( get_user_locale() ); 2119 $l10n = array( 2120 'shiftClickToEdit' => __( 'Shift-click to edit this element.' ), 2121 'linkUnpreviewable' => __( 'This link is not live-previewable.' ), 2122 'formUnpreviewable' => __( 'This form is not live-previewable.' ), 2123 ); 2124 if ( $switched_locale ) { 2125 restore_previous_locale(); 2126 } 2127 2128 $settings = array( 2129 'changeset' => array( 2130 'uuid' => $this->changeset_uuid(), 2131 'autosaved' => $this->autosaved(), 2132 ), 2133 'timeouts' => array( 2134 'selectiveRefresh' => 250, 2135 'keepAliveSend' => 1000, 2136 ), 2137 'theme' => array( 2138 'stylesheet' => $this->get_stylesheet(), 2139 'active' => $this->is_theme_active(), 2140 ), 2141 'url' => array( 2142 'self' => $self_url, 2143 'allowed' => array_map( 'esc_url_raw', $this->get_allowed_urls() ), 2144 'allowedHosts' => array_unique( $allowed_hosts ), 2145 'isCrossDomain' => $this->is_cross_domain(), 2146 ), 2147 'channel' => $this->messenger_channel, 2148 'activePanels' => array(), 2149 'activeSections' => array(), 2150 'activeControls' => array(), 2151 'settingValidities' => $exported_setting_validities, 2152 'nonce' => current_user_can( 'customize' ) ? $this->get_nonces() : array(), 2153 'l10n' => $l10n, 2154 '_dirty' => array_keys( $post_values ), 2155 ); 2156 2157 foreach ( $this->panels as $panel_id => $panel ) { 2158 if ( $panel->check_capabilities() ) { 2159 $settings['activePanels'][ $panel_id ] = $panel->active(); 2160 foreach ( $panel->sections as $section_id => $section ) { 2161 if ( $section->check_capabilities() ) { 2162 $settings['activeSections'][ $section_id ] = $section->active(); 2163 } 2164 } 2165 } 2166 } 2167 foreach ( $this->sections as $id => $section ) { 2168 if ( $section->check_capabilities() ) { 2169 $settings['activeSections'][ $id ] = $section->active(); 2170 } 2171 } 2172 foreach ( $this->controls as $id => $control ) { 2173 if ( $control->check_capabilities() ) { 2174 $settings['activeControls'][ $id ] = $control->active(); 2175 } 2176 } 2177 2178 ?> 2179 <script type="text/javascript"> 2180 var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>; 2181 _wpCustomizeSettings.values = {}; 2182 (function( v ) { 2183 <?php 2184 /* 2185 * Serialize settings separately from the initial _wpCustomizeSettings 2186 * serialization in order to avoid a peak memory usage spike. 2187 * @todo We may not even need to export the values at all since the pane syncs them anyway. 2188 */ 2189 foreach ( $this->settings as $id => $setting ) { 2190 if ( $setting->check_capabilities() ) { 2191 printf( 2192 "v[%s] = %s;\n", 2193 wp_json_encode( $id ), 2194 wp_json_encode( $setting->js_value() ) 2195 ); 2196 } 2197 } 2198 ?> 2199 })( _wpCustomizeSettings.values ); 2200 </script> 2201 <?php 2202 } 2203 2204 /** 2205 * Prints a signature so we can ensure the Customizer was properly executed. 2206 * 2207 * @since 3.4.0 2208 * @deprecated 4.7.0 2209 */ 2210 public function customize_preview_signature() { 2211 _deprecated_function( __METHOD__, '4.7.0' ); 2212 } 2213 2214 /** 2215 * Removes the signature in case we experience a case where the Customizer was not properly executed. 2216 * 2217 * @since 3.4.0 2218 * @deprecated 4.7.0 2219 * 2220 * @param mixed $return Value passed through for {@see 'wp_die_handler'} filter. 2221 * @return mixed Value passed through for {@see 'wp_die_handler'} filter. 2222 */ 2223 public function remove_preview_signature( $return = null ) { 2224 _deprecated_function( __METHOD__, '4.7.0' ); 2225 2226 return $return; 2227 } 2228 2229 /** 2230 * Is it a theme preview? 2231 * 2232 * @since 3.4.0 2233 * 2234 * @return bool True if it's a preview, false if not. 2235 */ 2236 public function is_preview() { 2237 return (bool) $this->previewing; 2238 } 2239 2240 /** 2241 * Retrieve the template name of the previewed theme. 2242 * 2243 * @since 3.4.0 2244 * 2245 * @return string Template name. 2246 */ 2247 public function get_template() { 2248 return $this->theme()->get_template(); 2249 } 2250 2251 /** 2252 * Retrieve the stylesheet name of the previewed theme. 2253 * 2254 * @since 3.4.0 2255 * 2256 * @return string Stylesheet name. 2257 */ 2258 public function get_stylesheet() { 2259 return $this->theme()->get_stylesheet(); 2260 } 2261 2262 /** 2263 * Retrieve the template root of the previewed theme. 2264 * 2265 * @since 3.4.0 2266 * 2267 * @return string Theme root. 2268 */ 2269 public function get_template_root() { 2270 return get_raw_theme_root( $this->get_template(), true ); 2271 } 2272 2273 /** 2274 * Retrieve the stylesheet root of the previewed theme. 2275 * 2276 * @since 3.4.0 2277 * 2278 * @return string Theme root. 2279 */ 2280 public function get_stylesheet_root() { 2281 return get_raw_theme_root( $this->get_stylesheet(), true ); 2282 } 2283 2284 /** 2285 * Filters the current theme and return the name of the previewed theme. 2286 * 2287 * @since 3.4.0 2288 * 2289 * @param $current_theme {@internal Parameter is not used} 2290 * @return string Theme name. 2291 */ 2292 public function current_theme( $current_theme ) { 2293 return $this->theme()->display( 'Name' ); 2294 } 2295 2296 /** 2297 * Validates setting values. 2298 * 2299 * Validation is skipped for unregistered settings or for values that are 2300 * already null since they will be skipped anyway. Sanitization is applied 2301 * to values that pass validation, and values that become null or `WP_Error` 2302 * after sanitizing are marked invalid. 2303 * 2304 * @since 4.6.0 2305 * 2306 * @see WP_REST_Request::has_valid_params() 2307 * @see WP_Customize_Setting::validate() 2308 * 2309 * @param array $setting_values Mapping of setting IDs to values to validate and sanitize. 2310 * @param array $options { 2311 * Options. 2312 * 2313 * @type bool $validate_existence Whether a setting's existence will be checked. 2314 * @type bool $validate_capability Whether the setting capability will be checked. 2315 * } 2316 * @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`. 2317 */ 2318 public function validate_setting_values( $setting_values, $options = array() ) { 2319 $options = wp_parse_args( 2320 $options, 2321 array( 2322 'validate_capability' => false, 2323 'validate_existence' => false, 2324 ) 2325 ); 2326 2327 $validities = array(); 2328 foreach ( $setting_values as $setting_id => $unsanitized_value ) { 2329 $setting = $this->get_setting( $setting_id ); 2330 if ( ! $setting ) { 2331 if ( $options['validate_existence'] ) { 2332 $validities[ $setting_id ] = new WP_Error( 'unrecognized', __( 'Setting does not exist or is unrecognized.' ) ); 2333 } 2334 continue; 2335 } 2336 if ( $options['validate_capability'] && ! current_user_can( $setting->capability ) ) { 2337 $validity = new WP_Error( 'unauthorized', __( 'Unauthorized to modify setting due to capability.' ) ); 2338 } else { 2339 if ( is_null( $unsanitized_value ) ) { 2340 continue; 2341 } 2342 $validity = $setting->validate( $unsanitized_value ); 2343 } 2344 if ( ! is_wp_error( $validity ) ) { 2345 /** This filter is documented in wp-includes/class-wp-customize-setting.php */ 2346 $late_validity = apply_filters( "customize_validate_{$setting->id}", new WP_Error(), $unsanitized_value, $setting ); 2347 if ( is_wp_error( $late_validity ) && $late_validity->has_errors() ) { 2348 $validity = $late_validity; 2349 } 2350 } 2351 if ( ! is_wp_error( $validity ) ) { 2352 $value = $setting->sanitize( $unsanitized_value ); 2353 if ( is_null( $value ) ) { 2354 $validity = false; 2355 } elseif ( is_wp_error( $value ) ) { 2356 $validity = $value; 2357 } 2358 } 2359 if ( false === $validity ) { 2360 $validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) ); 2361 } 2362 $validities[ $setting_id ] = $validity; 2363 } 2364 return $validities; 2365 } 2366 2367 /** 2368 * Prepares setting validity for exporting to the client (JS). 2369 * 2370 * Converts `WP_Error` instance into array suitable for passing into the 2371 * `wp.customize.Notification` JS model. 2372 * 2373 * @since 4.6.0 2374 * 2375 * @param true|WP_Error $validity Setting validity. 2376 * @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped 2377 * to their respective `message` and `data` to pass into the 2378 * `wp.customize.Notification` JS model. 2379 */ 2380 public function prepare_setting_validity_for_js( $validity ) { 2381 if ( is_wp_error( $validity ) ) { 2382 $notification = array(); 2383 foreach ( $validity->errors as $error_code => $error_messages ) { 2384 $notification[ $error_code ] = array( 2385 'message' => join( ' ', $error_messages ), 2386 'data' => $validity->get_error_data( $error_code ), 2387 ); 2388 } 2389 return $notification; 2390 } else { 2391 return true; 2392 } 2393 } 2394 2395 /** 2396 * Handle customize_save WP Ajax request to save/update a changeset. 2397 * 2398 * @since 3.4.0 2399 * @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes. 2400 */ 2401 public function save() { 2402 if ( ! is_user_logged_in() ) { 2403 wp_send_json_error( 'unauthenticated' ); 2404 } 2405 2406 if ( ! $this->is_preview() ) { 2407 wp_send_json_error( 'not_preview' ); 2408 } 2409 2410 $action = 'save-customize_' . $this->get_stylesheet(); 2411 if ( ! check_ajax_referer( $action, 'nonce', false ) ) { 2412 wp_send_json_error( 'invalid_nonce' ); 2413 } 2414 2415 $changeset_post_id = $this->changeset_post_id(); 2416 $is_new_changeset = empty( $changeset_post_id ); 2417 if ( $is_new_changeset ) { 2418 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) { 2419 wp_send_json_error( 'cannot_create_changeset_post' ); 2420 } 2421 } else { 2422 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { 2423 wp_send_json_error( 'cannot_edit_changeset_post' ); 2424 } 2425 } 2426 2427 if ( ! empty( $_POST['customize_changeset_data'] ) ) { 2428 $input_changeset_data = json_decode( wp_unslash( $_POST['customize_changeset_data'] ), true ); 2429 if ( ! is_array( $input_changeset_data ) ) { 2430 wp_send_json_error( 'invalid_customize_changeset_data' ); 2431 } 2432 } else { 2433 $input_changeset_data = array(); 2434 } 2435 2436 // Validate title. 2437 $changeset_title = null; 2438 if ( isset( $_POST['customize_changeset_title'] ) ) { 2439 $changeset_title = sanitize_text_field( wp_unslash( $_POST['customize_changeset_title'] ) ); 2440 } 2441 2442 // Validate changeset status param. 2443 $is_publish = null; 2444 $changeset_status = null; 2445 if ( isset( $_POST['customize_changeset_status'] ) ) { 2446 $changeset_status = wp_unslash( $_POST['customize_changeset_status'] ); 2447 if ( ! get_post_status_object( $changeset_status ) || ! in_array( $changeset_status, array( 'draft', 'pending', 'publish', 'future' ), true ) ) { 2448 wp_send_json_error( 'bad_customize_changeset_status', 400 ); 2449 } 2450 $is_publish = ( 'publish' === $changeset_status || 'future' === $changeset_status ); 2451 if ( $is_publish && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) { 2452 wp_send_json_error( 'changeset_publish_unauthorized', 403 ); 2453 } 2454 } 2455 2456 /* 2457 * Validate changeset date param. Date is assumed to be in local time for 2458 * the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date 2459 * is parsed with strtotime() so that ISO date format may be supplied 2460 * or a string like "+10 minutes". 2461 */ 2462 $changeset_date_gmt = null; 2463 if ( isset( $_POST['customize_changeset_date'] ) ) { 2464 $changeset_date = wp_unslash( $_POST['customize_changeset_date'] ); 2465 if ( preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $changeset_date ) ) { 2466 $mm = substr( $changeset_date, 5, 2 ); 2467 $jj = substr( $changeset_date, 8, 2 ); 2468 $aa = substr( $changeset_date, 0, 4 ); 2469 $valid_date = wp_checkdate( $mm, $jj, $aa, $changeset_date ); 2470 if ( ! $valid_date ) { 2471 wp_send_json_error( 'bad_customize_changeset_date', 400 ); 2472 } 2473 $changeset_date_gmt = get_gmt_from_date( $changeset_date ); 2474 } else { 2475 $timestamp = strtotime( $changeset_date ); 2476 if ( ! $timestamp ) { 2477 wp_send_json_error( 'bad_customize_changeset_date', 400 ); 2478 } 2479 $changeset_date_gmt = gmdate( 'Y-m-d H:i:s', $timestamp ); 2480 } 2481 } 2482 2483 $lock_user_id = null; 2484 $autosave = ! empty( $_POST['customize_changeset_autosave'] ); 2485 if ( ! $is_new_changeset ) { 2486 $lock_user_id = wp_check_post_lock( $this->changeset_post_id() ); 2487 } 2488 2489 // Force request to autosave when changeset is locked. 2490 if ( $lock_user_id && ! $autosave ) { 2491 $autosave = true; 2492 $changeset_status = null; 2493 $changeset_date_gmt = null; 2494 } 2495 2496 if ( $autosave && ! defined( 'DOING_AUTOSAVE' ) ) { // Back-compat. 2497 define( 'DOING_AUTOSAVE', true ); 2498 } 2499 2500 $autosaved = false; 2501 $r = $this->save_changeset_post( 2502 array( 2503 'status' => $changeset_status, 2504 'title' => $changeset_title, 2505 'date_gmt' => $changeset_date_gmt, 2506 'data' => $input_changeset_data, 2507 'autosave' => $autosave, 2508 ) 2509 ); 2510 if ( $autosave && ! is_wp_error( $r ) ) { 2511 $autosaved = true; 2512 } 2513 2514 // If the changeset was locked and an autosave request wasn't itself an error, then now explicitly return with a failure. 2515 if ( $lock_user_id && ! is_wp_error( $r ) ) { 2516 $r = new WP_Error( 2517 'changeset_locked', 2518 __( 'Changeset is being edited by other user.' ), 2519 array( 2520 'lock_user' => $this->get_lock_user_data( $lock_user_id ), 2521 ) 2522 ); 2523 } 2524 2525 if ( is_wp_error( $r ) ) { 2526 $response = array( 2527 'message' => $r->get_error_message(), 2528 'code' => $r->get_error_code(), 2529 ); 2530 if ( is_array( $r->get_error_data() ) ) { 2531 $response = array_merge( $response, $r->get_error_data() ); 2532 } else { 2533 $response['data'] = $r->get_error_data(); 2534 } 2535 } else { 2536 $response = $r; 2537 $changeset_post = get_post( $this->changeset_post_id() ); 2538 2539 // Dismiss all other auto-draft changeset posts for this user (they serve like autosave revisions), as there should only be one. 2540 if ( $is_new_changeset ) { 2541 $this->dismiss_user_auto_draft_changesets(); 2542 } 2543 2544 // Note that if the changeset status was publish, then it will get set to Trash if revisions are not supported. 2545 $response['changeset_status'] = $changeset_post->post_status; 2546 if ( $is_publish && 'trash' === $response['changeset_status'] ) { 2547 $response['changeset_status'] = 'publish'; 2548 } 2549 2550 if ( 'publish' !== $response['changeset_status'] ) { 2551 $this->set_changeset_lock( $changeset_post->ID ); 2552 } 2553 2554 if ( 'future' === $response['changeset_status'] ) { 2555 $response['changeset_date'] = $changeset_post->post_date; 2556 } 2557 2558 if ( 'publish' === $response['changeset_status'] || 'trash' === $response['changeset_status'] ) { 2559 $response['next_changeset_uuid'] = wp_generate_uuid4(); 2560 } 2561 } 2562 2563 if ( $autosave ) { 2564 $response['autosaved'] = $autosaved; 2565 } 2566 2567 if ( isset( $response['setting_validities'] ) ) { 2568 $response['setting_validities'] = array_map( array( $this, 'prepare_setting_validity_for_js' ), $response['setting_validities'] ); 2569 } 2570 2571 /** 2572 * Filters response data for a successful customize_save Ajax request. 2573 * 2574 * This filter does not apply if there was a nonce or authentication failure. 2575 * 2576 * @since 4.2.0 2577 * 2578 * @param array $response Additional information passed back to the 'saved' 2579 * event on `wp.customize`. 2580 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 2581 */ 2582 $response = apply_filters( 'customize_save_response', $response, $this ); 2583 2584 if ( is_wp_error( $r ) ) { 2585 wp_send_json_error( $response ); 2586 } else { 2587 wp_send_json_success( $response ); 2588 } 2589 } 2590 2591 /** 2592 * Save the post for the loaded changeset. 2593 * 2594 * @since 4.7.0 2595 * 2596 * @param array $args { 2597 * Args for changeset post. 2598 * 2599 * @type array $data Optional additional changeset data. Values will be merged on top of any existing post values. 2600 * @type string $status Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed. 2601 * @type string $title Post title. Optional. 2602 * @type string $date_gmt Date in GMT. Optional. 2603 * @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID. 2604 * @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved. 2605 * @type bool $autosave Whether this is a request to create an autosave revision. 2606 * } 2607 * 2608 * @return array|WP_Error Returns array on success and WP_Error with array data on error. 2609 */ 2610 function save_changeset_post( $args = array() ) { 2611 2612 $args = array_merge( 2613 array( 2614 'status' => null, 2615 'title' => null, 2616 'data' => array(), 2617 'date_gmt' => null, 2618 'user_id' => get_current_user_id(), 2619 'starter_content' => false, 2620 'autosave' => false, 2621 ), 2622 $args 2623 ); 2624 2625 $changeset_post_id = $this->changeset_post_id(); 2626 $existing_changeset_data = array(); 2627 if ( $changeset_post_id ) { 2628 $existing_status = get_post_status( $changeset_post_id ); 2629 if ( 'publish' === $existing_status || 'trash' === $existing_status ) { 2630 return new WP_Error( 2631 'changeset_already_published', 2632 __( 'The previous set of changes has already been published. Please try saving your current set of changes again.' ), 2633 array( 2634 'next_changeset_uuid' => wp_generate_uuid4(), 2635 ) 2636 ); 2637 } 2638 2639 $existing_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); 2640 if ( is_wp_error( $existing_changeset_data ) ) { 2641 return $existing_changeset_data; 2642 } 2643 } 2644 2645 // Fail if attempting to publish but publish hook is missing. 2646 if ( 'publish' === $args['status'] && false === has_action( 'transition_post_status', '_wp_customize_publish_changeset' ) ) { 2647 return new WP_Error( 'missing_publish_callback' ); 2648 } 2649 2650 // Validate date. 2651 $now = gmdate( 'Y-m-d H:i:59' ); 2652 if ( $args['date_gmt'] ) { 2653 $is_future_dated = ( mysql2date( 'U', $args['date_gmt'], false ) > mysql2date( 'U', $now, false ) ); 2654 if ( ! $is_future_dated ) { 2655 return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); // Only future dates are allowed. 2656 } 2657 2658 if ( ! $this->is_theme_active() && ( 'future' === $args['status'] || $is_future_dated ) ) { 2659 return new WP_Error( 'cannot_schedule_theme_switches' ); // This should be allowed in the future, when theme is a regular setting. 2660 } 2661 $will_remain_auto_draft = ( ! $args['status'] && ( ! $changeset_post_id || 'auto-draft' === get_post_status( $changeset_post_id ) ) ); 2662 if ( $will_remain_auto_draft ) { 2663 return new WP_Error( 'cannot_supply_date_for_auto_draft_changeset' ); 2664 } 2665 } elseif ( $changeset_post_id && 'future' === $args['status'] ) { 2666 2667 // Fail if the new status is future but the existing post's date is not in the future. 2668 $changeset_post = get_post( $changeset_post_id ); 2669 if ( mysql2date( 'U', $changeset_post->post_date_gmt, false ) <= mysql2date( 'U', $now, false ) ) { 2670 return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); 2671 } 2672 } 2673 2674 if ( ! empty( $is_future_dated ) && 'publish' === $args['status'] ) { 2675 $args['status'] = 'future'; 2676 } 2677 2678 // Validate autosave param. See _wp_post_revision_fields() for why these fields are disallowed. 2679 if ( $args['autosave'] ) { 2680 if ( $args['date_gmt'] ) { 2681 return new WP_Error( 'illegal_autosave_with_date_gmt' ); 2682 } elseif ( $args['status'] ) { 2683 return new WP_Error( 'illegal_autosave_with_status' ); 2684 } elseif ( $args['user_id'] && get_current_user_id() !== $args['user_id'] ) { 2685 return new WP_Error( 'illegal_autosave_with_non_current_user' ); 2686 } 2687 } 2688 2689 // The request was made via wp.customize.previewer.save(). 2690 $update_transactionally = (bool) $args['status']; 2691 $allow_revision = (bool) $args['status']; 2692 2693 // Amend post values with any supplied data. 2694 foreach ( $args['data'] as $setting_id => $setting_params ) { 2695 if ( is_array( $setting_params ) && array_key_exists( 'value', $setting_params ) ) { 2696 $this->set_post_value( $setting_id, $setting_params['value'] ); // Add to post values so that they can be validated and sanitized. 2697 } 2698 } 2699 2700 // Note that in addition to post data, this will include any stashed theme mods. 2701 $post_values = $this->unsanitized_post_values( 2702 array( 2703 'exclude_changeset' => true, 2704 'exclude_post_data' => false, 2705 ) 2706 ); 2707 $this->add_dynamic_settings( array_keys( $post_values ) ); // Ensure settings get created even if they lack an input value. 2708 2709 /* 2710 * Get list of IDs for settings that have values different from what is currently 2711 * saved in the changeset. By skipping any values that are already the same, the 2712 * subset of changed settings can be passed into validate_setting_values to prevent 2713 * an underprivileged modifying a single setting for which they have the capability 2714 * from being blocked from saving. This also prevents a user from touching of the 2715 * previous saved settings and overriding the associated user_id if they made no change. 2716 */ 2717 $changed_setting_ids = array(); 2718 foreach ( $post_values as $setting_id => $setting_value ) { 2719 $setting = $this->get_setting( $setting_id ); 2720 2721 if ( $setting && 'theme_mod' === $setting->type ) { 2722 $prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id; 2723 } else { 2724 $prefixed_setting_id = $setting_id; 2725 } 2726 2727 $is_value_changed = ( 2728 ! isset( $existing_changeset_data[ $prefixed_setting_id ] ) 2729 || 2730 ! array_key_exists( 'value', $existing_changeset_data[ $prefixed_setting_id ] ) 2731 || 2732 $existing_changeset_data[ $prefixed_setting_id ]['value'] !== $setting_value 2733 ); 2734 if ( $is_value_changed ) { 2735 $changed_setting_ids[] = $setting_id; 2736 } 2737 } 2738 2739 /** 2740 * Fires before save validation happens. 2741 * 2742 * Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters 2743 * at this point to catch any settings registered after `customize_register`. 2744 * The dynamic portion of the hook name, `$this->ID` refers to the setting ID. 2745 * 2746 * @since 4.6.0 2747 * 2748 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 2749 */ 2750 do_action( 'customize_save_validation_before', $this ); 2751 2752 // Validate settings. 2753 $validated_values = array_merge( 2754 array_fill_keys( array_keys( $args['data'] ), null ), // Make sure existence/capability checks are done on value-less setting updates. 2755 $post_values 2756 ); 2757 $setting_validities = $this->validate_setting_values( 2758 $validated_values, 2759 array( 2760 'validate_capability' => true, 2761 'validate_existence' => true, 2762 ) 2763 ); 2764 $invalid_setting_count = count( array_filter( $setting_validities, 'is_wp_error' ) ); 2765 2766 /* 2767 * Short-circuit if there are invalid settings the update is transactional. 2768 * A changeset update is transactional when a status is supplied in the request. 2769 */ 2770 if ( $update_transactionally && $invalid_setting_count > 0 ) { 2771 $response = array( 2772 'setting_validities' => $setting_validities, 2773 /* translators: %s: Number of invalid settings. */ 2774 '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 ) ), 2775 ); 2776 return new WP_Error( 'transaction_fail', '', $response ); 2777 } 2778 2779 // Obtain/merge data for changeset. 2780 $original_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); 2781 $data = $original_changeset_data; 2782 if ( is_wp_error( $data ) ) { 2783 $data = array(); 2784 } 2785 2786 // Ensure that all post values are included in the changeset data. 2787 foreach ( $post_values as $setting_id => $post_value ) { 2788 if ( ! isset( $args['data'][ $setting_id ] ) ) { 2789 $args['data'][ $setting_id ] = array(); 2790 } 2791 if ( ! isset( $args['data'][ $setting_id ]['value'] ) ) { 2792 $args['data'][ $setting_id ]['value'] = $post_value; 2793 } 2794 } 2795 2796 foreach ( $args['data'] as $setting_id => $setting_params ) { 2797 $setting = $this->get_setting( $setting_id ); 2798 if ( ! $setting || ! $setting->check_capabilities() ) { 2799 continue; 2800 } 2801 2802 // Skip updating changeset for invalid setting values. 2803 if ( isset( $setting_validities[ $setting_id ] ) && is_wp_error( $setting_validities[ $setting_id ] ) ) { 2804 continue; 2805 } 2806 2807 $changeset_setting_id = $setting_id; 2808 if ( 'theme_mod' === $setting->type ) { 2809 $changeset_setting_id = sprintf( '%s::%s', $this->get_stylesheet(), $setting_id ); 2810 } 2811 2812 if ( null === $setting_params ) { 2813 // Remove setting from changeset entirely. 2814 unset( $data[ $changeset_setting_id ] ); 2815 } else { 2816 2817 if ( ! isset( $data[ $changeset_setting_id ] ) ) { 2818 $data[ $changeset_setting_id ] = array(); 2819 } 2820 2821 // Merge any additional setting params that have been supplied with the existing params. 2822 $merged_setting_params = array_merge( $data[ $changeset_setting_id ], $setting_params ); 2823 2824 // Skip updating setting params if unchanged (ensuring the user_id is not overwritten). 2825 if ( $data[ $changeset_setting_id ] === $merged_setting_params ) { 2826 continue; 2827 } 2828 2829 $data[ $changeset_setting_id ] = array_merge( 2830 $merged_setting_params, 2831 array( 2832 'type' => $setting->type, 2833 'user_id' => $args['user_id'], 2834 'date_modified_gmt' => current_time( 'mysql', true ), 2835 ) 2836 ); 2837 2838 // Clear starter_content flag in data if changeset is not explicitly being updated for starter content. 2839 if ( empty( $args['starter_content'] ) ) { 2840 unset( $data[ $changeset_setting_id ]['starter_content'] ); 2841 } 2842 } 2843 } 2844 2845 $filter_context = array( 2846 'uuid' => $this->changeset_uuid(), 2847 'title' => $args['title'], 2848 'status' => $args['status'], 2849 'date_gmt' => $args['date_gmt'], 2850 'post_id' => $changeset_post_id, 2851 'previous_data' => is_wp_error( $original_changeset_data ) ? array() : $original_changeset_data, 2852 'manager' => $this, 2853 ); 2854 2855 /** 2856 * Filters the settings' data that will be persisted into the changeset. 2857 * 2858 * Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter. 2859 * 2860 * @since 4.7.0 2861 * 2862 * @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata. 2863 * @param array $context { 2864 * Filter context. 2865 * 2866 * @type string $uuid Changeset UUID. 2867 * @type string $title Requested title for the changeset post. 2868 * @type string $status Requested status for the changeset post. 2869 * @type string $date_gmt Requested date for the changeset post in MySQL format and GMT timezone. 2870 * @type int|false $post_id Post ID for the changeset, or false if it doesn't exist yet. 2871 * @type array $previous_data Previous data contained in the changeset. 2872 * @type WP_Customize_Manager $manager Manager instance. 2873 * } 2874 */ 2875 $data = apply_filters( 'customize_changeset_save_data', $data, $filter_context ); 2876 2877 // Switch theme if publishing changes now. 2878 if ( 'publish' === $args['status'] && ! $this->is_theme_active() ) { 2879 // Temporarily stop previewing the theme to allow switch_themes() to operate properly. 2880 $this->stop_previewing_theme(); 2881 switch_theme( $this->get_stylesheet() ); 2882 update_option( 'theme_switched_via_customizer', true ); 2883 $this->start_previewing_theme(); 2884 } 2885 2886 // Gather the data for wp_insert_post()/wp_update_post(). 2887 $post_array = array( 2888 // JSON_UNESCAPED_SLASHES is only to improve readability as slashes needn't be escaped in storage. 2889 'post_content' => wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ), 2890 ); 2891 if ( $args['title'] ) { 2892 $post_array['post_title'] = $args['title']; 2893 } 2894 if ( $changeset_post_id ) { 2895 $post_array['ID'] = $changeset_post_id; 2896 } else { 2897 $post_array['post_type'] = 'customize_changeset'; 2898 $post_array['post_name'] = $this->changeset_uuid(); 2899 $post_array['post_status'] = 'auto-draft'; 2900 } 2901 if ( $args['status'] ) { 2902 $post_array['post_status'] = $args['status']; 2903 } 2904 2905 // Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date. 2906 if ( 'publish' === $args['status'] ) { 2907 $post_array['post_date_gmt'] = '0000-00-00 00:00:00'; 2908 $post_array['post_date'] = '0000-00-00 00:00:00'; 2909 } elseif ( $args['date_gmt'] ) { 2910 $post_array['post_date_gmt'] = $args['date_gmt']; 2911 $post_array['post_date'] = get_date_from_gmt( $args['date_gmt'] ); 2912 } elseif ( $changeset_post_id && 'auto-draft' === get_post_status( $changeset_post_id ) ) { 2913 /* 2914 * Keep bumping the date for the auto-draft whenever it is modified; 2915 * this extends its life, preserving it from garbage-collection via 2916 * wp_delete_auto_drafts(). 2917 */ 2918 $post_array['post_date'] = current_time( 'mysql' ); 2919 $post_array['post_date_gmt'] = ''; 2920 } 2921 2922 $this->store_changeset_revision = $allow_revision; 2923 add_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ), 5, 3 ); 2924 2925 /* 2926 * Update the changeset post. The publish_customize_changeset action will cause the settings in the 2927 * changeset to be saved via WP_Customize_Setting::save(). Updating a post with publish status will 2928 * trigger WP_Customize_Manager::publish_changeset_values(). 2929 */ 2930 add_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5, 3 ); 2931 if ( $changeset_post_id ) { 2932 if ( $args['autosave'] && 'auto-draft' !== get_post_status( $changeset_post_id ) ) { 2933 // See _wp_translate_postdata() for why this is required as it will use the edit_post meta capability. 2934 add_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10, 4 ); 2935 2936 $post_array['post_ID'] = $post_array['ID']; 2937 $post_array['post_type'] = 'customize_changeset'; 2938 2939 $r = wp_create_post_autosave( wp_slash( $post_array ) ); 2940 2941 remove_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10 ); 2942 } else { 2943 $post_array['edit_date'] = true; // Prevent date clearing. 2944 2945 $r = wp_update_post( wp_slash( $post_array ), true ); 2946 2947 // Delete autosave revision for user when the changeset is updated. 2948 if ( ! empty( $args['user_id'] ) ) { 2949 $autosave_draft = wp_get_post_autosave( $changeset_post_id, $args['user_id'] ); 2950 if ( $autosave_draft ) { 2951 wp_delete_post( $autosave_draft->ID, true ); 2952 } 2953 } 2954 } 2955 } else { 2956 $r = wp_insert_post( wp_slash( $post_array ), true ); 2957 if ( ! is_wp_error( $r ) ) { 2958 $this->_changeset_post_id = $r; // Update cached post ID for the loaded changeset. 2959 } 2960 } 2961 remove_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5 ); 2962 2963 $this->_changeset_data = null; // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents. 2964 2965 remove_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ) ); 2966 2967 $response = array( 2968 'setting_validities' => $setting_validities, 2969 ); 2970 2971 if ( is_wp_error( $r ) ) { 2972 $response['changeset_post_save_failure'] = $r->get_error_code(); 2973 return new WP_Error( 'changeset_post_save_failure', '', $response ); 2974 } 2975 2976 return $response; 2977 } 2978 2979 /** 2980 * Preserve the initial JSON post_content passed to save into the post. 2981 * 2982 * This is needed to prevent KSES and other {@see 'content_save_pre'} filters 2983 * from corrupting JSON data. 2984 * 2985 * Note that WP_Customize_Manager::validate_setting_values() have already 2986 * run on the setting values being serialized as JSON into the post content 2987 * so it is pre-sanitized. 2988 * 2989 * Also, the sanitization logic is re-run through the respective 2990 * WP_Customize_Setting::sanitize() method when being read out of the 2991 * changeset, via WP_Customize_Manager::post_value(), and this sanitized 2992 * value will also be sent into WP_Customize_Setting::update() for 2993 * persisting to the DB. 2994 * 2995 * Multiple users can collaborate on a single changeset, where one user may 2996 * have the unfiltered_html capability but another may not. A user with 2997 * unfiltered_html may add a script tag to some field which needs to be kept 2998 * intact even when another user updates the changeset to modify another field 2999 * when they do not have unfiltered_html. 3000 * 3001 * @since 5.4.1 3002 * 3003 * @param array $data An array of slashed and processed post data. 3004 * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data. 3005 * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as originally passed to wp_insert_post(). 3006 * @return array Filtered post data. 3007 */ 3008 public function preserve_insert_changeset_post_content( $data, $postarr, $unsanitized_postarr ) { 3009 if ( 3010 isset( $data['post_type'] ) && 3011 isset( $unsanitized_postarr['post_content'] ) && 3012 'customize_changeset' === $data['post_type'] || 3013 ( 3014 'revision' === $data['post_type'] && 3015 ! empty( $data['post_parent'] ) && 3016 'customize_changeset' === get_post_type( $data['post_parent'] ) 3017 ) 3018 ) { 3019 $data['post_content'] = $unsanitized_postarr['post_content']; 3020 } 3021 return $data; 3022 } 3023 3024 /** 3025 * Trash or delete a changeset post. 3026 * 3027 * The following re-formulates the logic from `wp_trash_post()` as done in 3028 * `wp_publish_post()`. The reason for bypassing `wp_trash_post()` is that it 3029 * will mutate the the `post_content` and the `post_name` when they should be 3030 * untouched. 3031 * 3032 * @since 4.9.0 3033 * @global wpdb $wpdb WordPress database abstraction object. 3034 * @see wp_trash_post() 3035 * 3036 * @param int|WP_Post $post The changeset post. 3037 * @return mixed A WP_Post object for the trashed post or an empty value on failure. 3038 */ 3039 public function trash_changeset_post( $post ) { 3040 global $wpdb; 3041 3042 $post = get_post( $post ); 3043 3044 if ( ! ( $post instanceof WP_Post ) ) { 3045 return $post; 3046 } 3047 $post_id = $post->ID; 3048 3049 if ( ! EMPTY_TRASH_DAYS ) { 3050 return wp_delete_post( $post_id, true ); 3051 } 3052 3053 if ( 'trash' === get_post_status( $post ) ) { 3054 return false; 3055 } 3056 3057 /** This filter is documented in wp-includes/post.php */ 3058 $check = apply_filters( 'pre_trash_post', null, $post ); 3059 if ( null !== $check ) { 3060 return $check; 3061 } 3062 3063 /** This action is documented in wp-includes/post.php */ 3064 do_action( 'wp_trash_post', $post_id ); 3065 3066 add_post_meta( $post_id, '_wp_trash_meta_status', $post->post_status ); 3067 add_post_meta( $post_id, '_wp_trash_meta_time', time() ); 3068 3069 $old_status = $post->post_status; 3070 $new_status = 'trash'; 3071 $wpdb->update( $wpdb->posts, array( 'post_status' => $new_status ), array( 'ID' => $post->ID ) ); 3072 clean_post_cache( $post->ID ); 3073 3074 $post->post_status = $new_status; 3075 wp_transition_post_status( $new_status, $old_status, $post ); 3076 3077 /** This action is documented in wp-includes/post.php */ 3078 do_action( "edit_post_{$post->post_type}", $post->ID, $post ); 3079 3080 /** This action is documented in wp-includes/post.php */ 3081 do_action( 'edit_post', $post->ID, $post ); 3082 3083 /** This action is documented in wp-includes/post.php */ 3084 do_action( "save_post_{$post->post_type}", $post->ID, $post, true ); 3085 3086 /** This action is documented in wp-includes/post.php */ 3087 do_action( 'save_post', $post->ID, $post, true ); 3088 3089 /** This action is documented in wp-includes/post.php */ 3090 do_action( 'wp_insert_post', $post->ID, $post, true ); 3091 3092 wp_trash_post_comments( $post_id ); 3093 3094 /** This action is documented in wp-includes/post.php */ 3095 do_action( 'trashed_post', $post_id ); 3096 3097 return $post; 3098 } 3099 3100 /** 3101 * Handle request to trash a changeset. 3102 * 3103 * @since 4.9.0 3104 */ 3105 public function handle_changeset_trash_request() { 3106 if ( ! is_user_logged_in() ) { 3107 wp_send_json_error( 'unauthenticated' ); 3108 } 3109 3110 if ( ! $this->is_preview() ) { 3111 wp_send_json_error( 'not_preview' ); 3112 } 3113 3114 if ( ! check_ajax_referer( 'trash_customize_changeset', 'nonce', false ) ) { 3115 wp_send_json_error( 3116 array( 3117 'code' => 'invalid_nonce', 3118 'message' => __( 'There was an authentication problem. Please reload and try again.' ), 3119 ) 3120 ); 3121 } 3122 3123 $changeset_post_id = $this->changeset_post_id(); 3124 3125 if ( ! $changeset_post_id ) { 3126 wp_send_json_error( 3127 array( 3128 'message' => __( 'No changes saved yet, so there is nothing to trash.' ), 3129 'code' => 'non_existent_changeset', 3130 ) 3131 ); 3132 return; 3133 } 3134 3135 if ( $changeset_post_id && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) { 3136 wp_send_json_error( 3137 array( 3138 'code' => 'changeset_trash_unauthorized', 3139 'message' => __( 'Unable to trash changes.' ), 3140 ) 3141 ); 3142 } 3143 3144 if ( 'trash' === get_post_status( $changeset_post_id ) ) { 3145 wp_send_json_error( 3146 array( 3147 'message' => __( 'Changes have already been trashed.' ), 3148 'code' => 'changeset_already_trashed', 3149 ) 3150 ); 3151 return; 3152 } 3153 3154 $r = $this->trash_changeset_post( $changeset_post_id ); 3155 if ( ! ( $r instanceof WP_Post ) ) { 3156 wp_send_json_error( 3157 array( 3158 'code' => 'changeset_trash_failure', 3159 'message' => __( 'Unable to trash changes.' ), 3160 ) 3161 ); 3162 } 3163 3164 wp_send_json_success( 3165 array( 3166 'message' => __( 'Changes trashed successfully.' ), 3167 ) 3168 ); 3169 } 3170 3171 /** 3172 * Re-map 'edit_post' meta cap for a customize_changeset post to be the same as 'customize' maps. 3173 * 3174 * There is essentially a "meta meta" cap in play here, where 'edit_post' meta cap maps to 3175 * the 'customize' meta cap which then maps to 'edit_theme_options'. This is currently 3176 * required in core for `wp_create_post_autosave()` because it will call 3177 * `_wp_translate_postdata()` which in turn will check if a user can 'edit_post', but the 3178 * the caps for the customize_changeset post type are all mapping to the meta capability. 3179 * This should be able to be removed once #40922 is addressed in core. 3180 * 3181 * @since 4.9.0 3182 * @link https://core.trac.wordpress.org/ticket/40922 3183 * @see WP_Customize_Manager::save_changeset_post() 3184 * @see _wp_translate_postdata() 3185 * 3186 * @param string[] $caps Array of the user's capabilities. 3187 * @param string $cap Capability name. 3188 * @param int $user_id The user ID. 3189 * @param array $args Adds the context to the cap. Typically the object ID. 3190 * @return array Capabilities. 3191 */ 3192 public function grant_edit_post_capability_for_changeset( $caps, $cap, $user_id, $args ) { 3193 if ( 'edit_post' === $cap && ! empty( $args[0] ) && 'customize_changeset' === get_post_type( $args[0] ) ) { 3194 $post_type_obj = get_post_type_object( 'customize_changeset' ); 3195 $caps = map_meta_cap( $post_type_obj->cap->$cap, $user_id ); 3196 } 3197 return $caps; 3198 } 3199 3200 /** 3201 * Marks the changeset post as being currently edited by the current user. 3202 * 3203 * @since 4.9.0 3204 * 3205 * @param int $changeset_post_id Changeset post id. 3206 * @param bool $take_over Take over the changeset, default is false. 3207 */ 3208 public function set_changeset_lock( $changeset_post_id, $take_over = false ) { 3209 if ( $changeset_post_id ) { 3210 $can_override = ! (bool) get_post_meta( $changeset_post_id, '_edit_lock', true ); 3211 3212 if ( $take_over ) { 3213 $can_override = true; 3214 } 3215 3216 if ( $can_override ) { 3217 $lock = sprintf( '%s:%s', time(), get_current_user_id() ); 3218 update_post_meta( $changeset_post_id, '_edit_lock', $lock ); 3219 } else { 3220 $this->refresh_changeset_lock( $changeset_post_id ); 3221 } 3222 } 3223 } 3224 3225 /** 3226 * Refreshes changeset lock with the current time if current user edited the changeset before. 3227 * 3228 * @since 4.9.0 3229 * 3230 * @param int $changeset_post_id Changeset post id. 3231 */ 3232 public function refresh_changeset_lock( $changeset_post_id ) { 3233 if ( ! $changeset_post_id ) { 3234 return; 3235 } 3236 $lock = get_post_meta( $changeset_post_id, '_edit_lock', true ); 3237 $lock = explode( ':', $lock ); 3238 3239 if ( $lock && ! empty( $lock[1] ) ) { 3240 $user_id = intval( $lock[1] ); 3241 $current_user_id = get_current_user_id(); 3242 if ( $user_id === $current_user_id ) { 3243 $lock = sprintf( '%s:%s', time(), $user_id ); 3244 update_post_meta( $changeset_post_id, '_edit_lock', $lock ); 3245 } 3246 } 3247 } 3248 3249 /** 3250 * Filter heartbeat settings for the Customizer. 3251 * 3252 * @since 4.9.0 3253 * @param array $settings Current settings to filter. 3254 * @return array Heartbeat settings. 3255 */ 3256 public function add_customize_screen_to_heartbeat_settings( $settings ) { 3257 global $pagenow; 3258 if ( 'customize.php' === $pagenow ) { 3259 $settings['screenId'] = 'customize'; 3260 } 3261 return $settings; 3262 } 3263 3264 /** 3265 * Get lock user data. 3266 * 3267 * @since 4.9.0 3268 * 3269 * @param int $user_id User ID. 3270 * @return array|null User data formatted for client. 3271 */ 3272 protected function get_lock_user_data( $user_id ) { 3273 if ( ! $user_id ) { 3274 return null; 3275 } 3276 $lock_user = get_userdata( $user_id ); 3277 if ( ! $lock_user ) { 3278 return null; 3279 } 3280 return array( 3281 'id' => $lock_user->ID, 3282 'name' => $lock_user->display_name, 3283 'avatar' => get_avatar_url( $lock_user->ID, array( 'size' => 128 ) ), 3284 ); 3285 } 3286 3287 /** 3288 * Check locked changeset with heartbeat API. 3289 * 3290 * @since 4.9.0 3291 * 3292 * @param array $response The Heartbeat response. 3293 * @param array $data The $_POST data sent. 3294 * @param string $screen_id The screen id. 3295 * @return array The Heartbeat response. 3296 */ 3297 public function check_changeset_lock_with_heartbeat( $response, $data, $screen_id ) { 3298 if ( isset( $data['changeset_uuid'] ) ) { 3299 $changeset_post_id = $this->find_changeset_post_id( $data['changeset_uuid'] ); 3300 } else { 3301 $changeset_post_id = $this->changeset_post_id(); 3302 } 3303 3304 if ( 3305 array_key_exists( 'check_changeset_lock', $data ) 3306 && 'customize' === $screen_id 3307 && $changeset_post_id 3308 && current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) 3309 ) { 3310 $lock_user_id = wp_check_post_lock( $changeset_post_id ); 3311 3312 if ( $lock_user_id ) { 3313 $response['customize_changeset_lock_user'] = $this->get_lock_user_data( $lock_user_id ); 3314 } else { 3315 3316 // Refreshing time will ensure that the user is sitting on customizer and has not closed the customizer tab. 3317 $this->refresh_changeset_lock( $changeset_post_id ); 3318 } 3319 } 3320 3321 return $response; 3322 } 3323 3324 /** 3325 * Removes changeset lock when take over request is sent via Ajax. 3326 * 3327 * @since 4.9.0 3328 */ 3329 public function handle_override_changeset_lock_request() { 3330 if ( ! $this->is_preview() ) { 3331 wp_send_json_error( 'not_preview', 400 ); 3332 } 3333 3334 if ( ! check_ajax_referer( 'customize_override_changeset_lock', 'nonce', false ) ) { 3335 wp_send_json_error( 3336 array( 3337 'code' => 'invalid_nonce', 3338 'message' => __( 'Security check failed.' ), 3339 ) 3340 ); 3341 } 3342 3343 $changeset_post_id = $this->changeset_post_id(); 3344 3345 if ( empty( $changeset_post_id ) ) { 3346 wp_send_json_error( 3347 array( 3348 'code' => 'no_changeset_found_to_take_over', 3349 'message' => __( 'No changeset found to take over' ), 3350 ) 3351 ); 3352 } 3353 3354 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { 3355 wp_send_json_error( 3356 array( 3357 'code' => 'cannot_remove_changeset_lock', 3358 'message' => __( 'Sorry, you are not allowed to take over.' ), 3359 ) 3360 ); 3361 } 3362 3363 $this->set_changeset_lock( $changeset_post_id, true ); 3364 3365 wp_send_json_success( 'changeset_taken_over' ); 3366 } 3367 3368 /** 3369 * Whether a changeset revision should be made. 3370 * 3371 * @since 4.7.0 3372 * @var bool 3373 */ 3374 protected $store_changeset_revision; 3375 3376 /** 3377 * Filters whether a changeset has changed to create a new revision. 3378 * 3379 * Note that this will not be called while a changeset post remains in auto-draft status. 3380 * 3381 * @since 4.7.0 3382 * 3383 * @param bool $post_has_changed Whether the post has changed. 3384 * @param WP_Post $last_revision The last revision post object. 3385 * @param WP_Post $post The post object. 3386 * @return bool Whether a revision should be made. 3387 */ 3388 public function _filter_revision_post_has_changed( $post_has_changed, $last_revision, $post ) { 3389 unset( $last_revision ); 3390 if ( 'customize_changeset' === $post->post_type ) { 3391 $post_has_changed = $this->store_changeset_revision; 3392 } 3393 return $post_has_changed; 3394 } 3395 3396 /** 3397 * Publish changeset values. 3398 * 3399 * This will the values contained in a changeset, even changesets that do not 3400 * correspond to current manager instance. This is called by 3401 * `_wp_customize_publish_changeset()` when a customize_changeset post is 3402 * transitioned to the `publish` status. As such, this method should not be 3403 * called directly and instead `wp_publish_post()` should be used. 3404 * 3405 * Please note that if the settings in the changeset are for a non-activated 3406 * theme, the theme must first be switched to (via `switch_theme()`) before 3407 * invoking this method. 3408 * 3409 * @since 4.7.0 3410 * @see _wp_customize_publish_changeset() 3411 * @global wpdb $wpdb WordPress database abstraction object. 3412 * 3413 * @param int $changeset_post_id ID for customize_changeset post. Defaults to the changeset for the current manager instance. 3414 * @return true|WP_Error True or error info. 3415 */ 3416 public function _publish_changeset_values( $changeset_post_id ) { 3417 global $wpdb; 3418 3419 $publishing_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); 3420 if ( is_wp_error( $publishing_changeset_data ) ) { 3421 return $publishing_changeset_data; 3422 } 3423 3424 $changeset_post = get_post( $changeset_post_id ); 3425 3426 /* 3427 * Temporarily override the changeset context so that it will be read 3428 * in calls to unsanitized_post_values() and so that it will be available 3429 * on the $wp_customize object passed to hooks during the save logic. 3430 */ 3431 $previous_changeset_post_id = $this->_changeset_post_id; 3432 $this->_changeset_post_id = $changeset_post_id; 3433 $previous_changeset_uuid = $this->_changeset_uuid; 3434 $this->_changeset_uuid = $changeset_post->post_name; 3435 $previous_changeset_data = $this->_changeset_data; 3436 $this->_changeset_data = $publishing_changeset_data; 3437 3438 // Parse changeset data to identify theme mod settings and user IDs associated with settings to be saved. 3439 $setting_user_ids = array(); 3440 $theme_mod_settings = array(); 3441 $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/'; 3442 $matches = array(); 3443 foreach ( $this->_changeset_data as $raw_setting_id => $setting_params ) { 3444 $actual_setting_id = null; 3445 $is_theme_mod_setting = ( 3446 isset( $setting_params['value'] ) 3447 && 3448 isset( $setting_params['type'] ) 3449 && 3450 'theme_mod' === $setting_params['type'] 3451 && 3452 preg_match( $namespace_pattern, $raw_setting_id, $matches ) 3453 ); 3454 if ( $is_theme_mod_setting ) { 3455 if ( ! isset( $theme_mod_settings[ $matches['stylesheet'] ] ) ) { 3456 $theme_mod_settings[ $matches['stylesheet'] ] = array(); 3457 } 3458 $theme_mod_settings[ $matches['stylesheet'] ][ $matches['setting_id'] ] = $setting_params; 3459 3460 if ( $this->get_stylesheet() === $matches['stylesheet'] ) { 3461 $actual_setting_id = $matches['setting_id']; 3462 } 3463 } else { 3464 $actual_setting_id = $raw_setting_id; 3465 } 3466 3467 // Keep track of the user IDs for settings actually for this theme. 3468 if ( $actual_setting_id && isset( $setting_params['user_id'] ) ) { 3469 $setting_user_ids[ $actual_setting_id ] = $setting_params['user_id']; 3470 } 3471 } 3472 3473 $changeset_setting_values = $this->unsanitized_post_values( 3474 array( 3475 'exclude_post_data' => true, 3476 'exclude_changeset' => false, 3477 ) 3478 ); 3479 $changeset_setting_ids = array_keys( $changeset_setting_values ); 3480 $this->add_dynamic_settings( $changeset_setting_ids ); 3481 3482 /** 3483 * Fires once the theme has switched in the Customizer, but before settings 3484 * have been saved. 3485 * 3486 * @since 3.4.0 3487 * 3488 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 3489 */ 3490 do_action( 'customize_save', $this ); 3491 3492 /* 3493 * Ensure that all settings will allow themselves to be saved. Note that 3494 * this is safe because the setting would have checked the capability 3495 * when the setting value was written into the changeset. So this is why 3496 * an additional capability check is not required here. 3497 */ 3498 $original_setting_capabilities = array(); 3499 foreach ( $changeset_setting_ids as $setting_id ) { 3500 $setting = $this->get_setting( $setting_id ); 3501 if ( $setting && ! isset( $setting_user_ids[ $setting_id ] ) ) { 3502 $original_setting_capabilities[ $setting->id ] = $setting->capability; 3503 $setting->capability = 'exist'; 3504 } 3505 } 3506 3507 $original_user_id = get_current_user_id(); 3508 foreach ( $changeset_setting_ids as $setting_id ) { 3509 $setting = $this->get_setting( $setting_id ); 3510 if ( $setting ) { 3511 /* 3512 * Set the current user to match the user who saved the value into 3513 * the changeset so that any filters that apply during the save 3514 * process will respect the original user's capabilities. This 3515 * will ensure, for example, that KSES won't strip unsafe HTML 3516 * when a scheduled changeset publishes via WP Cron. 3517 */ 3518 if ( isset( $setting_user_ids[ $setting_id ] ) ) { 3519 wp_set_current_user( $setting_user_ids[ $setting_id ] ); 3520 } else { 3521 wp_set_current_user( $original_user_id ); 3522 } 3523 3524 $setting->save(); 3525 } 3526 } 3527 wp_set_current_user( $original_user_id ); 3528 3529 // Update the stashed theme mod settings, removing the active theme's stashed settings, if activated. 3530 if ( did_action( 'switch_theme' ) ) { 3531 $other_theme_mod_settings = $theme_mod_settings; 3532 unset( $other_theme_mod_settings[ $this->get_stylesheet() ] ); 3533 $this->update_stashed_theme_mod_settings( $other_theme_mod_settings ); 3534 } 3535 3536 /** 3537 * Fires after Customize settings have been saved. 3538 * 3539 * @since 3.6.0 3540 * 3541 * @param WP_Customize_Manager $manager WP_Customize_Manager instance. 3542 */ 3543 do_action( 'customize_save_after', $this ); 3544 3545 // Restore original capabilities. 3546 foreach ( $original_setting_capabilities as $setting_id => $capability ) { 3547 $setting = $this->get_setting( $setting_id ); 3548 if ( $setting ) { 3549 $setting->capability = $capability; 3550 } 3551 } 3552 3553 // Restore original changeset data. 3554 $this->_changeset_data = $previous_changeset_data; 3555 $this->_changeset_post_id = $previous_changeset_post_id; 3556 $this->_changeset_uuid = $previous_changeset_uuid; 3557 3558 /* 3559 * Convert all autosave revisions into their own auto-drafts so that users can be prompted to 3560 * restore them when a changeset is published, but they had been locked out from including 3561 * their changes in the changeset. 3562 */ 3563 $revisions = wp_get_post_revisions( $changeset_post_id, array( 'check_enabled' => false ) ); 3564 foreach ( $revisions as $revision ) { 3565 if ( false !== strpos( $revision->post_name, "{$changeset_post_id}-autosave" ) ) { 3566 $wpdb->update( 3567 $wpdb->posts, 3568 array( 3569 'post_status' => 'auto-draft', 3570 'post_type' => 'customize_changeset', 3571 'post_name' => wp_generate_uuid4(), 3572 'post_parent' => 0, 3573 ), 3574 array( 3575 'ID' => $revision->ID, 3576 ) 3577 ); 3578 clean_post_cache( $revision->ID ); 3579 } 3580 } 3581 3582 return true; 3583 } 3584 3585 /** 3586 * Update stashed theme mod settings. 3587 * 3588 * @since 4.7.0 3589 * 3590 * @param array $inactive_theme_mod_settings Mapping of stylesheet to arrays of theme mod settings. 3591 * @return array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes. 3592 */ 3593 protected function update_stashed_theme_mod_settings( $inactive_theme_mod_settings ) { 3594 $stashed_theme_mod_settings = get_option( 'customize_stashed_theme_mods' ); 3595 if ( empty( $stashed_theme_mod_settings ) ) { 3596 $stashed_theme_mod_settings = array(); 3597 } 3598 3599 // Delete any stashed theme mods for the active theme since they would have been loaded and saved upon activation. 3600 unset( $stashed_theme_mod_settings[ $this->get_stylesheet() ] ); 3601 3602 // Merge inactive theme mods with the stashed theme mod settings. 3603 foreach ( $inactive_theme_mod_settings as $stylesheet => $theme_mod_settings ) { 3604 if ( ! isset( $stashed_theme_mod_settings[ $stylesheet ] ) ) { 3605 $stashed_theme_mod_settings[ $stylesheet ] = array(); 3606 } 3607 3608 $stashed_theme_mod_settings[ $stylesheet ] = array_merge( 3609 $stashed_theme_mod_settings[ $stylesheet ], 3610 $theme_mod_settings 3611 ); 3612 } 3613 3614 $autoload = false; 3615 $result = update_option( 'customize_stashed_theme_mods', $stashed_theme_mod_settings, $autoload ); 3616 if ( ! $result ) { 3617 return false; 3618 } 3619 return $stashed_theme_mod_settings; 3620 } 3621 3622 /** 3623 * Refresh nonces for the current preview. 3624 * 3625 * @since 4.2.0 3626 */ 3627 public function refresh_nonces() { 3628 if ( ! $this->is_preview() ) { 3629 wp_send_json_error( 'not_preview' ); 3630 } 3631 3632 wp_send_json_success( $this->get_nonces() ); 3633 } 3634 3635 /** 3636 * Delete a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. 3637 * 3638 * @since 4.9.0 3639 */ 3640 public function handle_dismiss_autosave_or_lock_request() { 3641 // Calls to dismiss_user_auto_draft_changesets() and wp_get_post_autosave() require non-zero get_current_user_id(). 3642 if ( ! is_user_logged_in() ) { 3643 wp_send_json_error( 'unauthenticated', 401 ); 3644 } 3645 3646 if ( ! $this->is_preview() ) { 3647 wp_send_json_error( 'not_preview', 400 ); 3648 } 3649 3650 if ( ! check_ajax_referer( 'customize_dismiss_autosave_or_lock', 'nonce', false ) ) { 3651 wp_send_json_error( 'invalid_nonce', 403 ); 3652 } 3653 3654 $changeset_post_id = $this->changeset_post_id(); 3655 $dismiss_lock = ! empty( $_POST['dismiss_lock'] ); 3656 $dismiss_autosave = ! empty( $_POST['dismiss_autosave'] ); 3657 3658 if ( $dismiss_lock ) { 3659 if ( empty( $changeset_post_id ) && ! $dismiss_autosave ) { 3660 wp_send_json_error( 'no_changeset_to_dismiss_lock', 404 ); 3661 } 3662 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) && ! $dismiss_autosave ) { 3663 wp_send_json_error( 'cannot_remove_changeset_lock', 403 ); 3664 } 3665 3666 delete_post_meta( $changeset_post_id, '_edit_lock' ); 3667 3668 if ( ! $dismiss_autosave ) { 3669 wp_send_json_success( 'changeset_lock_dismissed' ); 3670 } 3671 } 3672 3673 if ( $dismiss_autosave ) { 3674 if ( empty( $changeset_post_id ) || 'auto-draft' === get_post_status( $changeset_post_id ) ) { 3675 $dismissed = $this->dismiss_user_auto_draft_changesets(); 3676 if ( $dismissed > 0 ) { 3677 wp_send_json_success( 'auto_draft_dismissed' ); 3678 } else { 3679 wp_send_json_error( 'no_auto_draft_to_delete', 404 ); 3680 } 3681 } else { 3682 $revision = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); 3683 3684 if ( $revision ) { 3685 if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) { 3686 wp_send_json_error( 'cannot_delete_autosave_revision', 403 ); 3687 } 3688 3689 if ( ! wp_delete_post( $revision->ID, true ) ) { 3690 wp_send_json_error( 'autosave_revision_deletion_failure', 500 ); 3691 } else { 3692 wp_send_json_success( 'autosave_revision_deleted' ); 3693 } 3694 } else { 3695 wp_send_json_error( 'no_autosave_revision_to_delete', 404 ); 3696 } 3697 } 3698 } 3699 3700 wp_send_json_error( 'unknown_error', 500 ); 3701 } 3702 3703 /** 3704 * Add a customize setting. 3705 * 3706 * @since 3.4.0 3707 * @since 4.5.0 Return added WP_Customize_Setting instance. 3708 * 3709 * @see WP_Customize_Setting::__construct() 3710 * @link https://developer.wordpress.org/themes/customize-api 3711 * 3712 * @param WP_Customize_Setting|string $id Customize Setting object, or ID. 3713 * @param array $args Optional. Array of properties for the new Setting object. 3714 * See WP_Customize_Setting::__construct() for information 3715 * on accepted arguments. Default empty array. 3716 * @return WP_Customize_Setting The instance of the setting that was added. 3717 */ 3718 public function add_setting( $id, $args = array() ) { 3719 if ( $id instanceof WP_Customize_Setting ) { 3720 $setting = $id; 3721 } else { 3722 $class = 'WP_Customize_Setting'; 3723 3724 /** This filter is documented in wp-includes/class-wp-customize-manager.php */ 3725 $args = apply_filters( 'customize_dynamic_setting_args', $args, $id ); 3726 3727 /** This filter is documented in wp-includes/class-wp-customize-manager.php */ 3728 $class = apply_filters( 'customize_dynamic_setting_class', $class, $id, $args ); 3729 3730 $setting = new $class( $this, $id, $args ); 3731 } 3732 3733 $this->settings[ $setting->id ] = $setting; 3734 return $setting; 3735 } 3736 3737 /** 3738 * Register any dynamically-created settings, such as those from $_POST['customized'] 3739 * that have no corresponding setting created. 3740 * 3741 * This is a mechanism to "wake up" settings that have been dynamically created 3742 * on the front end and have been sent to WordPress in `$_POST['customized']`. When WP 3743 * loads, the dynamically-created settings then will get created and previewed 3744 * even though they are not directly created statically with code. 3745 * 3746 * @since 4.2.0 3747 * 3748 * @param array $setting_ids The setting IDs to add. 3749 * @return array The WP_Customize_Setting objects added. 3750 */ 3751 public function add_dynamic_settings( $setting_ids ) { 3752 $new_settings = array(); 3753 foreach ( $setting_ids as $setting_id ) { 3754 // Skip settings already created. 3755 if ( $this->get_setting( $setting_id ) ) { 3756 continue; 3757 } 3758 3759 $setting_args = false; 3760 $setting_class = 'WP_Customize_Setting'; 3761 3762 /** 3763 * Filters a dynamic setting's constructor args. 3764 * 3765 * For a dynamic setting to be registered, this filter must be employed 3766 * to override the default false value with an array of args to pass to 3767 * the WP_Customize_Setting constructor. 3768 * 3769 * @since 4.2.0 3770 * 3771 * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor. 3772 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. 3773 */ 3774 $setting_args = apply_filters( 'customize_dynamic_setting_args', $setting_args, $setting_id ); 3775 if ( false === $setting_args ) { 3776 continue; 3777 } 3778 3779 /** 3780 * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass. 3781 * 3782 * @since 4.2.0 3783 * 3784 * @param string $setting_class WP_Customize_Setting or a subclass. 3785 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. 3786 * @param array $setting_args WP_Customize_Setting or a subclass. 3787 */ 3788 $setting_class = apply_filters( 'customize_dynamic_setting_class', $setting_class, $setting_id, $setting_args ); 3789 3790 $setting = new $setting_class( $this, $setting_id, $setting_args ); 3791 3792 $this->add_setting( $setting ); 3793 $new_settings[] = $setting; 3794 } 3795 return $new_settings; 3796 } 3797 3798 /** 3799 * Retrieve a customize setting. 3800 * 3801 * @since 3.4.0 3802 * 3803 * @param string $id Customize Setting ID. 3804 * @return WP_Customize_Setting|void The setting, if set. 3805 */ 3806 public function get_setting( $id ) { 3807 if ( isset( $this->settings[ $id ] ) ) { 3808 return $this->settings[ $id ]; 3809 } 3810 } 3811 3812 /** 3813 * Remove a customize setting. 3814 * 3815 * Note that removing the setting doesn't destroy the WP_Customize_Setting instance or remove its filters. 3816 * 3817 * @since 3.4.0 3818 * 3819 * @param string $id Customize Setting ID. 3820 */ 3821 public function remove_setting( $id ) { 3822 unset( $this->settings[ $id ] ); 3823 } 3824 3825 /** 3826 * Add a customize panel. 3827 * 3828 * @since 4.0.0 3829 * @since 4.5.0 Return added WP_Customize_Panel instance. 3830 * 3831 * @see WP_Customize_Panel::__construct() 3832 * 3833 * @param WP_Customize_Panel|string $id Customize Panel object, or ID. 3834 * @param array $args Optional. Array of properties for the new Panel object. 3835 * See WP_Customize_Panel::__construct() for information 3836 * on accepted arguments. Default empty array. 3837 * @return WP_Customize_Panel The instance of the panel that was added. 3838 */ 3839 public function add_panel( $id, $args = array() ) { 3840 if ( $id instanceof WP_Customize_Panel ) { 3841 $panel = $id; 3842 } else { 3843 $panel = new WP_Customize_Panel( $this, $id, $args ); 3844 } 3845 3846 $this->panels[ $panel->id ] = $panel; 3847 return $panel; 3848 } 3849 3850 /** 3851 * Retrieve a customize panel. 3852 * 3853 * @since 4.0.0 3854 * 3855 * @param string $id Panel ID to get. 3856 * @return WP_Customize_Panel|void Requested panel instance, if set. 3857 */ 3858 public function get_panel( $id ) { 3859 if ( isset( $this->panels[ $id ] ) ) { 3860 return $this->panels[ $id ]; 3861 } 3862 } 3863 3864 /** 3865 * Remove a customize panel. 3866 * 3867 * Note that removing the panel doesn't destroy the WP_Customize_Panel instance or remove its filters. 3868 * 3869 * @since 4.0.0 3870 * 3871 * @param string $id Panel ID to remove. 3872 */ 3873 public function remove_panel( $id ) { 3874 // Removing core components this way is _doing_it_wrong(). 3875 if ( in_array( $id, $this->components, true ) ) { 3876 $message = sprintf( 3877 /* translators: 1: Panel ID, 2: Link to 'customize_loaded_components' filter reference. */ 3878 __( 'Removing %1$s manually will cause PHP warnings. Use the %2$s filter instead.' ), 3879 $id, 3880 '<a href="' . esc_url( 'https://developer.wordpress.org/reference/hooks/customize_loaded_components/' ) . '"><code>customize_loaded_components</code></a>' 3881 ); 3882 3883 _doing_it_wrong( __METHOD__, $message, '4.5.0' ); 3884 } 3885 unset( $this->panels[ $id ] ); 3886 } 3887 3888 /** 3889 * Register a customize panel type. 3890 * 3891 * Registered types are eligible to be rendered via JS and created dynamically. 3892 * 3893 * @since 4.3.0 3894 * 3895 * @see WP_Customize_Panel 3896 * 3897 * @param string $panel Name of a custom panel which is a subclass of WP_Customize_Panel. 3898 */ 3899 public function register_panel_type( $panel ) { 3900 $this->registered_panel_types[] = $panel; 3901 } 3902 3903 /** 3904 * Render JS templates for all registered panel types. 3905 * 3906 * @since 4.3.0 3907 */ 3908 public function render_panel_templates() { 3909 foreach ( $this->registered_panel_types as $panel_type ) { 3910 $panel = new $panel_type( $this, 'temp', array() ); 3911 $panel->print_template(); 3912 } 3913 } 3914 3915 /** 3916 * Add a customize section. 3917 * 3918 * @since 3.4.0 3919 * @since 4.5.0 Return added WP_Customize_Section instance. 3920 * 3921 * @see WP_Customize_Section::__construct() 3922 * 3923 * @param WP_Customize_Section|string $id Customize Section object, or ID. 3924 * @param array $args Optional. Array of properties for the new Section object. 3925 * See WP_Customize_Section::__construct() for information 3926 * on accepted arguments. Default empty array. 3927 * @return WP_Customize_Section The instance of the section that was added. 3928 */ 3929 public function add_section( $id, $args = array() ) { 3930 if ( $id instanceof WP_Customize_Section ) { 3931 $section = $id; 3932 } else { 3933 $section = new WP_Customize_Section( $this, $id, $args ); 3934 } 3935 3936 $this->sections[ $section->id ] = $section; 3937 return $section; 3938 } 3939 3940 /** 3941 * Retrieve a customize section. 3942 * 3943 * @since 3.4.0 3944 * 3945 * @param string $id Section ID. 3946 * @return WP_Customize_Section|void The section, if set. 3947 */ 3948 public function get_section( $id ) { 3949 if ( isset( $this->sections[ $id ] ) ) { 3950 return $this->sections[ $id ]; 3951 } 3952 } 3953 3954 /** 3955 * Remove a customize section. 3956 * 3957 * Note that removing the section doesn't destroy the WP_Customize_Section instance or remove its filters. 3958 * 3959 * @since 3.4.0 3960 * 3961 * @param string $id Section ID. 3962 */ 3963 public function remove_section( $id ) { 3964 unset( $this->sections[ $id ] ); 3965 } 3966 3967 /** 3968 * Register a customize section type. 3969 * 3970 * Registered types are eligible to be rendered via JS and created dynamically. 3971 * 3972 * @since 4.3.0 3973 * 3974 * @see WP_Customize_Section 3975 * 3976 * @param string $section Name of a custom section which is a subclass of WP_Customize_Section. 3977 */ 3978 public function register_section_type( $section ) { 3979 $this->registered_section_types[] = $section; 3980 } 3981 3982 /** 3983 * Render JS templates for all registered section types. 3984 * 3985 * @since 4.3.0 3986 */ 3987 public function render_section_templates() { 3988 foreach ( $this->registered_section_types as $section_type ) { 3989 $section = new $section_type( $this, 'temp', array() ); 3990 $section->print_template(); 3991 } 3992 } 3993 3994 /** 3995 * Add a customize control. 3996 * 3997 * @since 3.4.0 3998 * @since 4.5.0 Return added WP_Customize_Control instance. 3999 * 4000 * @see WP_Customize_Control::__construct() 4001 * 4002 * @param WP_Customize_Control|string $id Customize Control object, or ID. 4003 * @param array $args Optional. Array of properties for the new Control object. 4004 * See WP_Customize_Control::__construct() for information 4005 * on accepted arguments. Default empty array. 4006 * @return WP_Customize_Control The instance of the control that was added. 4007 */ 4008 public function add_control( $id, $args = array() ) { 4009 if ( $id instanceof WP_Customize_Control ) { 4010 $control = $id; 4011 } else { 4012 $control = new WP_Customize_Control( $this, $id, $args ); 4013 } 4014 4015 $this->controls[ $control->id ] = $control; 4016 return $control; 4017 } 4018 4019 /** 4020 * Retrieve a customize control. 4021 * 4022 * @since 3.4.0 4023 * 4024 * @param string $id ID of the control. 4025 * @return WP_Customize_Control|void The control object, if set. 4026 */ 4027 public function get_control( $id ) { 4028 if ( isset( $this->controls[ $id ] ) ) { 4029 return $this->controls[ $id ]; 4030 } 4031 } 4032 4033 /** 4034 * Remove a customize control. 4035 * 4036 * Note that removing the control doesn't destroy the WP_Customize_Control instance or remove its filters. 4037 * 4038 * @since 3.4.0 4039 * 4040 * @param string $id ID of the control. 4041 */ 4042 public function remove_control( $id ) { 4043 unset( $this->controls[ $id ] ); 4044 } 4045 4046 /** 4047 * Register a customize control type. 4048 * 4049 * Registered types are eligible to be rendered via JS and created dynamically. 4050 * 4051 * @since 4.1.0 4052 * 4053 * @param string $control Name of a custom control which is a subclass of 4054 * WP_Customize_Control. 4055 */ 4056 public function register_control_type( $control ) { 4057 $this->registered_control_types[] = $control; 4058 } 4059 4060 /** 4061 * Render JS templates for all registered control types. 4062 * 4063 * @since 4.1.0 4064 */ 4065 public function render_control_templates() { 4066 if ( $this->branching() ) { 4067 $l10n = array( 4068 /* translators: %s: User who is customizing the changeset in customizer. */ 4069 'locked' => __( '%s is already customizing this changeset. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ), 4070 /* translators: %s: User who is customizing the changeset in customizer. */ 4071 'locked_allow_override' => __( '%s is already customizing this changeset. Do you want to take over?' ), 4072 ); 4073 } else { 4074 $l10n = array( 4075 /* translators: %s: User who is customizing the changeset in customizer. */ 4076 'locked' => __( '%s is already customizing this site. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ), 4077 /* translators: %s: User who is customizing the changeset in customizer. */ 4078 'locked_allow_override' => __( '%s is already customizing this site. Do you want to take over?' ), 4079 ); 4080 } 4081 4082 foreach ( $this->registered_control_types as $control_type ) { 4083 $control = new $control_type( 4084 $this, 4085 'temp', 4086 array( 4087 'settings' => array(), 4088 ) 4089 ); 4090 $control->print_template(); 4091 } 4092 ?> 4093 4094 <script type="text/html" id="tmpl-customize-control-default-content"> 4095 <# 4096 var inputId = _.uniqueId( 'customize-control-default-input-' ); 4097 var descriptionId = _.uniqueId( 'customize-control-default-description-' ); 4098 var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : ''; 4099 #> 4100 <# switch ( data.type ) { 4101 case 'checkbox': #> 4102 <span class="customize-inside-control-row"> 4103 <input 4104 id="{{ inputId }}" 4105 {{{ describedByAttr }}} 4106 type="checkbox" 4107 value="{{ data.value }}" 4108 data-customize-setting-key-link="default" 4109 > 4110 <label for="{{ inputId }}"> 4111 {{ data.label }} 4112 </label> 4113 <# if ( data.description ) { #> 4114 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4115 <# } #> 4116 </span> 4117 <# 4118 break; 4119 case 'radio': 4120 if ( ! data.choices ) { 4121 return; 4122 } 4123 #> 4124 <# if ( data.label ) { #> 4125 <label for="{{ inputId }}" class="customize-control-title"> 4126 {{ data.label }} 4127 </label> 4128 <# } #> 4129 <# if ( data.description ) { #> 4130 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4131 <# } #> 4132 <# _.each( data.choices, function( val, key ) { #> 4133 <span class="customize-inside-control-row"> 4134 <# 4135 var value, text; 4136 if ( _.isObject( val ) ) { 4137 value = val.value; 4138 text = val.text; 4139 } else { 4140 value = key; 4141 text = val; 4142 } 4143 #> 4144 <input 4145 id="{{ inputId + '-' + value }}" 4146 type="radio" 4147 value="{{ value }}" 4148 name="{{ inputId }}" 4149 data-customize-setting-key-link="default" 4150 {{{ describedByAttr }}} 4151 > 4152 <label for="{{ inputId + '-' + value }}">{{ text }}</label> 4153 </span> 4154 <# } ); #> 4155 <# 4156 break; 4157 default: 4158 #> 4159 <# if ( data.label ) { #> 4160 <label for="{{ inputId }}" class="customize-control-title"> 4161 {{ data.label }} 4162 </label> 4163 <# } #> 4164 <# if ( data.description ) { #> 4165 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4166 <# } #> 4167 4168 <# 4169 var inputAttrs = { 4170 id: inputId, 4171 'data-customize-setting-key-link': 'default' 4172 }; 4173 if ( 'textarea' === data.type ) { 4174 inputAttrs.rows = '5'; 4175 } else if ( 'button' === data.type ) { 4176 inputAttrs['class'] = 'button button-secondary'; 4177 inputAttrs.type = 'button'; 4178 } else { 4179 inputAttrs.type = data.type; 4180 } 4181 if ( data.description ) { 4182 inputAttrs['aria-describedby'] = descriptionId; 4183 } 4184 _.extend( inputAttrs, data.input_attrs ); 4185 #> 4186 4187 <# if ( 'button' === data.type ) { #> 4188 <button 4189 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4190 {{{ key }}}="{{ value }}" 4191 <# } ); #> 4192 >{{ inputAttrs.value }}</button> 4193 <# } else if ( 'textarea' === data.type ) { #> 4194 <textarea 4195 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4196 {{{ key }}}="{{ value }}" 4197 <# }); #> 4198 >{{ inputAttrs.value }}</textarea> 4199 <# } else if ( 'select' === data.type ) { #> 4200 <# delete inputAttrs.type; #> 4201 <select 4202 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4203 {{{ key }}}="{{ value }}" 4204 <# }); #> 4205 > 4206 <# _.each( data.choices, function( val, key ) { #> 4207 <# 4208 var value, text; 4209 if ( _.isObject( val ) ) { 4210 value = val.value; 4211 text = val.text; 4212 } else { 4213 value = key; 4214 text = val; 4215 } 4216 #> 4217 <option value="{{ value }}">{{ text }}</option> 4218 <# } ); #> 4219 </select> 4220 <# } else { #> 4221 <input 4222 <# _.each( _.extend( inputAttrs ), function( value, key ) { #> 4223 {{{ key }}}="{{ value }}" 4224 <# }); #> 4225 > 4226 <# } #> 4227 <# } #> 4228 </script> 4229 4230 <script type="text/html" id="tmpl-customize-notification"> 4231 <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 }}"> 4232 <div class="notification-message">{{{ data.message || data.code }}}</div> 4233 <# if ( data.dismissible ) { #> 4234 <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php _e( 'Dismiss' ); ?></span></button> 4235 <# } #> 4236 </li> 4237 </script> 4238 4239 <script type="text/html" id="tmpl-customize-changeset-locked-notification"> 4240 <li class="notice notice-{{ data.type || 'info' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> 4241 <div class="notification-message customize-changeset-locked-message"> 4242 <img class="customize-changeset-locked-avatar" src="{{ data.lockUser.avatar }}" alt="{{ data.lockUser.name }}"> 4243 <p class="currently-editing"> 4244 <# if ( data.message ) { #> 4245 {{{ data.message }}} 4246 <# } else if ( data.allowOverride ) { #> 4247 <?php 4248 echo esc_html( sprintf( $l10n['locked_allow_override'], '{{ data.lockUser.name }}' ) ); 4249 ?> 4250 <# } else { #> 4251 <?php 4252 echo esc_html( sprintf( $l10n['locked'], '{{ data.lockUser.name }}' ) ); 4253 ?> 4254 <# } #> 4255 </p> 4256 <p class="notice notice-error notice-alt" hidden></p> 4257 <p class="action-buttons"> 4258 <# if ( data.returnUrl !== data.previewUrl ) { #> 4259 <a class="button customize-notice-go-back-button" href="{{ data.returnUrl }}"><?php _e( 'Go back' ); ?></a> 4260 <# } #> 4261 <a class="button customize-notice-preview-button" href="{{ data.frontendPreviewUrl }}"><?php _e( 'Preview' ); ?></a> 4262 <# if ( data.allowOverride ) { #> 4263 <button class="button button-primary wp-tab-last customize-notice-take-over-button"><?php _e( 'Take over' ); ?></button> 4264 <# } #> 4265 </p> 4266 </div> 4267 </li> 4268 </script> 4269 4270 <script type="text/html" id="tmpl-customize-code-editor-lint-error-notification"> 4271 <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 }}"> 4272 <div class="notification-message">{{{ data.message || data.code }}}</div> 4273 4274 <p> 4275 <# var elementId = 'el-' + String( Math.random() ); #> 4276 <input id="{{ elementId }}" type="checkbox"> 4277 <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label> 4278 </p> 4279 </li> 4280 </script> 4281 4282 <?php 4283 /* The following template is obsolete in core but retained for plugins. */ 4284 ?> 4285 <script type="text/html" id="tmpl-customize-control-notifications"> 4286 <ul> 4287 <# _.each( data.notifications, function( notification ) { #> 4288 <li class="notice notice-{{ notification.type || 'info' }} {{ data.altNotice ? 'notice-alt' : '' }}" data-code="{{ notification.code }}" data-type="{{ notification.type }}">{{{ notification.message || notification.code }}}</li> 4289 <# } ); #> 4290 </ul> 4291 </script> 4292 4293 <script type="text/html" id="tmpl-customize-preview-link-control" > 4294 <# var elementPrefix = _.uniqueId( 'el' ) + '-' #> 4295 <p class="customize-control-title"> 4296 <?php esc_html_e( 'Share Preview Link' ); ?> 4297 </p> 4298 <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> 4299 <div class="customize-control-notifications-container"></div> 4300 <div class="preview-link-wrapper"> 4301 <label for="{{ elementPrefix }}customize-preview-link-input" class="screen-reader-text"><?php esc_html_e( 'Preview Link' ); ?></label> 4302 <a href="" target=""> 4303 <span class="preview-control-element" data-component="url"></span> 4304 <span class="screen-reader-text"><?php _e( '(opens in a new tab)' ); ?></span> 4305 </a> 4306 <input id="{{ elementPrefix }}customize-preview-link-input" readonly tabindex="-1" class="preview-control-element" data-component="input"> 4307 <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> 4308 </div> 4309 </script> 4310 <script type="text/html" id="tmpl-customize-selected-changeset-status-control"> 4311 <# var inputId = _.uniqueId( 'customize-selected-changeset-status-control-input-' ); #> 4312 <# var descriptionId = _.uniqueId( 'customize-selected-changeset-status-control-description-' ); #> 4313 <# if ( data.label ) { #> 4314 <label for="{{ inputId }}" class="customize-control-title">{{ data.label }}</label> 4315 <# } #> 4316 <# if ( data.description ) { #> 4317 <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> 4318 <# } #> 4319 <# _.each( data.choices, function( choice ) { #> 4320 <# var choiceId = inputId + '-' + choice.status; #> 4321 <span class="customize-inside-control-row"> 4322 <input id="{{ choiceId }}" type="radio" value="{{ choice.status }}" name="{{ inputId }}" data-customize-setting-key-link="default"> 4323 <label for="{{ choiceId }}">{{ choice.label }}</label> 4324 </span> 4325 <# } ); #> 4326 </script> 4327 <?php 4328 } 4329 4330 /** 4331 * Helper function to compare two objects by priority, ensuring sort stability via instance_number. 4332 * 4333 * @since 3.4.0 4334 * @deprecated 4.7.0 Use wp_list_sort() 4335 * 4336 * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a Object A. 4337 * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b Object B. 4338 * @return int 4339 */ 4340 protected function _cmp_priority( $a, $b ) { 4341 _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' ); 4342 4343 if ( $a->priority === $b->priority ) { 4344 return $a->instance_number - $b->instance_number; 4345 } else { 4346 return $a->priority - $b->priority; 4347 } 4348 } 4349 4350 /** 4351 * Prepare panels, sections, and controls. 4352 * 4353 * For each, check if required related components exist, 4354 * whether the user has the necessary capabilities, 4355 * and sort by priority. 4356 * 4357 * @since 3.4.0 4358 */ 4359 public function prepare_controls() { 4360 4361 $controls = array(); 4362 $this->controls = wp_list_sort( 4363 $this->controls, 4364 array( 4365 'priority' => 'ASC', 4366 'instance_number' => 'ASC', 4367 ), 4368 'ASC', 4369 true 4370 ); 4371 4372 foreach ( $this->controls as $id => $control ) { 4373 if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) { 4374 continue; 4375 } 4376 4377 $this->sections[ $control->section ]->controls[] = $control; 4378 $controls[ $id ] = $control; 4379 } 4380 $this->controls = $controls; 4381 4382 // Prepare sections. 4383 $this->sections = wp_list_sort( 4384 $this->sections, 4385 array( 4386 'priority' => 'ASC', 4387 'instance_number' => 'ASC', 4388 ), 4389 'ASC', 4390 true 4391 ); 4392 $sections = array(); 4393 4394 foreach ( $this->sections as $section ) { 4395 if ( ! $section->check_capabilities() ) { 4396 continue; 4397 } 4398 4399 $section->controls = wp_list_sort( 4400 $section->controls, 4401 array( 4402 'priority' => 'ASC', 4403 'instance_number' => 'ASC', 4404 ) 4405 ); 4406 4407 if ( ! $section->panel ) { 4408 // Top-level section. 4409 $sections[ $section->id ] = $section; 4410 } else { 4411 // This section belongs to a panel. 4412 if ( isset( $this->panels [ $section->panel ] ) ) { 4413 $this->panels[ $section->panel ]->sections[ $section->id ] = $section; 4414 } 4415 } 4416 } 4417 $this->sections = $sections; 4418 4419 // Prepare panels. 4420 $this->panels = wp_list_sort( 4421 $this->panels, 4422 array( 4423 'priority' => 'ASC', 4424 'instance_number' => 'ASC', 4425 ), 4426 'ASC', 4427 true 4428 ); 4429 $panels = array(); 4430 4431 foreach ( $this->panels as $panel ) { 4432 if ( ! $panel->check_capabilities() ) { 4433 continue; 4434 } 4435 4436 $panel->sections = wp_list_sort( 4437 $panel->sections, 4438 array( 4439 'priority' => 'ASC', 4440 'instance_number' => 'ASC', 4441 ), 4442 'ASC', 4443 true 4444 ); 4445 $panels[ $panel->id ] = $panel; 4446 } 4447 $this->panels = $panels; 4448 4449 // Sort panels and top-level sections together. 4450 $this->containers = array_merge( $this->panels, $this->sections ); 4451 $this->containers = wp_list_sort( 4452 $this->containers, 4453 array( 4454 'priority' => 'ASC', 4455 'instance_number' => 'ASC', 4456 ), 4457 'ASC', 4458 true 4459 ); 4460 } 4461 4462 /** 4463 * Enqueue scripts for customize controls. 4464 * 4465 * @since 3.4.0 4466 */ 4467 public function enqueue_control_scripts() { 4468 foreach ( $this->controls as $control ) { 4469 $control->enqueue(); 4470 } 4471 4472 if ( ! is_multisite() && ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) || current_user_can( 'delete_themes' ) ) ) { 4473 wp_enqueue_script( 'updates' ); 4474 wp_localize_script( 4475 'updates', 4476 '_wpUpdatesItemCounts', 4477 array( 4478 'totals' => wp_get_update_data(), 4479 ) 4480 ); 4481 } 4482 } 4483 4484 /** 4485 * Determine whether the user agent is iOS. 4486 * 4487 * @since 4.4.0 4488 * 4489 * @return bool Whether the user agent is iOS. 4490 */ 4491 public function is_ios() { 4492 return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] ); 4493 } 4494 4495 /** 4496 * Get the template string for the Customizer pane document title. 4497 * 4498 * @since 4.4.0 4499 * 4500 * @return string The template string for the document title. 4501 */ 4502 public function get_document_title_template() { 4503 if ( $this->is_theme_active() ) { 4504 /* translators: %s: Document title from the preview. */ 4505 $document_title_tmpl = __( 'Customize: %s' ); 4506 } else { 4507 /* translators: %s: Document title from the preview. */ 4508 $document_title_tmpl = __( 'Live Preview: %s' ); 4509 } 4510 $document_title_tmpl = html_entity_decode( $document_title_tmpl, ENT_QUOTES, 'UTF-8' ); // Because exported to JS and assigned to document.title. 4511 return $document_title_tmpl; 4512 } 4513 4514 /** 4515 * Set the initial URL to be previewed. 4516 * 4517 * URL is validated. 4518 * 4519 * @since 4.4.0 4520 * 4521 * @param string $preview_url URL to be previewed. 4522 */ 4523 public function set_preview_url( $preview_url ) { 4524 $preview_url = esc_url_raw( $preview_url ); 4525 $this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) ); 4526 } 4527 4528 /** 4529 * Get the initial URL to be previewed. 4530 * 4531 * @since 4.4.0 4532 * 4533 * @return string URL being previewed. 4534 */ 4535 public function get_preview_url() { 4536 if ( empty( $this->preview_url ) ) { 4537 $preview_url = home_url( '/' ); 4538 } else { 4539 $preview_url = $this->preview_url; 4540 } 4541 return $preview_url; 4542 } 4543 4544 /** 4545 * Determines whether the admin and the frontend are on different domains. 4546 * 4547 * @since 4.7.0 4548 * 4549 * @return bool Whether cross-domain. 4550 */ 4551 public function is_cross_domain() { 4552 $admin_origin = wp_parse_url( admin_url() ); 4553 $home_origin = wp_parse_url( home_url() ); 4554 $cross_domain = ( strtolower( $admin_origin['host'] ) !== strtolower( $home_origin['host'] ) ); 4555 return $cross_domain; 4556 } 4557 4558 /** 4559 * Get URLs allowed to be previewed. 4560 * 4561 * If the front end and the admin are served from the same domain, load the 4562 * preview over ssl if the Customizer is being loaded over ssl. This avoids 4563 * insecure content warnings. This is not attempted if the admin and front end 4564 * are on different domains to avoid the case where the front end doesn't have 4565 * ssl certs. Domain mapping plugins can allow other urls in these conditions 4566 * using the customize_allowed_urls filter. 4567 * 4568 * @since 4.7.0 4569 * 4570 * @return array Allowed URLs. 4571 */ 4572 public function get_allowed_urls() { 4573 $allowed_urls = array( home_url( '/' ) ); 4574 4575 if ( is_ssl() && ! $this->is_cross_domain() ) { 4576 $allowed_urls[] = home_url( '/', 'https' ); 4577 } 4578 4579 /** 4580 * Filters the list of URLs allowed to be clicked and followed in the Customizer preview. 4581 * 4582 * @since 3.4.0 4583 * 4584 * @param string[] $allowed_urls An array of allowed URLs. 4585 */ 4586 $allowed_urls = array_unique( apply_filters( 'customize_allowed_urls', $allowed_urls ) ); 4587 4588 return $allowed_urls; 4589 } 4590 4591 /** 4592 * Get messenger channel. 4593 * 4594 * @since 4.7.0 4595 * 4596 * @return string Messenger channel. 4597 */ 4598 public function get_messenger_channel() { 4599 return $this->messenger_channel; 4600 } 4601 4602 /** 4603 * Set URL to link the user to when closing the Customizer. 4604 * 4605 * URL is validated. 4606 * 4607 * @since 4.4.0 4608 * 4609 * @param string $return_url URL for return link. 4610 */ 4611 public function set_return_url( $return_url ) { 4612 $return_url = esc_url_raw( $return_url ); 4613 $return_url = remove_query_arg( wp_removable_query_args(), $return_url ); 4614 $return_url = wp_validate_redirect( $return_url ); 4615 $this->return_url = $return_url; 4616 } 4617 4618 /** 4619 * Get URL to link the user to when closing the Customizer. 4620 * 4621 * @since 4.4.0 4622 * 4623 * @global array $_registered_pages 4624 * 4625 * @return string URL for link to close Customizer. 4626 */ 4627 public function get_return_url() { 4628 global $_registered_pages; 4629 4630 $referer = wp_get_referer(); 4631 $excluded_referer_basenames = array( 'customize.php', 'wp-login.php' ); 4632 4633 if ( $this->return_url ) { 4634 $return_url = $this->return_url; 4635 } elseif ( $referer && ! in_array( wp_basename( parse_url( $referer, PHP_URL_PATH ) ), $excluded_referer_basenames, true ) ) { 4636 $return_url = $referer; 4637 } elseif ( $this->preview_url ) { 4638 $return_url = $this->preview_url; 4639 } else { 4640 $return_url = home_url( '/' ); 4641 } 4642 4643 $return_url_basename = wp_basename( parse_url( $this->return_url, PHP_URL_PATH ) ); 4644 $return_url_query = parse_url( $this->return_url, PHP_URL_QUERY ); 4645 4646 if ( 'themes.php' === $return_url_basename && $return_url_query ) { 4647 parse_str( $return_url_query, $query_vars ); 4648 4649 /* 4650 * If the return URL is a page added by a theme to the Appearance menu via add_submenu_page(), 4651 * verify that belongs to the active theme, otherwise fall back to the Themes screen. 4652 */ 4653 if ( isset( $query_vars['page'] ) && ! isset( $_registered_pages[ "appearance_page_{$query_vars['page']}" ] ) ) { 4654 $return_url = admin_url( 'themes.php' ); 4655 } 4656 } 4657 4658 return $return_url; 4659 } 4660 4661 /** 4662 * Set the autofocused constructs. 4663 * 4664 * @since 4.4.0 4665 * 4666 * @param array $autofocus { 4667 * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. 4668 * 4669 * @type string [$control] ID for control to be autofocused. 4670 * @type string [$section] ID for section to be autofocused. 4671 * @type string [$panel] ID for panel to be autofocused. 4672 * } 4673 */ 4674 public function set_autofocus( $autofocus ) { 4675 $this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' ); 4676 } 4677 4678 /** 4679 * Get the autofocused constructs. 4680 * 4681 * @since 4.4.0 4682 * 4683 * @return array { 4684 * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. 4685 * 4686 * @type string [$control] ID for control to be autofocused. 4687 * @type string [$section] ID for section to be autofocused. 4688 * @type string [$panel] ID for panel to be autofocused. 4689 * } 4690 */ 4691 public function get_autofocus() { 4692 return $this->autofocus; 4693 } 4694 4695 /** 4696 * Get nonces for the Customizer. 4697 * 4698 * @since 4.5.0 4699 * 4700 * @return array Nonces. 4701 */ 4702 public function get_nonces() { 4703 $nonces = array( 4704 'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ), 4705 'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ), 4706 'switch_themes' => wp_create_nonce( 'switch_themes' ), 4707 'dismiss_autosave_or_lock' => wp_create_nonce( 'customize_dismiss_autosave_or_lock' ), 4708 'override_lock' => wp_create_nonce( 'customize_override_changeset_lock' ), 4709 'trash' => wp_create_nonce( 'trash_customize_changeset' ), 4710 ); 4711 4712 /** 4713 * Filters nonces for Customizer. 4714 * 4715 * @since 4.2.0 4716 * 4717 * @param string[] $nonces Array of refreshed nonces for save and 4718 * preview actions. 4719 * @param WP_Customize_Manager $this WP_Customize_Manager instance. 4720 */ 4721 $nonces = apply_filters( 'customize_refresh_nonces', $nonces, $this ); 4722 4723 return $nonces; 4724 } 4725 4726 /** 4727 * Print JavaScript settings for parent window. 4728 * 4729 * @since 4.4.0 4730 */ 4731 public function customize_pane_settings() { 4732 4733 $login_url = add_query_arg( 4734 array( 4735 'interim-login' => 1, 4736 'customize-login' => 1, 4737 ), 4738 wp_login_url() 4739 ); 4740 4741 // Ensure dirty flags are set for modified settings. 4742 foreach ( array_keys( $this->unsanitized_post_values() ) as $setting_id ) { 4743 $setting = $this->get_setting( $setting_id ); 4744 if ( $setting ) { 4745 $setting->dirty = true; 4746 } 4747 } 4748 4749 $autosave_revision_post = null; 4750 $autosave_autodraft_post = null; 4751 $changeset_post_id = $this->changeset_post_id(); 4752 if ( ! $this->saved_starter_content_changeset && ! $this->autosaved() ) { 4753 if ( $changeset_post_id ) { 4754 if ( is_user_logged_in() ) { 4755 $autosave_revision_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); 4756 } 4757 } else { 4758 $autosave_autodraft_posts = $this->get_changeset_posts( 4759 array( 4760 'posts_per_page' => 1, 4761 'post_status' => 'auto-draft', 4762 'exclude_restore_dismissed' => true, 4763 ) 4764 ); 4765 if ( ! empty( $autosave_autodraft_posts ) ) { 4766 $autosave_autodraft_post = array_shift( $autosave_autodraft_posts ); 4767 } 4768 } 4769 } 4770 4771 $current_user_can_publish = current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ); 4772 4773 // @todo Include all of the status labels here from script-loader.php, and then allow it to be filtered. 4774 $status_choices = array(); 4775 if ( $current_user_can_publish ) { 4776 $status_choices[] = array( 4777 'status' => 'publish', 4778 'label' => __( 'Publish' ), 4779 ); 4780 } 4781 $status_choices[] = array( 4782 'status' => 'draft', 4783 'label' => __( 'Save Draft' ), 4784 ); 4785 if ( $current_user_can_publish ) { 4786 $status_choices[] = array( 4787 'status' => 'future', 4788 'label' => _x( 'Schedule', 'customizer changeset action/button label' ), 4789 ); 4790 } 4791 4792 // Prepare Customizer settings to pass to JavaScript. 4793 $changeset_post = null; 4794 if ( $changeset_post_id ) { 4795 $changeset_post = get_post( $changeset_post_id ); 4796 } 4797 4798 // Determine initial date to be at present or future, not past. 4799 $current_time = current_time( 'mysql', false ); 4800 $initial_date = $current_time; 4801 if ( $changeset_post ) { 4802 $initial_date = get_the_time( 'Y-m-d H:i:s', $changeset_post->ID ); 4803 if ( $initial_date < $current_time ) { 4804 $initial_date = $current_time; 4805 } 4806 } 4807 4808 $lock_user_id = false; 4809 if ( $this->changeset_post_id() ) { 4810 $lock_user_id = wp_check_post_lock( $this->changeset_post_id() ); 4811 } 4812 4813 $settings = array( 4814 'changeset' => array( 4815 'uuid' => $this->changeset_uuid(), 4816 'branching' => $this->branching(), 4817 'autosaved' => $this->autosaved(), 4818 'hasAutosaveRevision' => ! empty( $autosave_revision_post ), 4819 'latestAutoDraftUuid' => $autosave_autodraft_post ? $autosave_autodraft_post->post_name : null, 4820 'status' => $changeset_post ? $changeset_post->post_status : '', 4821 'currentUserCanPublish' => $current_user_can_publish, 4822 'publishDate' => $initial_date, 4823 'statusChoices' => $status_choices, 4824 'lockUser' => $lock_user_id ? $this->get_lock_user_data( $lock_user_id ) : null, 4825 ), 4826 'initialServerDate' => $current_time, 4827 'dateFormat' => get_option( 'date_format' ), 4828 'timeFormat' => get_option( 'time_format' ), 4829 'initialServerTimestamp' => floor(