[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * WordPress Customize Widgets classes
   4   *
   5   * @package WordPress
   6   * @subpackage Customize
   7   * @since 3.9.0
   8   */
   9  
  10  /**
  11   * Customize Widgets class.
  12   *
  13   * Implements widget management in the Customizer.
  14   *
  15   * @since 3.9.0
  16   *
  17   * @see WP_Customize_Manager
  18   */
  19  final class WP_Customize_Widgets {
  20  
  21      /**
  22       * WP_Customize_Manager instance.
  23       *
  24       * @since 3.9.0
  25       * @var WP_Customize_Manager
  26       */
  27      public $manager;
  28  
  29      /**
  30       * All id_bases for widgets defined in core.
  31       *
  32       * @since 3.9.0
  33       * @var array
  34       */
  35      protected $core_widget_id_bases = array(
  36          'archives',
  37          'calendar',
  38          'categories',
  39          'custom_html',
  40          'links',
  41          'media_audio',
  42          'media_image',
  43          'media_video',
  44          'meta',
  45          'nav_menu',
  46          'pages',
  47          'recent-comments',
  48          'recent-posts',
  49          'rss',
  50          'search',
  51          'tag_cloud',
  52          'text',
  53      );
  54  
  55      /**
  56       * @since 3.9.0
  57       * @var array
  58       */
  59      protected $rendered_sidebars = array();
  60  
  61      /**
  62       * @since 3.9.0
  63       * @var array
  64       */
  65      protected $rendered_widgets = array();
  66  
  67      /**
  68       * @since 3.9.0
  69       * @var array
  70       */
  71      protected $old_sidebars_widgets = array();
  72  
  73      /**
  74       * Mapping of widget ID base to whether it supports selective refresh.
  75       *
  76       * @since 4.5.0
  77       * @var array
  78       */
  79      protected $selective_refreshable_widgets;
  80  
  81      /**
  82       * Mapping of setting type to setting ID pattern.
  83       *
  84       * @since 4.2.0
  85       * @var array
  86       */
  87      protected $setting_id_patterns = array(
  88          'widget_instance' => '/^widget_(?P<id_base>.+?)(?:\[(?P<widget_number>\d+)\])?$/',
  89          'sidebar_widgets' => '/^sidebars_widgets\[(?P<sidebar_id>.+?)\]$/',
  90      );
  91  
  92      /**
  93       * Initial loader.
  94       *
  95       * @since 3.9.0
  96       *
  97       * @param WP_Customize_Manager $manager Customizer bootstrap instance.
  98       */
  99  	public function __construct( $manager ) {
 100          $this->manager = $manager;
 101  
 102          // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
 103          add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
 104          add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
 105          add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
 106  
 107          // Skip remaining hooks when the user can't manage widgets anyway.
 108          if ( ! current_user_can( 'edit_theme_options' ) ) {
 109              return;
 110          }
 111  
 112          add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
 113          add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
 114          add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
 115          add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
 116          add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
 117          add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
 118          add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
 119          add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
 120          add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
 121  
 122          add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
 123          add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
 124          add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
 125  
 126          // Selective Refresh.
 127          add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
 128          add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
 129      }
 130  
 131      /**
 132       * List whether each registered widget can be use selective refresh.
 133       *
 134       * If the theme does not support the customize-selective-refresh-widgets feature,
 135       * then this will always return an empty array.
 136       *
 137       * @since 4.5.0
 138       *
 139       * @global WP_Widget_Factory $wp_widget_factory
 140       *
 141       * @return array Mapping of id_base to support. If theme doesn't support
 142       *               selective refresh, an empty array is returned.
 143       */
 144  	public function get_selective_refreshable_widgets() {
 145          global $wp_widget_factory;
 146          if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
 147              return array();
 148          }
 149          if ( ! isset( $this->selective_refreshable_widgets ) ) {
 150              $this->selective_refreshable_widgets = array();
 151              foreach ( $wp_widget_factory->widgets as $wp_widget ) {
 152                  $this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
 153              }
 154          }
 155          return $this->selective_refreshable_widgets;
 156      }
 157  
 158      /**
 159       * Determines if a widget supports selective refresh.
 160       *
 161       * @since 4.5.0
 162       *
 163       * @param string $id_base Widget ID Base.
 164       * @return bool Whether the widget can be selective refreshed.
 165       */
 166  	public function is_widget_selective_refreshable( $id_base ) {
 167          $selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
 168          return ! empty( $selective_refreshable_widgets[ $id_base ] );
 169      }
 170  
 171      /**
 172       * Retrieves the widget setting type given a setting ID.
 173       *
 174       * @since 4.2.0
 175       *
 176       * @param string $setting_id Setting ID.
 177       * @return string|void Setting type.
 178       */
 179  	protected function get_setting_type( $setting_id ) {
 180          static $cache = array();
 181          if ( isset( $cache[ $setting_id ] ) ) {
 182              return $cache[ $setting_id ];
 183          }
 184          foreach ( $this->setting_id_patterns as $type => $pattern ) {
 185              if ( preg_match( $pattern, $setting_id ) ) {
 186                  $cache[ $setting_id ] = $type;
 187                  return $type;
 188              }
 189          }
 190      }
 191  
 192      /**
 193       * Inspects the incoming customized data for any widget settings, and dynamically adds
 194       * them up-front so widgets will be initialized properly.
 195       *
 196       * @since 4.2.0
 197       */
 198  	public function register_settings() {
 199          $widget_setting_ids   = array();
 200          $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
 201          foreach ( $incoming_setting_ids as $setting_id ) {
 202              if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
 203                  $widget_setting_ids[] = $setting_id;
 204              }
 205          }
 206          if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
 207              $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
 208          }
 209  
 210          $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
 211  
 212          if ( $this->manager->settings_previewed() ) {
 213              foreach ( $settings as $setting ) {
 214                  $setting->preview();
 215              }
 216          }
 217      }
 218  
 219      /**
 220       * Determines the arguments for a dynamically-created setting.
 221       *
 222       * @since 4.2.0
 223       *
 224       * @param false|array $args       The arguments to the WP_Customize_Setting constructor.
 225       * @param string      $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
 226       * @return array|false Setting arguments, false otherwise.
 227       */
 228  	public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
 229          if ( $this->get_setting_type( $setting_id ) ) {
 230              $args = $this->get_setting_args( $setting_id );
 231          }
 232          return $args;
 233      }
 234  
 235      /**
 236       * Retrieves an unslashed post value or return a default.
 237       *
 238       * @since 3.9.0
 239       *
 240       * @param string $name    Post value.
 241       * @param mixed  $default Default post value.
 242       * @return mixed Unslashed post value or default value.
 243       */
 244  	protected function get_post_value( $name, $default = null ) {
 245          if ( ! isset( $_POST[ $name ] ) ) {
 246              return $default;
 247          }
 248  
 249          return wp_unslash( $_POST[ $name ] );
 250      }
 251  
 252      /**
 253       * Override sidebars_widgets for theme switch.
 254       *
 255       * When switching a theme via the Customizer, supply any previously-configured
 256       * sidebars_widgets from the target theme as the initial sidebars_widgets
 257       * setting. Also store the old theme's existing settings so that they can
 258       * be passed along for storing in the sidebars_widgets theme_mod when the
 259       * theme gets switched.
 260       *
 261       * @since 3.9.0
 262       *
 263       * @global array $sidebars_widgets
 264       * @global array $_wp_sidebars_widgets
 265       */
 266  	public function override_sidebars_widgets_for_theme_switch() {
 267          global $sidebars_widgets;
 268  
 269          if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
 270              return;
 271          }
 272  
 273          $this->old_sidebars_widgets = wp_get_sidebars_widgets();
 274          add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
 275          $this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
 276  
 277          // retrieve_widgets() looks at the global $sidebars_widgets.
 278          $sidebars_widgets = $this->old_sidebars_widgets;
 279          $sidebars_widgets = retrieve_widgets( 'customize' );
 280          add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
 281          // Reset global cache var used by wp_get_sidebars_widgets().
 282          unset( $GLOBALS['_wp_sidebars_widgets'] );
 283      }
 284  
 285      /**
 286       * Filters old_sidebars_widgets_data Customizer setting.
 287       *
 288       * When switching themes, filter the Customizer setting old_sidebars_widgets_data
 289       * to supply initial $sidebars_widgets before they were overridden by retrieve_widgets().
 290       * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
 291       * theme_mod.
 292       *
 293       * @since 3.9.0
 294       *
 295       * @see WP_Customize_Widgets::handle_theme_switch()
 296       *
 297       * @param array $old_sidebars_widgets
 298       * @return array
 299       */
 300      public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
 301          return $this->old_sidebars_widgets;
 302      }
 303  
 304      /**
 305       * Filters sidebars_widgets option for theme switch.
 306       *
 307       * When switching themes, the retrieve_widgets() function is run when the Customizer initializes,
 308       * and then the new sidebars_widgets here get supplied as the default value for the sidebars_widgets
 309       * option.
 310       *
 311       * @since 3.9.0
 312       *
 313       * @see WP_Customize_Widgets::handle_theme_switch()
 314       * @global array $sidebars_widgets
 315       *
 316       * @param array $sidebars_widgets
 317       * @return array
 318       */
 319      public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
 320          $sidebars_widgets                  = $GLOBALS['sidebars_widgets'];
 321          $sidebars_widgets['array_version'] = 3;
 322          return $sidebars_widgets;
 323      }
 324  
 325      /**
 326       * Ensures all widgets get loaded into the Customizer.
 327       *
 328       * Note: these actions are also fired in wp_ajax_update_widget().
 329       *
 330       * @since 3.9.0
 331       */
 332  	public function customize_controls_init() {
 333          /** This action is documented in wp-admin/includes/ajax-actions.php */
 334          do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 335  
 336          /** This action is documented in wp-admin/includes/ajax-actions.php */
 337          do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 338  
 339          /** This action is documented in wp-admin/widgets.php */
 340          do_action( 'sidebar_admin_setup' );
 341      }
 342  
 343      /**
 344       * Ensures widgets are available for all types of previews.
 345       *
 346       * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded
 347       * so that all filters have been initialized (e.g. Widget Visibility).
 348       *
 349       * @since 3.9.0
 350       */
 351  	public function schedule_customize_register() {
 352          if ( is_admin() ) {
 353              $this->customize_register();
 354          } else {
 355              add_action( 'wp', array( $this, 'customize_register' ) );
 356          }
 357      }
 358  
 359      /**
 360       * Registers Customizer settings and controls for all sidebars and widgets.
 361       *
 362       * @since 3.9.0
 363       *
 364       * @global array $wp_registered_widgets
 365       * @global array $wp_registered_widget_controls
 366       * @global array $wp_registered_sidebars
 367       */
 368  	public function customize_register() {
 369          global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
 370  
 371          add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
 372  
 373          $sidebars_widgets = array_merge(
 374              array( 'wp_inactive_widgets' => array() ),
 375              array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
 376              wp_get_sidebars_widgets()
 377          );
 378  
 379          $new_setting_ids = array();
 380  
 381          /*
 382           * Register a setting for all widgets, including those which are active,
 383           * inactive, and orphaned since a widget may get suppressed from a sidebar
 384           * via a plugin (like Widget Visibility).
 385           */
 386          foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
 387              $setting_id   = $this->get_setting_id( $widget_id );
 388              $setting_args = $this->get_setting_args( $setting_id );
 389              if ( ! $this->manager->get_setting( $setting_id ) ) {
 390                  $this->manager->add_setting( $setting_id, $setting_args );
 391              }
 392              $new_setting_ids[] = $setting_id;
 393          }
 394  
 395          /*
 396           * Add a setting which will be supplied for the theme's sidebars_widgets
 397           * theme_mod when the theme is switched.
 398           */
 399          if ( ! $this->manager->is_theme_active() ) {
 400              $setting_id   = 'old_sidebars_widgets_data';
 401              $setting_args = $this->get_setting_args(
 402                  $setting_id,
 403                  array(
 404                      'type'  => 'global_variable',
 405                      'dirty' => true,
 406                  )
 407              );
 408              $this->manager->add_setting( $setting_id, $setting_args );
 409          }
 410  
 411          $this->manager->add_panel(
 412              'widgets',
 413              array(
 414                  'type'                     => 'widgets',
 415                  'title'                    => __( 'Widgets' ),
 416                  'description'              => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
 417                  'priority'                 => 110,
 418                  'active_callback'          => array( $this, 'is_panel_active' ),
 419                  'auto_expand_sole_section' => true,
 420              )
 421          );
 422  
 423          foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
 424              if ( empty( $sidebar_widget_ids ) ) {
 425                  $sidebar_widget_ids = array();
 426              }
 427  
 428              $is_registered_sidebar = is_registered_sidebar( $sidebar_id );
 429              $is_inactive_widgets   = ( 'wp_inactive_widgets' === $sidebar_id );
 430              $is_active_sidebar     = ( $is_registered_sidebar && ! $is_inactive_widgets );
 431  
 432              // Add setting for managing the sidebar's widgets.
 433              if ( $is_registered_sidebar || $is_inactive_widgets ) {
 434                  $setting_id   = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
 435                  $setting_args = $this->get_setting_args( $setting_id );
 436                  if ( ! $this->manager->get_setting( $setting_id ) ) {
 437                      if ( ! $this->manager->is_theme_active() ) {
 438                          $setting_args['dirty'] = true;
 439                      }
 440                      $this->manager->add_setting( $setting_id, $setting_args );
 441                  }
 442                  $new_setting_ids[] = $setting_id;
 443  
 444                  // Add section to contain controls.
 445                  $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
 446                  if ( $is_active_sidebar ) {
 447  
 448                      $section_args = array(
 449                          'title'       => $wp_registered_sidebars[ $sidebar_id ]['name'],
 450                          'description' => $wp_registered_sidebars[ $sidebar_id ]['description'],
 451                          'priority'    => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ), true ),
 452                          'panel'       => 'widgets',
 453                          'sidebar_id'  => $sidebar_id,
 454                      );
 455  
 456                      /**
 457                       * Filters Customizer widget section arguments for a given sidebar.
 458                       *
 459                       * @since 3.9.0
 460                       *
 461                       * @param array      $section_args Array of Customizer widget section arguments.
 462                       * @param string     $section_id   Customizer section ID.
 463                       * @param int|string $sidebar_id   Sidebar ID.
 464                       */
 465                      $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
 466  
 467                      $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
 468                      $this->manager->add_section( $section );
 469  
 470                      $control           = new WP_Widget_Area_Customize_Control(
 471                          $this->manager,
 472                          $setting_id,
 473                          array(
 474                              'section'    => $section_id,
 475                              'sidebar_id' => $sidebar_id,
 476                              'priority'   => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
 477                          )
 478                      );
 479                      $new_setting_ids[] = $setting_id;
 480  
 481                      $this->manager->add_control( $control );
 482                  }
 483              }
 484  
 485              // Add a control for each active widget (located in a sidebar).
 486              foreach ( $sidebar_widget_ids as $i => $widget_id ) {
 487  
 488                  // Skip widgets that may have gone away due to a plugin being deactivated.
 489                  if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
 490                      continue;
 491                  }
 492  
 493                  $registered_widget = $wp_registered_widgets[ $widget_id ];
 494                  $setting_id        = $this->get_setting_id( $widget_id );
 495                  $id_base           = $wp_registered_widget_controls[ $widget_id ]['id_base'];
 496  
 497                  $control = new WP_Widget_Form_Customize_Control(
 498                      $this->manager,
 499                      $setting_id,
 500                      array(
 501                          'label'          => $registered_widget['name'],
 502                          'section'        => $section_id,
 503                          'sidebar_id'     => $sidebar_id,
 504                          'widget_id'      => $widget_id,
 505                          'widget_id_base' => $id_base,
 506                          'priority'       => $i,
 507                          'width'          => $wp_registered_widget_controls[ $widget_id ]['width'],
 508                          'height'         => $wp_registered_widget_controls[ $widget_id ]['height'],
 509                          'is_wide'        => $this->is_wide_widget( $widget_id ),
 510                      )
 511                  );
 512                  $this->manager->add_control( $control );
 513              }
 514          }
 515  
 516          if ( $this->manager->settings_previewed() ) {
 517              foreach ( $new_setting_ids as $new_setting_id ) {
 518                  $this->manager->get_setting( $new_setting_id )->preview();
 519              }
 520          }
 521      }
 522  
 523      /**
 524       * Determines whether the widgets panel is active, based on whether there are sidebars registered.
 525       *
 526       * @since 4.4.0
 527       *
 528       * @see WP_Customize_Panel::$active_callback
 529       *
 530       * @global array $wp_registered_sidebars
 531       * @return bool Active.
 532       */
 533  	public function is_panel_active() {
 534          global $wp_registered_sidebars;
 535          return ! empty( $wp_registered_sidebars );
 536      }
 537  
 538      /**
 539       * Converts a widget_id into its corresponding Customizer setting ID (option name).
 540       *
 541       * @since 3.9.0
 542       *
 543       * @param string $widget_id Widget ID.
 544       * @return string Maybe-parsed widget ID.
 545       */
 546  	public function get_setting_id( $widget_id ) {
 547          $parsed_widget_id = $this->parse_widget_id( $widget_id );
 548          $setting_id       = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
 549  
 550          if ( ! is_null( $parsed_widget_id['number'] ) ) {
 551              $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
 552          }
 553          return $setting_id;
 554      }
 555  
 556      /**
 557       * Determines whether the widget is considered "wide".
 558       *
 559       * Core widgets which may have controls wider than 250, but can still be shown
 560       * in the narrow Customizer panel. The RSS and Text widgets in Core, for example,
 561       * have widths of 400 and yet they still render fine in the Customizer panel.
 562       *
 563       * This method will return all Core widgets as being not wide, but this can be
 564       * overridden with the {@see 'is_wide_widget_in_customizer'} filter.
 565       *
 566       * @since 3.9.0
 567       *
 568       * @global $wp_registered_widget_controls
 569       *
 570       * @param string $widget_id Widget ID.
 571       * @return bool Whether or not the widget is a "wide" widget.
 572       */
 573  	public function is_wide_widget( $widget_id ) {
 574          global $wp_registered_widget_controls;
 575  
 576          $parsed_widget_id = $this->parse_widget_id( $widget_id );
 577          $width            = $wp_registered_widget_controls[ $widget_id ]['width'];
 578          $is_core          = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases, true );
 579          $is_wide          = ( $width > 250 && ! $is_core );
 580  
 581          /**
 582           * Filters whether the given widget is considered "wide".
 583           *
 584           * @since 3.9.0
 585           *
 586           * @param bool   $is_wide   Whether the widget is wide, Default false.
 587           * @param string $widget_id Widget ID.
 588           */
 589          return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
 590      }
 591  
 592      /**
 593       * Converts a widget ID into its id_base and number components.
 594       *
 595       * @since 3.9.0
 596       *
 597       * @param string $widget_id Widget ID.
 598       * @return array Array containing a widget's id_base and number components.
 599       */
 600  	public function parse_widget_id( $widget_id ) {
 601          $parsed = array(
 602              'number'  => null,
 603              'id_base' => null,
 604          );
 605  
 606          if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
 607              $parsed['id_base'] = $matches[1];
 608              $parsed['number']  = intval( $matches[2] );
 609          } else {
 610              // Likely an old single widget.
 611              $parsed['id_base'] = $widget_id;
 612          }
 613          return $parsed;
 614      }
 615  
 616      /**
 617       * Converts a widget setting ID (option path) to its id_base and number components.
 618       *
 619       * @since 3.9.0
 620       *
 621       * @param string $setting_id Widget setting ID.
 622       * @return array|WP_Error Array containing a widget's id_base and number components,
 623       *                        or a WP_Error object.
 624       */
 625  	public function parse_widget_setting_id( $setting_id ) {
 626          if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
 627              return new WP_Error( 'widget_setting_invalid_id' );
 628          }
 629  
 630          $id_base = $matches[2];
 631          $number  = isset( $matches[3] ) ? intval( $matches[3] ) : null;
 632  
 633          return compact( 'id_base', 'number' );
 634      }
 635  
 636      /**
 637       * Calls admin_print_styles-widgets.php and admin_print_styles hooks to
 638       * allow custom styles from plugins.
 639       *
 640       * @since 3.9.0
 641       */
 642  	public function print_styles() {
 643          /** This action is documented in wp-admin/admin-header.php */
 644          do_action( 'admin_print_styles-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 645  
 646          /** This action is documented in wp-admin/admin-header.php */
 647          do_action( 'admin_print_styles' );
 648      }
 649  
 650      /**
 651       * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to
 652       * allow custom scripts from plugins.
 653       *
 654       * @since 3.9.0
 655       */
 656  	public function print_scripts() {
 657          /** This action is documented in wp-admin/admin-header.php */
 658          do_action( 'admin_print_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 659  
 660          /** This action is documented in wp-admin/admin-header.php */
 661          do_action( 'admin_print_scripts' );
 662      }
 663  
 664      /**
 665       * Enqueues scripts and styles for Customizer panel and export data to JavaScript.
 666       *
 667       * @since 3.9.0
 668       *
 669       * @global WP_Scripts $wp_scripts
 670       * @global array $wp_registered_sidebars
 671       * @global array $wp_registered_widgets
 672       */
 673  	public function enqueue_scripts() {
 674          global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
 675  
 676          wp_enqueue_style( 'customize-widgets' );
 677          wp_enqueue_script( 'customize-widgets' );
 678  
 679          /** This action is documented in wp-admin/admin-header.php */
 680          do_action( 'admin_enqueue_scripts', 'widgets.php' );
 681  
 682          /*
 683           * Export available widgets with control_tpl removed from model
 684           * since plugins need templates to be in the DOM.
 685           */
 686          $available_widgets = array();
 687  
 688          foreach ( $this->get_available_widgets() as $available_widget ) {
 689              unset( $available_widget['control_tpl'] );
 690              $available_widgets[] = $available_widget;
 691          }
 692  
 693          $widget_reorder_nav_tpl = sprintf(
 694              '<div class="widget-reorder-nav"><span class="move-widget" tabindex="0">%1$s</span><span class="move-widget-down" tabindex="0">%2$s</span><span class="move-widget-up" tabindex="0">%3$s</span></div>',
 695              __( 'Move to another area&hellip;' ),
 696              __( 'Move down' ),
 697              __( 'Move up' )
 698          );
 699  
 700          $move_widget_area_tpl = str_replace(
 701              array( '{description}', '{btn}' ),
 702              array(
 703                  __( 'Select an area to move this widget into:' ),
 704                  _x( 'Move', 'Move widget' ),
 705              ),
 706              '<div class="move-widget-area">
 707                  <p class="description">{description}</p>
 708                  <ul class="widget-area-select">
 709                      <% _.each( sidebars, function ( sidebar ){ %>
 710                          <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
 711                      <% }); %>
 712                  </ul>
 713                  <div class="move-widget-actions">
 714                      <button class="move-widget-btn button" type="button">{btn}</button>
 715                  </div>
 716              </div>'
 717          );
 718  
 719          /*
 720           * Gather all strings in PHP that may be needed by JS on the client.
 721           * Once JS i18n is implemented (in #20491), this can be removed.
 722           */
 723          $some_non_rendered_areas_messages    = array();
 724          $some_non_rendered_areas_messages[1] = html_entity_decode(
 725              __( 'Your theme has 1 other widget area, but this particular page doesn&#8217;t display it.' ),
 726              ENT_QUOTES,
 727              get_bloginfo( 'charset' )
 728          );
 729          $registered_sidebar_count            = count( $wp_registered_sidebars );
 730          for ( $non_rendered_count = 2; $non_rendered_count < $registered_sidebar_count; $non_rendered_count++ ) {
 731              $some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode(
 732                  sprintf(
 733                      /* translators: %s: The number of other widget areas registered but not rendered. */
 734                      _n(
 735                          'Your theme has %s other widget area, but this particular page doesn&#8217;t display it.',
 736                          'Your theme has %s other widget areas, but this particular page doesn&#8217;t display them.',
 737                          $non_rendered_count
 738                      ),
 739                      number_format_i18n( $non_rendered_count )
 740                  ),
 741                  ENT_QUOTES,
 742                  get_bloginfo( 'charset' )
 743              );
 744          }
 745  
 746          if ( 1 === $registered_sidebar_count ) {
 747              $no_areas_shown_message = html_entity_decode(
 748                  sprintf(
 749                      __( 'Your theme has 1 widget area, but this particular page doesn&#8217;t display it.' )
 750                  ),
 751                  ENT_QUOTES,
 752                  get_bloginfo( 'charset' )
 753              );
 754          } else {
 755              $no_areas_shown_message = html_entity_decode(
 756                  sprintf(
 757                      /* translators: %s: The total number of widget areas registered. */
 758                      _n(
 759                          'Your theme has %s widget area, but this particular page doesn&#8217;t display it.',
 760                          'Your theme has %s widget areas, but this particular page doesn&#8217;t display them.',
 761                          $registered_sidebar_count
 762                      ),
 763                      number_format_i18n( $registered_sidebar_count )
 764                  ),
 765                  ENT_QUOTES,
 766                  get_bloginfo( 'charset' )
 767              );
 768          }
 769  
 770          $settings = array(
 771              'registeredSidebars'          => array_values( $wp_registered_sidebars ),
 772              'registeredWidgets'           => $wp_registered_widgets,
 773              'availableWidgets'            => $available_widgets, // @todo Merge this with registered_widgets.
 774              'l10n'                        => array(
 775                  'saveBtnLabel'     => __( 'Apply' ),
 776                  'saveBtnTooltip'   => __( 'Save and preview changes before publishing them.' ),
 777                  'removeBtnLabel'   => __( 'Remove' ),
 778                  'removeBtnTooltip' => __( 'Keep widget settings and move it to the inactive widgets' ),
 779                  'error'            => __( 'An error has occurred. Please reload the page and try again.' ),
 780                  'widgetMovedUp'    => __( 'Widget moved up' ),
 781                  'widgetMovedDown'  => __( 'Widget moved down' ),
 782                  'navigatePreview'  => __( 'You can navigate to other pages on your site while using the Customizer to view and edit the widgets displayed on those pages.' ),
 783                  'someAreasShown'   => $some_non_rendered_areas_messages,
 784                  'noAreasShown'     => $no_areas_shown_message,
 785                  'reorderModeOn'    => __( 'Reorder mode enabled' ),
 786                  'reorderModeOff'   => __( 'Reorder mode closed' ),
 787                  'reorderLabelOn'   => esc_attr__( 'Reorder widgets' ),
 788                  /* translators: %d: The number of widgets found. */
 789                  'widgetsFound'     => __( 'Number of widgets found: %d' ),
 790                  'noWidgetsFound'   => __( 'No widgets found.' ),
 791              ),
 792              'tpl'                         => array(
 793                  'widgetReorderNav' => $widget_reorder_nav_tpl,
 794                  'moveWidgetArea'   => $move_widget_area_tpl,
 795              ),
 796              'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
 797          );
 798  
 799          foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
 800              unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
 801          }
 802  
 803          $wp_scripts->add_data(
 804              'customize-widgets',
 805              'data',
 806              sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
 807          );
 808      }
 809  
 810      /**
 811       * Renders the widget form control templates into the DOM.
 812       *
 813       * @since 3.9.0
 814       */
 815  	public function output_widget_control_templates() {
 816          ?>
 817          <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
 818          <div id="available-widgets">
 819              <div class="customize-section-title">
 820                  <button class="customize-section-back" tabindex="-1">
 821                      <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
 822                  </button>
 823                  <h3>
 824                      <span class="customize-action">
 825                      <?php
 826                          /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
 827                          printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
 828                      ?>
 829                      </span>
 830                      <?php _e( 'Add a Widget' ); ?>
 831                  </h3>
 832              </div>
 833              <div id="available-widgets-filter">
 834                  <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
 835                  <input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ); ?>" aria-describedby="widgets-search-desc" />
 836                  <div class="search-icon" aria-hidden="true"></div>
 837                  <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
 838                  <p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
 839              </div>
 840              <div id="available-widgets-list">
 841              <?php foreach ( $this->get_available_widgets() as $available_widget ) : ?>
 842                  <div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ); ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ); ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ); ?>" tabindex="0">
 843                      <?php echo $available_widget['control_tpl']; ?>
 844                  </div>
 845              <?php endforeach; ?>
 846              <p class="no-widgets-found-message"><?php _e( 'No widgets found.' ); ?></p>
 847              </div><!-- #available-widgets-list -->
 848          </div><!-- #available-widgets -->
 849          </div><!-- #widgets-left -->
 850          <?php
 851      }
 852  
 853      /**
 854       * Calls admin_print_footer_scripts and admin_print_scripts hooks to
 855       * allow custom scripts from plugins.
 856       *
 857       * @since 3.9.0
 858       */
 859  	public function print_footer_scripts() {
 860          /** This action is documented in wp-admin/admin-footer.php */
 861          do_action( 'admin_print_footer_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 862  
 863          /** This action is documented in wp-admin/admin-footer.php */
 864          do_action( 'admin_print_footer_scripts' );
 865  
 866          /** This action is documented in wp-admin/admin-footer.php */
 867          do_action( 'admin_footer-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
 868      }
 869  
 870      /**
 871       * Retrieves common arguments to supply when constructing a Customizer setting.
 872       *
 873       * @since 3.9.0
 874       *
 875       * @param string $id        Widget setting ID.
 876       * @param array  $overrides Array of setting overrides.
 877       * @return array Possibly modified setting arguments.
 878       */
 879  	public function get_setting_args( $id, $overrides = array() ) {
 880          $args = array(
 881              'type'       => 'option',
 882              'capability' => 'edit_theme_options',
 883              'default'    => array(),
 884          );
 885  
 886          if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
 887              $args['sanitize_callback']    = array( $this, 'sanitize_sidebar_widgets' );
 888              $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
 889              $args['transport']            = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
 890          } elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
 891              $args['sanitize_callback']    = array( $this, 'sanitize_widget_instance' );
 892              $args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
 893              $args['transport']            = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
 894          }
 895  
 896          $args = array_merge( $args, $overrides );
 897  
 898          /**
 899           * Filters the common arguments supplied when constructing a Customizer setting.
 900           *
 901           * @since 3.9.0
 902           *
 903           * @see WP_Customize_Setting
 904           *
 905           * @param array  $args Array of Customizer setting arguments.
 906           * @param string $id   Widget setting ID.
 907           */
 908          return apply_filters( 'widget_customizer_setting_args', $args, $id );
 909      }
 910  
 911      /**
 912       * Ensures sidebar widget arrays only ever contain widget IDS.
 913       *
 914       * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
 915       *
 916       * @since 3.9.0
 917       *
 918       * @param string[] $widget_ids Array of widget IDs.
 919       * @return string[] Array of sanitized widget IDs.
 920       */
 921  	public function sanitize_sidebar_widgets( $widget_ids ) {
 922          $widget_ids           = array_map( 'strval', (array) $widget_ids );
 923          $sanitized_widget_ids = array();
 924          foreach ( $widget_ids as $widget_id ) {
 925              $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
 926          }
 927          return $sanitized_widget_ids;
 928      }
 929  
 930      /**
 931       * Builds up an index of all available widgets for use in Backbone models.
 932       *
 933       * @since 3.9.0
 934       *
 935       * @global array $wp_registered_widgets
 936       * @global array $wp_registered_widget_controls
 937       *
 938       * @see wp_list_widgets()
 939       *
 940       * @return array List of available widgets.
 941       */
 942  	public function get_available_widgets() {
 943          static $available_widgets = array();
 944          if ( ! empty( $available_widgets ) ) {
 945              return $available_widgets;
 946          }
 947  
 948          global $wp_registered_widgets, $wp_registered_widget_controls;
 949          require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number().
 950  
 951          $sort = $wp_registered_widgets;
 952          usort( $sort, array( $this, '_sort_name_callback' ) );
 953          $done = array();
 954  
 955          foreach ( $sort as $widget ) {
 956              if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget.
 957                  continue;
 958              }
 959  
 960              $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
 961              $done[]  = $widget['callback'];
 962  
 963              if ( ! isset( $widget['params'][0] ) ) {
 964                  $widget['params'][0] = array();
 965              }
 966  
 967              $available_widget = $widget;
 968              unset( $available_widget['callback'] ); // Not serializable to JSON.
 969  
 970              $args = array(
 971                  'widget_id'   => $widget['id'],
 972                  'widget_name' => $widget['name'],
 973                  '_display'    => 'template',
 974              );
 975  
 976              $is_disabled     = false;
 977              $is_multi_widget = ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
 978              if ( $is_multi_widget ) {
 979                  $id_base            = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
 980                  $args['_temp_id']   = "$id_base-__i__";
 981                  $args['_multi_num'] = next_widget_id_number( $id_base );
 982                  $args['_add']       = 'multi';
 983              } else {
 984                  $args['_add'] = 'single';
 985  
 986                  if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
 987                      $is_disabled = true;
 988                  }
 989                  $id_base = $widget['id'];
 990              }
 991  
 992              $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar(
 993                  array(
 994                      0 => $args,
 995                      1 => $widget['params'][0],
 996                  )
 997              );
 998              $control_tpl               = $this->get_widget_control( $list_widget_controls_args );
 999  
