[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-customize-manager.php (source)

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