[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Tue Jun 30 08:20:12 2026 Cross-referenced by PHPXref