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