1000              // The properties here are mapped to the Backbone Widget model.
1001              $available_widget = array_merge(
1002                  $available_widget,
1003                  array(
1004                      'temp_id'      => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
1005                      'is_multi'     => $is_multi_widget,
1006                      'control_tpl'  => $control_tpl,
1007                      'multi_number' => ( 'multi' === $args['_add'] ) ? $args['_multi_num'] : false,
1008                      'is_disabled'  => $is_disabled,
1009                      'id_base'      => $id_base,
1010                      'transport'    => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
1011                      'width'        => $wp_registered_widget_controls[ $widget['id'] ]['width'],
1012                      'height'       => $wp_registered_widget_controls[ $widget['id'] ]['height'],
1013                      'is_wide'      => $this->is_wide_widget( $widget['id'] ),
1014                  )
1015              );
1016  
1017              $available_widgets[] = $available_widget;
1018          }
1019  
1020          return $available_widgets;
1021      }
1022  
1023      /**
1024       * Naturally orders available widgets by name.
1025       *
1026       * @since 3.9.0
1027       *
1028       * @param array $widget_a The first widget to compare.
1029       * @param array $widget_b The second widget to compare.
1030       * @return int Reorder position for the current widget comparison.
1031       */
1032  	protected function _sort_name_callback( $widget_a, $widget_b ) {
1033          return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
1034      }
1035  
1036      /**
1037       * Retrieves the widget control markup.
1038       *
1039       * @since 3.9.0
1040       *
1041       * @param array $args Widget control arguments.
1042       * @return string Widget control form HTML markup.
1043       */
1044  	public function get_widget_control( $args ) {
1045          $args[0]['before_form']           = '<div class="form">';
1046          $args[0]['after_form']            = '</div><!-- .form -->';
1047          $args[0]['before_widget_content'] = '<div class="widget-content">';
1048          $args[0]['after_widget_content']  = '</div><!-- .widget-content -->';
1049          ob_start();
1050          wp_widget_control( ...$args );
1051          $control_tpl = ob_get_clean();
1052          return $control_tpl;
1053      }
1054  
1055      /**
1056       * Retrieves the widget control markup parts.
1057       *
1058       * @since 4.4.0
1059       *
1060       * @param array $args Widget control arguments.
1061       * @return array {
1062       *     @type string $control Markup for widget control wrapping form.
1063       *     @type string $content The contents of the widget form itself.
1064       * }
1065       */
1066  	public function get_widget_control_parts( $args ) {
1067          $args[0]['before_widget_content'] = '<div class="widget-content">';
1068          $args[0]['after_widget_content']  = '</div><!-- .widget-content -->';
1069          $control_markup                   = $this->get_widget_control( $args );
1070  
1071          $content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
1072          $content_end_pos   = strrpos( $control_markup, $args[0]['after_widget_content'] );
1073  
1074          $control  = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
1075          $control .= substr( $control_markup, $content_end_pos );
1076          $content  = trim(
1077              substr(
1078                  $control_markup,
1079                  $content_start_pos + strlen( $args[0]['before_widget_content'] ),
1080                  $content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
1081              )
1082          );
1083  
1084          return compact( 'control', 'content' );
1085      }
1086  
1087      /**
1088       * Adds hooks for the Customizer preview.
1089       *
1090       * @since 3.9.0
1091       */
1092  	public function customize_preview_init() {
1093          add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
1094          add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
1095          add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
1096      }
1097  
1098      /**
1099       * Refreshes the nonce for widget updates.
1100       *
1101       * @since 4.2.0
1102       *
1103       * @param array $nonces Array of nonces.
1104       * @return array Array of nonces.
1105       */
1106  	public function refresh_nonces( $nonces ) {
1107          $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
1108          return $nonces;
1109      }
1110  
1111      /**
1112       * When previewing, ensures the proper previewing widgets are used.
1113       *
1114       * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via
1115       * wp_convert_widget_settings()) and can set global variable `$_wp_sidebars_widgets`
1116       * to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview
1117       * filter is added, it has to be reset after the filter has been added.
1118       *
1119       * @since 3.9.0
1120       *
1121       * @param array $sidebars_widgets List of widgets for the current sidebar.
1122       * @return array
1123       */
1124  	public function preview_sidebars_widgets( $sidebars_widgets ) {
1125          $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1126  
1127          unset( $sidebars_widgets['array_version'] );
1128          return $sidebars_widgets;
1129      }
1130  
1131      /**
1132       * Enqueues scripts for the Customizer preview.
1133       *
1134       * @since 3.9.0
1135       */
1136  	public function customize_preview_enqueue() {
1137          wp_enqueue_script( 'customize-preview-widgets' );
1138      }
1139  
1140      /**
1141       * Inserts default style for highlighted widget at early point so theme
1142       * stylesheet can override.
1143       *
1144       * @since 3.9.0
1145       */
1146  	public function print_preview_css() {
1147          ?>
1148          <style>
1149          .widget-customizer-highlighted-widget {
1150              outline: none;
1151              -webkit-box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
1152              box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
1153              position: relative;
1154              z-index: 1;
1155          }
1156          </style>
1157          <?php
1158      }
1159  
1160      /**
1161       * Communicates the sidebars that appeared on the page at the very end of the page,
1162       * and at the very end of the wp_footer,
1163       *
1164       * @since 3.9.0
1165       *
1166       * @global array $wp_registered_sidebars
1167       * @global array $wp_registered_widgets
1168       */
1169  	public function export_preview_data() {
1170          global $wp_registered_sidebars, $wp_registered_widgets;
1171  
1172          $switched_locale = switch_to_locale( get_user_locale() );
1173  
1174          $l10n = array(
1175              'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
1176          );
1177  
1178          if ( $switched_locale ) {
1179              restore_previous_locale();
1180          }
1181  
1182          $rendered_sidebars = array_filter( $this->rendered_sidebars );
1183          $rendered_widgets  = array_filter( $this->rendered_widgets );
1184  
1185          // Prepare Customizer settings to pass to JavaScript.
1186          $settings = array(
1187              'renderedSidebars'            => array_fill_keys( array_keys( $rendered_sidebars ), true ),
1188              'renderedWidgets'             => array_fill_keys( array_keys( $rendered_widgets ), true ),
1189              'registeredSidebars'          => array_values( $wp_registered_sidebars ),
1190              'registeredWidgets'           => $wp_registered_widgets,
1191              'l10n'                        => $l10n,
1192              'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
1193          );
1194  
1195          foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
1196              unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
1197          }
1198  
1199          ?>
1200          <script type="text/javascript">
1201              var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
1202          </script>
1203          <?php
1204      }
1205  
1206      /**
1207       * Tracks the widgets that were rendered.
1208       *
1209       * @since 3.9.0
1210       *
1211       * @param array $widget Rendered widget to tally.
1212       */
1213  	public function tally_rendered_widgets( $widget ) {
1214          $this->rendered_widgets[ $widget['id'] ] = true;
1215      }
1216  
1217      /**
1218       * Determine if a widget is rendered on the page.
1219       *
1220       * @since 4.0.0
1221       *
1222       * @param string $widget_id Widget ID to check.
1223       * @return bool Whether the widget is rendered.
1224       */
1225  	public function is_widget_rendered( $widget_id ) {
1226          return ! empty( $this->rendered_widgets[ $widget_id ] );
1227      }
1228  
1229      /**
1230       * Determines if a sidebar is rendered on the page.
1231       *
1232       * @since 4.0.0
1233       *
1234       * @param string $sidebar_id Sidebar ID to check.
1235       * @return bool Whether the sidebar is rendered.
1236       */
1237  	public function is_sidebar_rendered( $sidebar_id ) {
1238          return ! empty( $this->rendered_sidebars[ $sidebar_id ] );
1239      }
1240  
1241      /**
1242       * Tallies the sidebars rendered via is_active_sidebar().
1243       *
1244       * Keep track of the times that is_active_sidebar() is called in the template,
1245       * and assume that this means that the sidebar would be rendered on the template
1246       * if there were widgets populating it.
1247       *
1248       * @since 3.9.0
1249       *
1250       * @param bool   $is_active  Whether the sidebar is active.
1251       * @param string $sidebar_id Sidebar ID.
1252       * @return bool Whether the sidebar is active.
1253       */
1254  	public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
1255          if ( is_registered_sidebar( $sidebar_id ) ) {
1256              $this->rendered_sidebars[ $sidebar_id ] = true;
1257          }
1258  
1259          /*
1260           * We may need to force this to true, and also force-true the value
1261           * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
1262           * is an area to drop widgets into, if the sidebar is empty.
1263           */
1264          return $is_active;
1265      }
1266  
1267      /**
1268       * Tallies the sidebars rendered via dynamic_sidebar().
1269       *
1270       * Keep track of the times that dynamic_sidebar() is called in the template,
1271       * and assume this means the sidebar would be rendered on the template if
1272       * there were widgets populating it.
1273       *
1274       * @since 3.9.0
1275       *
1276       * @param bool   $has_widgets Whether the current sidebar has widgets.
1277       * @param string $sidebar_id  Sidebar ID.
1278       * @return bool Whether the current sidebar has widgets.
1279       */
1280  	public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
1281          if ( is_registered_sidebar( $sidebar_id ) ) {
1282              $this->rendered_sidebars[ $sidebar_id ] = true;
1283          }
1284  
1285          /*
1286           * We may need to force this to true, and also force-true the value
1287           * for 'is_active_sidebar' if we want to ensure there is an area to
1288           * drop widgets into, if the sidebar is empty.
1289           */
1290          return $has_widgets;
1291      }
1292  
1293      /**
1294       * Retrieves MAC for a serialized widget instance string.
1295       *
1296       * Allows values posted back from JS to be rejected if any tampering of the
1297       * data has occurred.
1298       *
1299       * @since 3.9.0
1300       *
1301       * @param string $serialized_instance Widget instance.
1302       * @return string MAC for serialized widget instance.
1303       */
1304  	protected function get_instance_hash_key( $serialized_instance ) {
1305          return wp_hash( $serialized_instance );
1306      }
1307  
1308      /**
1309       * Sanitizes a widget instance.
1310       *
1311       * Unserialize the JS-instance for storing in the options. It's important that this filter
1312       * only get applied to an instance *once*.
1313       *
1314       * @since 3.9.0
1315       *
1316       * @param array $value Widget instance to sanitize.
1317       * @return array|void Sanitized widget instance.
1318       */
1319  	public function sanitize_widget_instance( $value ) {
1320          if ( array() === $value ) {
1321              return $value;
1322          }
1323  
1324          if ( empty( $value['is_widget_customizer_js_value'] )
1325              || empty( $value['instance_hash_key'] )
1326              || empty( $value['encoded_serialized_instance'] ) ) {
1327              return;
1328          }
1329  
1330          $decoded = base64_decode( $value['encoded_serialized_instance'], true );
1331          if ( false === $decoded ) {
1332              return;
1333          }
1334  
1335          if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
1336              return;
1337          }
1338  
1339          $instance = unserialize( $decoded );
1340          if ( false === $instance ) {
1341              return;
1342          }
1343  
1344          return $instance;
1345      }
1346  
1347      /**
1348       * Converts a widget instance into JSON-representable format.
1349       *
1350       * @since 3.9.0
1351       *
1352       * @param array $value Widget instance to convert to JSON.
1353       * @return array JSON-converted widget instance.
1354       */
1355  	public function sanitize_widget_js_instance( $value ) {
1356          if ( empty( $value['is_widget_customizer_js_value'] ) ) {
1357              $serialized = serialize( $value );
1358  
1359              $value = array(
1360                  'encoded_serialized_instance'   => base64_encode( $serialized ),
1361                  'title'                         => empty( $value['title'] ) ? '' : $value['title'],
1362                  'is_widget_customizer_js_value' => true,
1363                  'instance_hash_key'             => $this->get_instance_hash_key( $serialized ),
1364              );
1365          }
1366          return $value;
1367      }
1368  
1369      /**
1370       * Strips out widget IDs for widgets which are no longer registered.
1371       *
1372       * One example where this might happen is when a plugin orphans a widget
1373       * in a sidebar upon deactivation.
1374       *
1375       * @since 3.9.0
1376       *
1377       * @global array $wp_registered_widgets
1378       *
1379       * @param array $widget_ids List of widget IDs.
1380       * @return array Parsed list of widget IDs.
1381       */
1382  	public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
1383          global $wp_registered_widgets;
1384          $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
1385          return $widget_ids;
1386      }
1387  
1388      /**
1389       * Finds and invokes the widget update and control callbacks.
1390       *
1391       * Requires that `$_POST` be populated with the instance data.
1392       *
1393       * @since 3.9.0
1394       *
1395       * @global array $wp_registered_widget_updates
1396       * @global array $wp_registered_widget_controls
1397       *
1398       * @param string $widget_id Widget ID.
1399       * @return array|WP_Error Array containing the updated widget information.
1400       *                        A WP_Error object, otherwise.
1401       */
1402  	public function call_widget_update( $widget_id ) {
1403          global $wp_registered_widget_updates, $wp_registered_widget_controls;
1404  
1405          $setting_id = $this->get_setting_id( $widget_id );
1406  
1407          /*
1408           * Make sure that other setting changes have previewed since this widget
1409           * may depend on them (e.g. Menus being present for Navigation Menu widget).
1410           */
1411          if ( ! did_action( 'customize_preview_init' ) ) {
1412              foreach ( $this->manager->settings() as $setting ) {
1413                  if ( $setting->id !== $setting_id ) {
1414                      $setting->preview();
1415                  }
1416              }
1417          }
1418  
1419          $this->start_capturing_option_updates();
1420          $parsed_id   = $this->parse_widget_id( $widget_id );
1421          $option_name = 'widget_' . $parsed_id['id_base'];
1422  
1423          /*
1424           * If a previously-sanitized instance is provided, populate the input vars
1425           * with its values so that the widget update callback will read this instance
1426           */
1427          $added_input_vars = array();
1428          if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
1429              $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
1430              if ( false === $sanitized_widget_setting ) {
1431                  $this->stop_capturing_option_updates();
1432                  return new WP_Error( 'widget_setting_malformed' );
1433              }
1434  
1435              $instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
1436              if ( is_null( $instance ) ) {
1437                  $this->stop_capturing_option_updates();
1438                  return new WP_Error( 'widget_setting_unsanitized' );
1439              }
1440  
1441              if ( ! is_null( $parsed_id['number'] ) ) {
1442                  $value                         = array();
1443                  $value[ $parsed_id['number'] ] = $instance;
1444                  $key                           = 'widget-' . $parsed_id['id_base'];
1445                  $_REQUEST[ $key ]              = wp_slash( $value );
1446                  $_POST[ $key ]                 = $_REQUEST[ $key ];
1447                  $added_input_vars[]            = $key;
1448              } else {
1449                  foreach ( $instance as $key => $value ) {
1450                      $_REQUEST[ $key ]   = wp_slash( $value );
1451                      $_POST[ $key ]      = $_REQUEST[ $key ];
1452                      $added_input_vars[] = $key;
1453                  }
1454              }
1455          }
1456  
1457          // Invoke the widget update callback.
1458          foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
1459              if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
1460                  ob_start();
1461                  call_user_func_array( $control['callback'], $control['params'] );
1462                  ob_end_clean();
1463                  break;
1464              }
1465          }
1466  
1467          // Clean up any input vars that were manually added.
1468          foreach ( $added_input_vars as $key ) {
1469              unset( $_POST[ $key ] );
1470              unset( $_REQUEST[ $key ] );
1471          }
1472  
1473          // Make sure the expected option was updated.
1474          if ( 0 !== $this->count_captured_options() ) {
1475              if ( $this->count_captured_options() > 1 ) {
1476                  $this->stop_capturing_option_updates();
1477                  return new WP_Error( 'widget_setting_too_many_options' );
1478              }
1479  
1480              $updated_option_name = key( $this->get_captured_options() );
1481              if ( $updated_option_name !== $option_name ) {
1482                  $this->stop_capturing_option_updates();
1483                  return new WP_Error( 'widget_setting_unexpected_option' );
1484              }
1485          }
1486  
1487          // Obtain the widget instance.
1488          $option = $this->get_captured_option( $option_name );
1489          if ( null !== $parsed_id['number'] ) {
1490              $instance = $option[ $parsed_id['number'] ];
1491          } else {
1492              $instance = $option;
1493          }
1494  
1495          /*
1496           * Override the incoming $_POST['customized'] for a newly-created widget's
1497           * setting with the new $instance so that the preview filter currently
1498           * in place from WP_Customize_Setting::preview() will use this value
1499           * instead of the default widget instance value (an empty array).
1500           */
1501          $this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance ) );
1502  
1503          // Obtain the widget control with the updated instance in place.
1504          ob_start();
1505          $form = $wp_registered_widget_controls[ $widget_id ];
1506          if ( $form ) {
1507              call_user_func_array( $form['callback'], $form['params'] );
1508          }
1509          $form = ob_get_clean();
1510  
1511          $this->stop_capturing_option_updates();
1512  
1513          return compact( 'instance', 'form' );
1514      }
1515  
1516      /**
1517       * Updates widget settings asynchronously.
1518       *
1519       * Allows the Customizer to update a widget using its form, but return the new
1520       * instance info via Ajax instead of saving it to the options table.
1521       *
1522       * Most code here copied from wp_ajax_save_widget().
1523       *
1524       * @since 3.9.0
1525       *
1526       * @see wp_ajax_save_widget()
1527       */
1528  	public function wp_ajax_update_widget() {
1529  
1530          if ( ! is_user_logged_in() ) {
1531              wp_die( 0 );
1532          }
1533  
1534          check_ajax_referer( 'update-widget', 'nonce' );
1535  
1536          if ( ! current_user_can( 'edit_theme_options' ) ) {
1537              wp_die( -1 );
1538          }
1539  
1540          if ( empty( $_POST['widget-id'] ) ) {
1541              wp_send_json_error( 'missing_widget-id' );
1542          }
1543  
1544          /** This action is documented in wp-admin/includes/ajax-actions.php */
1545          do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
1546  
1547          /** This action is documented in wp-admin/includes/ajax-actions.php */
1548          do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
1549  
1550          /** This action is documented in wp-admin/widgets.php */
1551          do_action( 'sidebar_admin_setup' );
1552  
1553          $widget_id = $this->get_post_value( 'widget-id' );
1554          $parsed_id = $this->parse_widget_id( $widget_id );
1555          $id_base   = $parsed_id['id_base'];
1556  
1557          $is_updating_widget_template = (
1558              isset( $_POST[ 'widget-' . $id_base ] )
1559              &&
1560              is_array( $_POST[ 'widget-' . $id_base ] )
1561              &&
1562              preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
1563          );
1564          if ( $is_updating_widget_template ) {
1565              wp_send_json_error( 'template_widget_not_updatable' );
1566          }
1567  
1568          $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
1569          if ( is_wp_error( $updated_widget ) ) {
1570              wp_send_json_error( $updated_widget->get_error_code() );
1571          }
1572  
1573          $form     = $updated_widget['form'];
1574          $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
1575  
1576          wp_send_json_success( compact( 'form', 'instance' ) );
1577      }
1578  
1579      /*
1580       * Selective Refresh Methods
1581       */
1582  
1583      /**
1584       * Filters arguments for dynamic widget partials.
1585       *
1586       * @since 4.5.0
1587       *
1588       * @param array|false $partial_args Partial arguments.
1589       * @param string      $partial_id   Partial ID.
1590       * @return array (Maybe) modified partial arguments.
1591       */
1592  	public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1593          if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1594              return $partial_args;
1595          }
1596  
1597          if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
1598              if ( false === $partial_args ) {
1599                  $partial_args = array();
1600              }
1601              $partial_args = array_merge(
1602                  $partial_args,
1603                  array(
1604                      'type'                => 'widget',
1605                      'render_callback'     => array( $this, 'render_widget_partial' ),
1606                      'container_inclusive' => true,
1607                      'settings'            => array( $this->get_setting_id( $matches['widget_id'] ) ),
1608                      'capability'          => 'edit_theme_options',
1609                  )
1610              );
1611          }
1612  
1613          return $partial_args;
1614      }
1615  
1616      /**
1617       * Adds hooks for selective refresh.
1618       *
1619       * @since 4.5.0
1620       */
1621  	public function selective_refresh_init() {
1622          if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1623              return;
1624          }
1625          add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
1626          add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
1627          add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
1628          add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
1629      }
1630  
1631      /**
1632       * Inject selective refresh data attributes into widget container elements.
1633       *
1634       * @since 4.5.0
1635       *
1636       * @param array $params {
1637       *     Dynamic sidebar params.
1638       *
1639       *     @type array $args        Sidebar args.
1640       *     @type array $widget_args Widget args.
1641       * }
1642       * @see WP_Customize_Nav_Menus::filter_wp_nav_menu_args()
1643       *
1644       * @return array Params.
1645       */
1646  	public function filter_dynamic_sidebar_params( $params ) {
1647          $sidebar_args = array_merge(
1648              array(
1649                  'before_widget' => '',
1650                  'after_widget'  => '',
1651              ),
1652              $params[0]
1653          );
1654  
1655          // Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
1656          $matches  = array();
1657          $is_valid = (
1658              isset( $sidebar_args['id'] )
1659              &&
1660              is_registered_sidebar( $sidebar_args['id'] )
1661              &&
1662              ( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
1663              &&
1664              preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
1665          );
1666          if ( ! $is_valid ) {
1667              return $params;
1668          }
1669          $this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
1670  
1671          $context = array(
1672              'sidebar_id' => $sidebar_args['id'],
1673          );
1674          if ( isset( $this->context_sidebar_instance_number ) ) {
1675              $context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
1676          } elseif ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
1677              $context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
1678          }
1679  
1680          $attributes                    = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
1681          $attributes                   .= ' data-customize-partial-type="widget"';
1682          $attributes                   .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
1683          $attributes                   .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
1684          $sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
1685  
1686          $params[0] = $sidebar_args;
1687          return $params;
1688      }
1689  
1690      /**
1691       * List of the tag names seen for before_widget strings.
1692       *
1693       * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the
1694       * data-* attributes can be allowed.
1695       *
1696       * @since 4.5.0
1697       * @var array
1698       */
1699      protected $before_widget_tags_seen = array();
1700  
1701      /**
1702       * Ensures the HTML data-* attributes for selective refresh are allowed by kses.
1703       *
1704       * This is needed in case the `$before_widget` is run through wp_kses() when printed.
1705       *
1706       * @since 4.5.0
1707       *
1708       * @param array $allowed_html Allowed HTML.
1709       * @return array (Maybe) modified allowed HTML.
1710       */
1711  	public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
1712          foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
1713              if ( ! isset( $allowed_html[ $tag_name ] ) ) {
1714                  $allowed_html[ $tag_name ] = array();
1715              }
1716              $allowed_html[ $tag_name ] = array_merge(
1717                  $allowed_html[ $tag_name ],
1718                  array_fill_keys(
1719                      array(
1720                          'data-customize-partial-id',
1721                          'data-customize-partial-type',
1722                          'data-customize-partial-placement-context',
1723                          'data-customize-partial-widget-id',
1724                          'data-customize-partial-options',
1725                      ),
1726                      true
1727                  )
1728              );
1729          }
1730          return $allowed_html;
1731      }
1732  
1733      /**
1734       * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index.
1735       *
1736       * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template.
1737       *
1738       * @since 4.5.0
1739       * @var array
1740       */
1741      protected $sidebar_instance_count = array();
1742  
1743      /**
1744       * The current request's sidebar_instance_number context.
1745       *
1746       * @since 4.5.0
1747       * @var int|null
1748       */
1749      protected $context_sidebar_instance_number;
1750  
1751      /**
1752       * Current sidebar ID being rendered.
1753       *
1754       * @since 4.5.0
1755       * @var array
1756       */
1757      protected $current_dynamic_sidebar_id_stack = array();
1758  
1759      /**
1760       * Begins keeping track of the current sidebar being rendered.
1761       *
1762       * Insert marker before widgets are rendered in a dynamic sidebar.
1763       *
1764       * @since 4.5.0
1765       *
1766       * @param int|string $index Index, name, or ID of the dynamic sidebar.
1767       */
1768  	public function start_dynamic_sidebar( $index ) {
1769          array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
1770          if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
1771              $this->sidebar_instance_count[ $index ] = 0;
1772          }
1773          $this->sidebar_instance_count[ $index ] += 1;
1774          if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1775              printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1776          }
1777      }
1778  
1779      /**
1780       * Finishes keeping track of the current sidebar being rendered.
1781       *
1782       * Inserts a marker after widgets are rendered in a dynamic sidebar.
1783       *
1784       * @since 4.5.0
1785       *
1786       * @param int|string $index Index, name, or ID of the dynamic sidebar.
1787       */
1788  	public function end_dynamic_sidebar( $index ) {
1789          array_shift( $this->current_dynamic_sidebar_id_stack );
1790          if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1791              printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1792          }
1793      }
1794  
1795      /**
1796       * Current sidebar being rendered.
1797       *
1798       * @since 4.5.0
1799       * @var string|null
1800       */
1801      protected $rendering_widget_id;
1802  
1803      /**
1804       * Current widget being rendered.
1805       *
1806       * @since 4.5.0
1807       * @var string|null
1808       */
1809      protected $rendering_sidebar_id;
1810  
1811      /**
1812       * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
1813       *
1814       * @since 4.5.0
1815       *
1816       * @param array $sidebars_widgets Sidebars widgets.
1817       * @return array Filtered sidebars widgets.
1818       */
1819  	public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
1820          $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
1821          return $sidebars_widgets;
1822      }
1823  
1824      /**
1825       * Renders a specific widget using the supplied sidebar arguments.
1826       *
1827       * @since 4.5.0
1828       *
1829       * @see dynamic_sidebar()
1830       *
1831       * @param WP_Customize_Partial $partial Partial.
1832       * @param array                $context {
1833       *     Sidebar args supplied as container context.
1834       *
1835       *     @type string $sidebar_id              ID for sidebar for widget to render into.
1836       *     @type int    $sidebar_instance_number Disambiguating instance number.
1837       * }
1838       * @return string|false
1839       */
1840  	public function render_widget_partial( $partial, $context ) {
1841          $id_data   = $partial->id_data();
1842          $widget_id = array_shift( $id_data['keys'] );
1843  
1844          if ( ! is_array( $context )
1845              || empty( $context['sidebar_id'] )
1846              || ! is_registered_sidebar( $context['sidebar_id'] )
1847          ) {
1848              return false;
1849          }
1850  
1851          $this->rendering_sidebar_id = $context['sidebar_id'];
1852  
1853          if ( isset( $context['sidebar_instance_number'] ) ) {
1854              $this->context_sidebar_instance_number = intval( $context['sidebar_instance_number'] );
1855          }
1856  
1857          // Filter sidebars_widgets so that only the queried widget is in the sidebar.
1858          $this->rendering_widget_id = $widget_id;
1859  
1860          $filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
1861          add_filter( 'sidebars_widgets', $filter_callback, 1000 );
1862  
1863          // Render the widget.
1864          ob_start();
1865          $this->rendering_sidebar_id = $context['sidebar_id'];
1866          dynamic_sidebar( $this->rendering_sidebar_id );
1867          $container = ob_get_clean();
1868  
1869          // Reset variables for next partial render.
1870          remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
1871  
1872          $this->context_sidebar_instance_number = null;
1873          $this->rendering_sidebar_id            = null;
1874          $this->rendering_widget_id             = null;
1875  
1876          return $container;
1877      }
1878  
1879      //
1880      // Option Update Capturing.
1881      //
1882  
1883      /**
1884       * List of captured widget option updates.
1885       *
1886       * @since 3.9.0
1887       * @var array $_captured_options Values updated while option capture is happening.
1888       */
1889      protected $_captured_options = array();
1890  
1891      /**
1892       * Whether option capture is currently happening.
1893       *
1894       * @since 3.9.0
1895       * @var bool $_is_current Whether option capture is currently happening or not.
1896       */
1897      protected $_is_capturing_option_updates = false;
1898  
1899      /**
1900       * Determines whether the captured option update should be ignored.
1901       *
1902       * @since 3.9.0
1903       *
1904       * @param string $option_name Option name.
1905       * @return bool Whether the option capture is ignored.
1906       */
1907  	protected function is_option_capture_ignored( $option_name ) {
1908          return ( 0 === strpos( $option_name, '_transient_' ) );
1909      }
1910  
1911      /**
1912       * Retrieves captured widget option updates.
1913       *
1914       * @since 3.9.0
1915       *
1916       * @return array Array of captured options.
1917       */
1918  	protected function get_captured_options() {
1919          return $this->_captured_options;
1920      }
1921  
1922      /**
1923       * Retrieves the option that was captured from being saved.
1924       *
1925       * @since 4.2.0
1926       *
1927       * @param string $option_name Option name.
1928       * @param mixed  $default     Optional. Default value to return if the option does not exist. Default false.
1929       * @return mixed Value set for the option.
1930       */
1931  	protected function get_captured_option( $option_name, $default = false ) {
1932          if ( array_key_exists( $option_name, $this->_captured_options ) ) {
1933              $value = $this->_captured_options[ $option_name ];
1934          } else {
1935              $value = $default;
1936          }
1937          return $value;
1938      }
1939  
1940      /**
1941       * Retrieves the number of captured widget option updates.
1942       *
1943       * @since 3.9.0
1944       *
1945       * @return int Number of updated options.
1946       */
1947  	protected function count_captured_options() {
1948          return count( $this->_captured_options );
1949      }
1950  
1951      /**
1952       * Begins keeping track of changes to widget options, caching new values.
1953       *
1954       * @since 3.9.0
1955       */
1956  	protected function start_capturing_option_updates() {
1957          if ( $this->_is_capturing_option_updates ) {
1958              return;
1959          }
1960  
1961          $this->_is_capturing_option_updates = true;
1962  
1963          add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1964      }
1965  
1966      /**
1967       * Pre-filters captured option values before updating.
1968       *
1969       * @since 3.9.0
1970       *
1971       * @param mixed  $new_value   The new option value.
1972       * @param string $option_name Name of the option.
1973       * @param mixed  $old_value   The old option value.
1974       * @return mixed Filtered option value.
1975       */
1976  	public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
1977          if ( $this->is_option_capture_ignored( $option_name ) ) {
1978              return $new_value;
1979          }
1980  
1981          if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
1982              add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1983          }
1984  
1985          $this->_captured_options[ $option_name ] = $new_value;
1986  
1987          return $old_value;
1988      }
1989  
1990      /**
1991       * Pre-filters captured option values before retrieving.
1992       *
1993       * @since 3.9.0
1994       *
1995       * @param mixed $value Value to return instead of the option value.
1996       * @return mixed Filtered option value.
1997       */
1998  	public function capture_filter_pre_get_option( $value ) {
1999          $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
2000  
2001          if ( isset( $this->_captured_options[ $option_name ] ) ) {
2002              $value = $this->_captured_options[ $option_name ];
2003  
2004              /** This filter is documented in wp-includes/option.php */
2005              $value = apply_filters( 'option_' . $option_name, $value, $option_name );
2006          }
2007  
2008          return $value;
2009      }
2010  
2011      /**
2012       * Undoes any changes to the options since options capture began.
2013       *
2014       * @since 3.9.0
2015       */
2016  	protected function stop_capturing_option_updates() {
2017          if ( ! $this->_is_capturing_option_updates ) {
2018              return;
2019          }
2020  
2021          remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
2022  
2023          foreach ( array_keys( $this->_captured_options ) as $option_name ) {
2024              remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
2025          }
2026  
2027          $this->_captured_options            = array();
2028          $this->_is_capturing_option_updates = false;
2029      }
2030  
2031      /**
2032       * {@internal Missing Summary}
2033       *
2034       * See the {@see 'customize_dynamic_setting_args'} filter.
2035       *
2036       * @since 3.9.0
2037       * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2038       */
2039  	public function setup_widget_addition_previews() {
2040          _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
2041      }
2042  
2043      /**
2044       * {@internal Missing Summary}
2045       *
2046       * See the {@see 'customize_dynamic_setting_args'} filter.
2047       *
2048       * @since 3.9.0
2049       * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2050       */
2051  	public function prepreview_added_sidebars_widgets() {
2052          _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
2053      }
2054  
2055      /**
2056       * {@internal Missing Summary}
2057       *
2058       * See the {@see 'customize_dynamic_setting_args'} filter.
2059       *
2060       * @since 3.9.0
2061       * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2062       */
2063  	public function prepreview_added_widget_instance() {
2064          _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
2065      }
2066  
2067      /**
2068       * {@internal Missing Summary}
2069       *
2070       * See the {@see 'customize_dynamic_setting_args'} filter.
2071       *
2072       * @since 3.9.0
2073       * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2074       */
2075  	public function remove_prepreview_filters() {
2076          _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
2077      }
2078  }


Generated: Thu Jul 16 01:00:03 2020 Cross-referenced by PHPXref 0.7.1