[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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