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


Generated: Mon Jun 21 01:00:04 2021 Cross-referenced by PHPXref 0.7.1