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