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