]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-customize-widgets.php
WordPress 4.7.1
[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                 $switched_locale = switch_to_locale( get_user_locale() );
1127                 $l10n = array(
1128                         'widgetTooltip'  => __( 'Shift-click to edit this widget.' ),
1129                 );
1130                 if ( $switched_locale ) {
1131                         restore_previous_locale();
1132                 }
1133
1134                 // Prepare Customizer settings to pass to JavaScript.
1135                 $settings = array(
1136                         'renderedSidebars'   => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
1137                         'renderedWidgets'    => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
1138                         'registeredSidebars' => array_values( $wp_registered_sidebars ),
1139                         'registeredWidgets'  => $wp_registered_widgets,
1140                         'l10n'               => $l10n,
1141                         'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
1142                 );
1143                 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
1144                         unset( $registered_widget['callback'] ); // may not be JSON-serializeable
1145                 }
1146
1147                 ?>
1148                 <script type="text/javascript">
1149                         var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
1150                 </script>
1151                 <?php
1152         }
1153
1154         /**
1155          * Tracks the widgets that were rendered.
1156          *
1157          * @since 3.9.0
1158          * @access public
1159          *
1160          * @param array $widget Rendered widget to tally.
1161          */
1162         public function tally_rendered_widgets( $widget ) {
1163                 $this->rendered_widgets[ $widget['id'] ] = true;
1164         }
1165
1166         /**
1167          * Determine if a widget is rendered on the page.
1168          *
1169          * @since 4.0.0
1170          * @access public
1171          *
1172          * @param string $widget_id Widget ID to check.
1173          * @return bool Whether the widget is rendered.
1174          */
1175         public function is_widget_rendered( $widget_id ) {
1176                 return in_array( $widget_id, $this->rendered_widgets );
1177         }
1178
1179         /**
1180          * Determines if a sidebar is rendered on the page.
1181          *
1182          * @since 4.0.0
1183          * @access public
1184          *
1185          * @param string $sidebar_id Sidebar ID to check.
1186          * @return bool Whether the sidebar is rendered.
1187          */
1188         public function is_sidebar_rendered( $sidebar_id ) {
1189                 return in_array( $sidebar_id, $this->rendered_sidebars );
1190         }
1191
1192         /**
1193          * Tallies the sidebars rendered via is_active_sidebar().
1194          *
1195          * Keep track of the times that is_active_sidebar() is called in the template,
1196          * and assume that this means that the sidebar would be rendered on the template
1197          * if there were widgets populating it.
1198          *
1199          * @since 3.9.0
1200          * @access public
1201          *
1202          * @param bool   $is_active  Whether the sidebar is active.
1203          * @param string $sidebar_id Sidebar ID.
1204          * @return bool Whether the sidebar is active.
1205          */
1206         public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
1207                 if ( is_registered_sidebar( $sidebar_id ) ) {
1208                         $this->rendered_sidebars[] = $sidebar_id;
1209                 }
1210                 /*
1211                  * We may need to force this to true, and also force-true the value
1212                  * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
1213                  * is an area to drop widgets into, if the sidebar is empty.
1214                  */
1215                 return $is_active;
1216         }
1217
1218         /**
1219          * Tallies the sidebars rendered via dynamic_sidebar().
1220          *
1221          * Keep track of the times that dynamic_sidebar() is called in the template,
1222          * and assume this means the sidebar would be rendered on the template if
1223          * there were widgets populating it.
1224          *
1225          * @since 3.9.0
1226          * @access public
1227          *
1228          * @param bool   $has_widgets Whether the current sidebar has widgets.
1229          * @param string $sidebar_id  Sidebar ID.
1230          * @return bool Whether the current sidebar has widgets.
1231          */
1232         public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
1233                 if ( is_registered_sidebar( $sidebar_id ) ) {
1234                         $this->rendered_sidebars[] = $sidebar_id;
1235                 }
1236
1237                 /*
1238                  * We may need to force this to true, and also force-true the value
1239                  * for 'is_active_sidebar' if we want to ensure there is an area to
1240                  * drop widgets into, if the sidebar is empty.
1241                  */
1242                 return $has_widgets;
1243         }
1244
1245         /**
1246          * Retrieves MAC for a serialized widget instance string.
1247          *
1248          * Allows values posted back from JS to be rejected if any tampering of the
1249          * data has occurred.
1250          *
1251          * @since 3.9.0
1252          * @access protected
1253          *
1254          * @param string $serialized_instance Widget instance.
1255          * @return string MAC for serialized widget instance.
1256          */
1257         protected function get_instance_hash_key( $serialized_instance ) {
1258                 return wp_hash( $serialized_instance );
1259         }
1260
1261         /**
1262          * Sanitizes a widget instance.
1263          *
1264          * Unserialize the JS-instance for storing in the options. It's important that this filter
1265          * only get applied to an instance *once*.
1266          *
1267          * @since 3.9.0
1268          * @access public
1269          *
1270          * @param array $value Widget instance to sanitize.
1271          * @return array|void Sanitized widget instance.
1272          */
1273         public function sanitize_widget_instance( $value ) {
1274                 if ( $value === array() ) {
1275                         return $value;
1276                 }
1277
1278                 if ( empty( $value['is_widget_customizer_js_value'] )
1279                         || empty( $value['instance_hash_key'] )
1280                         || empty( $value['encoded_serialized_instance'] ) )
1281                 {
1282                         return;
1283                 }
1284
1285                 $decoded = base64_decode( $value['encoded_serialized_instance'], true );
1286                 if ( false === $decoded ) {
1287                         return;
1288                 }
1289
1290                 if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
1291                         return;
1292                 }
1293
1294                 $instance = unserialize( $decoded );
1295                 if ( false === $instance ) {
1296                         return;
1297                 }
1298
1299                 return $instance;
1300         }
1301
1302         /**
1303          * Converts a widget instance into JSON-representable format.
1304          *
1305          * @since 3.9.0
1306          * @access public
1307          *
1308          * @param array $value Widget instance to convert to JSON.
1309          * @return array JSON-converted widget instance.
1310          */
1311         public function sanitize_widget_js_instance( $value ) {
1312                 if ( empty( $value['is_widget_customizer_js_value'] ) ) {
1313                         $serialized = serialize( $value );
1314
1315                         $value = array(
1316                                 'encoded_serialized_instance'   => base64_encode( $serialized ),
1317                                 'title'                         => empty( $value['title'] ) ? '' : $value['title'],
1318                                 'is_widget_customizer_js_value' => true,
1319                                 'instance_hash_key'             => $this->get_instance_hash_key( $serialized ),
1320                         );
1321                 }
1322                 return $value;
1323         }
1324
1325         /**
1326          * Strips out widget IDs for widgets which are no longer registered.
1327          *
1328          * One example where this might happen is when a plugin orphans a widget
1329          * in a sidebar upon deactivation.
1330          *
1331          * @since 3.9.0
1332          * @access public
1333          *
1334          * @global array $wp_registered_widgets
1335          *
1336          * @param array $widget_ids List of widget IDs.
1337          * @return array Parsed list of widget IDs.
1338          */
1339         public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
1340                 global $wp_registered_widgets;
1341                 $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
1342                 return $widget_ids;
1343         }
1344
1345         /**
1346          * Finds and invokes the widget update and control callbacks.
1347          *
1348          * Requires that `$_POST` be populated with the instance data.
1349          *
1350          * @since 3.9.0
1351          * @access public
1352          *
1353          * @global array $wp_registered_widget_updates
1354          * @global array $wp_registered_widget_controls
1355          *
1356          * @param  string $widget_id Widget ID.
1357          * @return WP_Error|array Array containing the updated widget information.
1358          *                        A WP_Error object, otherwise.
1359          */
1360         public function call_widget_update( $widget_id ) {
1361                 global $wp_registered_widget_updates, $wp_registered_widget_controls;
1362
1363                 $setting_id = $this->get_setting_id( $widget_id );
1364
1365                 /*
1366                  * Make sure that other setting changes have previewed since this widget
1367                  * may depend on them (e.g. Menus being present for Custom Menu widget).
1368                  */
1369                 if ( ! did_action( 'customize_preview_init' ) ) {
1370                         foreach ( $this->manager->settings() as $setting ) {
1371                                 if ( $setting->id !== $setting_id ) {
1372                                         $setting->preview();
1373                                 }
1374                         }
1375                 }
1376
1377                 $this->start_capturing_option_updates();
1378                 $parsed_id   = $this->parse_widget_id( $widget_id );
1379                 $option_name = 'widget_' . $parsed_id['id_base'];
1380
1381                 /*
1382                  * If a previously-sanitized instance is provided, populate the input vars
1383                  * with its values so that the widget update callback will read this instance
1384                  */
1385                 $added_input_vars = array();
1386                 if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
1387                         $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
1388                         if ( false === $sanitized_widget_setting ) {
1389                                 $this->stop_capturing_option_updates();
1390                                 return new WP_Error( 'widget_setting_malformed' );
1391                         }
1392
1393                         $instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
1394                         if ( is_null( $instance ) ) {
1395                                 $this->stop_capturing_option_updates();
1396                                 return new WP_Error( 'widget_setting_unsanitized' );
1397                         }
1398
1399                         if ( ! is_null( $parsed_id['number'] ) ) {
1400                                 $value = array();
1401                                 $value[$parsed_id['number']] = $instance;
1402                                 $key = 'widget-' . $parsed_id['id_base'];
1403                                 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1404                                 $added_input_vars[] = $key;
1405                         } else {
1406                                 foreach ( $instance as $key => $value ) {
1407                                         $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1408                                         $added_input_vars[] = $key;
1409                                 }
1410                         }
1411                 }
1412
1413                 // Invoke the widget update callback.
1414                 foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
1415                         if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
1416                                 ob_start();
1417                                 call_user_func_array( $control['callback'], $control['params'] );
1418                                 ob_end_clean();
1419                                 break;
1420                         }
1421                 }
1422
1423                 // Clean up any input vars that were manually added
1424                 foreach ( $added_input_vars as $key ) {
1425                         unset( $_POST[ $key ] );
1426                         unset( $_REQUEST[ $key ] );
1427                 }
1428
1429                 // Make sure the expected option was updated.
1430                 if ( 0 !== $this->count_captured_options() ) {
1431                         if ( $this->count_captured_options() > 1 ) {
1432                                 $this->stop_capturing_option_updates();
1433                                 return new WP_Error( 'widget_setting_too_many_options' );
1434                         }
1435
1436                         $updated_option_name = key( $this->get_captured_options() );
1437                         if ( $updated_option_name !== $option_name ) {
1438                                 $this->stop_capturing_option_updates();
1439                                 return new WP_Error( 'widget_setting_unexpected_option' );
1440                         }
1441                 }
1442
1443                 // Obtain the widget instance.
1444                 $option = $this->get_captured_option( $option_name );
1445                 if ( null !== $parsed_id['number'] ) {
1446                         $instance = $option[ $parsed_id['number'] ];
1447                 } else {
1448                         $instance = $option;
1449                 }
1450
1451                 /*
1452                  * Override the incoming $_POST['customized'] for a newly-created widget's
1453                  * setting with the new $instance so that the preview filter currently
1454                  * in place from WP_Customize_Setting::preview() will use this value
1455                  * instead of the default widget instance value (an empty array).
1456                  */
1457                 $this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance ) );
1458
1459                 // Obtain the widget control with the updated instance in place.
1460                 ob_start();
1461                 $form = $wp_registered_widget_controls[ $widget_id ];
1462                 if ( $form ) {
1463                         call_user_func_array( $form['callback'], $form['params'] );
1464                 }
1465                 $form = ob_get_clean();
1466
1467                 $this->stop_capturing_option_updates();
1468
1469                 return compact( 'instance', 'form' );
1470         }
1471
1472         /**
1473          * Updates widget settings asynchronously.
1474          *
1475          * Allows the Customizer to update a widget using its form, but return the new
1476          * instance info via Ajax instead of saving it to the options table.
1477          *
1478          * Most code here copied from wp_ajax_save_widget().
1479          *
1480          * @since 3.9.0
1481          * @access public
1482          *
1483          * @see wp_ajax_save_widget()
1484          */
1485         public function wp_ajax_update_widget() {
1486
1487                 if ( ! is_user_logged_in() ) {
1488                         wp_die( 0 );
1489                 }
1490
1491                 check_ajax_referer( 'update-widget', 'nonce' );
1492
1493                 if ( ! current_user_can( 'edit_theme_options' ) ) {
1494                         wp_die( -1 );
1495                 }
1496
1497                 if ( empty( $_POST['widget-id'] ) ) {
1498                         wp_send_json_error( 'missing_widget-id' );
1499                 }
1500
1501                 /** This action is documented in wp-admin/includes/ajax-actions.php */
1502                 do_action( 'load-widgets.php' );
1503
1504                 /** This action is documented in wp-admin/includes/ajax-actions.php */
1505                 do_action( 'widgets.php' );
1506
1507                 /** This action is documented in wp-admin/widgets.php */
1508                 do_action( 'sidebar_admin_setup' );
1509
1510                 $widget_id = $this->get_post_value( 'widget-id' );
1511                 $parsed_id = $this->parse_widget_id( $widget_id );
1512                 $id_base = $parsed_id['id_base'];
1513
1514                 $is_updating_widget_template = (
1515                         isset( $_POST[ 'widget-' . $id_base ] )
1516                         &&
1517                         is_array( $_POST[ 'widget-' . $id_base ] )
1518                         &&
1519                         preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
1520                 );
1521                 if ( $is_updating_widget_template ) {
1522                         wp_send_json_error( 'template_widget_not_updatable' );
1523                 }
1524
1525                 $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
1526                 if ( is_wp_error( $updated_widget ) ) {
1527                         wp_send_json_error( $updated_widget->get_error_code() );
1528                 }
1529
1530                 $form = $updated_widget['form'];
1531                 $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
1532
1533                 wp_send_json_success( compact( 'form', 'instance' ) );
1534         }
1535
1536         /*
1537          * Selective Refresh Methods
1538          */
1539
1540         /**
1541          * Filters arguments for dynamic widget partials.
1542          *
1543          * @since 4.5.0
1544          * @access public
1545          *
1546          * @param array|false $partial_args Partial arguments.
1547          * @param string      $partial_id   Partial ID.
1548          * @return array (Maybe) modified partial arguments.
1549          */
1550         public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1551                 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1552                         return $partial_args;
1553                 }
1554
1555                 if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
1556                         if ( false === $partial_args ) {
1557                                 $partial_args = array();
1558                         }
1559                         $partial_args = array_merge(
1560                                 $partial_args,
1561                                 array(
1562                                         'type'                => 'widget',
1563                                         'render_callback'     => array( $this, 'render_widget_partial' ),
1564                                         'container_inclusive' => true,
1565                                         'settings'            => array( $this->get_setting_id( $matches['widget_id'] ) ),
1566                                         'capability'          => 'edit_theme_options',
1567                                 )
1568                         );
1569                 }
1570
1571                 return $partial_args;
1572         }
1573
1574         /**
1575          * Adds hooks for selective refresh.
1576          *
1577          * @since 4.5.0
1578          * @access public
1579          */
1580         public function selective_refresh_init() {
1581                 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1582                         return;
1583                 }
1584                 add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
1585                 add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
1586                 add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
1587                 add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
1588         }
1589
1590         /**
1591          * Inject selective refresh data attributes into widget container elements.
1592          *
1593          * @param array $params {
1594          *     Dynamic sidebar params.
1595          *
1596          *     @type array $args        Sidebar args.
1597          *     @type array $widget_args Widget args.
1598          * }
1599          * @see WP_Customize_Nav_Menus_Partial_Refresh::filter_wp_nav_menu_args()
1600          *
1601          * @return array Params.
1602          */
1603         public function filter_dynamic_sidebar_params( $params ) {
1604                 $sidebar_args = array_merge(
1605                         array(
1606                                 'before_widget' => '',
1607                                 'after_widget' => '',
1608                         ),
1609                         $params[0]
1610                 );
1611
1612                 // Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
1613                 $matches = array();
1614                 $is_valid = (
1615                         isset( $sidebar_args['id'] )
1616                         &&
1617                         is_registered_sidebar( $sidebar_args['id'] )
1618                         &&
1619                         ( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
1620                         &&
1621                         preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
1622                 );
1623                 if ( ! $is_valid ) {
1624                         return $params;
1625                 }
1626                 $this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
1627
1628                 $context = array(
1629                         'sidebar_id' => $sidebar_args['id'],
1630                 );
1631                 if ( isset( $this->context_sidebar_instance_number ) ) {
1632                         $context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
1633                 } else if ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
1634                         $context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
1635                 }
1636
1637                 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
1638                 $attributes .= ' data-customize-partial-type="widget"';
1639                 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
1640                 $attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
1641                 $sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
1642
1643                 $params[0] = $sidebar_args;
1644                 return $params;
1645         }
1646
1647         /**
1648          * List of the tag names seen for before_widget strings.
1649          *
1650          * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the
1651          * data-* attributes can be whitelisted.
1652          *
1653          * @since 4.5.0
1654          * @access protected
1655          * @var array
1656          */
1657         protected $before_widget_tags_seen = array();
1658
1659         /**
1660          * Ensures the HTML data-* attributes for selective refresh are allowed by kses.
1661          *
1662          * This is needed in case the `$before_widget` is run through wp_kses() when printed.
1663          *
1664          * @since 4.5.0
1665          * @access public
1666          *
1667          * @param array $allowed_html Allowed HTML.
1668          * @return array (Maybe) modified allowed HTML.
1669          */
1670         public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
1671                 foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
1672                         if ( ! isset( $allowed_html[ $tag_name ] ) ) {
1673                                 $allowed_html[ $tag_name ] = array();
1674                         }
1675                         $allowed_html[ $tag_name ] = array_merge(
1676                                 $allowed_html[ $tag_name ],
1677                                 array_fill_keys( array(
1678                                         'data-customize-partial-id',
1679                                         'data-customize-partial-type',
1680                                         'data-customize-partial-placement-context',
1681                                         'data-customize-partial-widget-id',
1682                                         'data-customize-partial-options',
1683                                 ), true )
1684                         );
1685                 }
1686                 return $allowed_html;
1687         }
1688
1689         /**
1690          * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index.
1691          *
1692          * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template.
1693          *
1694          * @since 4.5.0
1695          * @access protected
1696          * @var array
1697          */
1698         protected $sidebar_instance_count = array();
1699
1700         /**
1701          * The current request's sidebar_instance_number context.
1702          *
1703          * @since 4.5.0
1704          * @access protected
1705          * @var int
1706          */
1707         protected $context_sidebar_instance_number;
1708
1709         /**
1710          * Current sidebar ID being rendered.
1711          *
1712          * @since 4.5.0
1713          * @access protected
1714          * @var array
1715          */
1716         protected $current_dynamic_sidebar_id_stack = array();
1717
1718         /**
1719          * Begins keeping track of the current sidebar being rendered.
1720          *
1721          * Insert marker before widgets are rendered in a dynamic sidebar.
1722          *
1723          * @since 4.5.0
1724          * @access public
1725          *
1726          * @param int|string $index Index, name, or ID of the dynamic sidebar.
1727          */
1728         public function start_dynamic_sidebar( $index ) {
1729                 array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
1730                 if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
1731                         $this->sidebar_instance_count[ $index ] = 0;
1732                 }
1733                 $this->sidebar_instance_count[ $index ] += 1;
1734                 if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1735                         printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1736                 }
1737         }
1738
1739         /**
1740          * Finishes keeping track of the current sidebar being rendered.
1741          *
1742          * Inserts a marker after widgets are rendered in a dynamic sidebar.
1743          *
1744          * @since 4.5.0
1745          * @access public
1746          *
1747          * @param int|string $index Index, name, or ID of the dynamic sidebar.
1748          */
1749         public function end_dynamic_sidebar( $index ) {
1750                 array_shift( $this->current_dynamic_sidebar_id_stack );
1751                 if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1752                         printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1753                 }
1754         }
1755
1756         /**
1757          * Current sidebar being rendered.
1758          *
1759          * @since 4.5.0
1760          * @access protected
1761          * @var string
1762          */
1763         protected $rendering_widget_id;
1764
1765         /**
1766          * Current widget being rendered.
1767          *
1768          * @since 4.5.0
1769          * @access protected
1770          * @var string
1771          */
1772         protected $rendering_sidebar_id;
1773
1774         /**
1775          * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
1776          *
1777          * @since 4.5.0
1778          * @access protected
1779          *
1780          * @param array $sidebars_widgets Sidebars widgets.
1781          * @return array Filtered sidebars widgets.
1782          */
1783         public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
1784                 $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
1785                 return $sidebars_widgets;
1786         }
1787
1788         /**
1789          * Renders a specific widget using the supplied sidebar arguments.
1790          *
1791          * @since 4.5.0
1792          * @access public
1793          *
1794          * @see dynamic_sidebar()
1795          *
1796          * @param WP_Customize_Partial $partial Partial.
1797          * @param array                $context {
1798          *     Sidebar args supplied as container context.
1799          *
1800          *     @type string $sidebar_id              ID for sidebar for widget to render into.
1801          *     @type int    $sidebar_instance_number Disambiguating instance number.
1802          * }
1803          * @return string|false
1804          */
1805         public function render_widget_partial( $partial, $context ) {
1806                 $id_data   = $partial->id_data();
1807                 $widget_id = array_shift( $id_data['keys'] );
1808
1809                 if ( ! is_array( $context )
1810                         || empty( $context['sidebar_id'] )
1811                         || ! is_registered_sidebar( $context['sidebar_id'] )
1812                 ) {
1813                         return false;
1814                 }
1815
1816                 $this->rendering_sidebar_id = $context['sidebar_id'];
1817
1818                 if ( isset( $context['sidebar_instance_number'] ) ) {
1819                         $this->context_sidebar_instance_number = intval( $context['sidebar_instance_number'] );
1820                 }
1821
1822                 // Filter sidebars_widgets so that only the queried widget is in the sidebar.
1823                 $this->rendering_widget_id = $widget_id;
1824
1825                 $filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
1826                 add_filter( 'sidebars_widgets', $filter_callback, 1000 );
1827
1828                 // Render the widget.
1829                 ob_start();
1830                 dynamic_sidebar( $this->rendering_sidebar_id = $context['sidebar_id'] );
1831                 $container = ob_get_clean();
1832
1833                 // Reset variables for next partial render.
1834                 remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
1835
1836                 $this->context_sidebar_instance_number = null;
1837                 $this->rendering_sidebar_id = null;
1838                 $this->rendering_widget_id = null;
1839
1840                 return $container;
1841         }
1842
1843         //
1844         // Option Update Capturing
1845         //
1846
1847         /**
1848          * List of captured widget option updates.
1849          *
1850          * @since 3.9.0
1851          * @access protected
1852          * @var array $_captured_options Values updated while option capture is happening.
1853          */
1854         protected $_captured_options = array();
1855
1856         /**
1857          * Whether option capture is currently happening.
1858          *
1859          * @since 3.9.0
1860          * @access protected
1861          * @var bool $_is_current Whether option capture is currently happening or not.
1862          */
1863         protected $_is_capturing_option_updates = false;
1864
1865         /**
1866          * Determines whether the captured option update should be ignored.
1867          *
1868          * @since 3.9.0
1869          * @access protected
1870          *
1871          * @param string $option_name Option name.
1872          * @return bool Whether the option capture is ignored.
1873          */
1874         protected function is_option_capture_ignored( $option_name ) {
1875                 return ( 0 === strpos( $option_name, '_transient_' ) );
1876         }
1877
1878         /**
1879          * Retrieves captured widget option updates.
1880          *
1881          * @since 3.9.0
1882          * @access protected
1883          *
1884          * @return array Array of captured options.
1885          */
1886         protected function get_captured_options() {
1887                 return $this->_captured_options;
1888         }
1889
1890         /**
1891          * Retrieves the option that was captured from being saved.
1892          *
1893          * @since 4.2.0
1894          * @access protected
1895          *
1896          * @param string $option_name Option name.
1897          * @param mixed  $default     Optional. Default value to return if the option does not exist. Default false.
1898          * @return mixed Value set for the option.
1899          */
1900         protected function get_captured_option( $option_name, $default = false ) {
1901                 if ( array_key_exists( $option_name, $this->_captured_options ) ) {
1902                         $value = $this->_captured_options[ $option_name ];
1903                 } else {
1904                         $value = $default;
1905                 }
1906                 return $value;
1907         }
1908
1909         /**
1910          * Retrieves the number of captured widget option updates.
1911          *
1912          * @since 3.9.0
1913          * @access protected
1914          *
1915          * @return int Number of updated options.
1916          */
1917         protected function count_captured_options() {
1918                 return count( $this->_captured_options );
1919         }
1920
1921         /**
1922          * Begins keeping track of changes to widget options, caching new values.
1923          *
1924          * @since 3.9.0
1925          * @access protected
1926          */
1927         protected function start_capturing_option_updates() {
1928                 if ( $this->_is_capturing_option_updates ) {
1929                         return;
1930                 }
1931
1932                 $this->_is_capturing_option_updates = true;
1933
1934                 add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1935         }
1936
1937         /**
1938          * Pre-filters captured option values before updating.
1939          *
1940          * @since 3.9.0
1941          * @access public
1942          *
1943          * @param mixed  $new_value   The new option value.
1944          * @param string $option_name Name of the option.
1945          * @param mixed  $old_value   The old option value.
1946          * @return mixed Filtered option value.
1947          */
1948         public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
1949                 if ( $this->is_option_capture_ignored( $option_name ) ) {
1950                         return;
1951                 }
1952
1953                 if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
1954                         add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1955                 }
1956
1957                 $this->_captured_options[ $option_name ] = $new_value;
1958
1959                 return $old_value;
1960         }
1961
1962         /**
1963          * Pre-filters captured option values before retrieving.
1964          *
1965          * @since 3.9.0
1966          * @access public
1967          *
1968          * @param mixed $value Value to return instead of the option value.
1969          * @return mixed Filtered option value.
1970          */
1971         public function capture_filter_pre_get_option( $value ) {
1972                 $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
1973
1974                 if ( isset( $this->_captured_options[ $option_name ] ) ) {
1975                         $value = $this->_captured_options[ $option_name ];
1976
1977                         /** This filter is documented in wp-includes/option.php */
1978                         $value = apply_filters( 'option_' . $option_name, $value );
1979                 }
1980
1981                 return $value;
1982         }
1983
1984         /**
1985          * Undoes any changes to the options since options capture began.
1986          *
1987          * @since 3.9.0
1988          * @access protected
1989          */
1990         protected function stop_capturing_option_updates() {
1991                 if ( ! $this->_is_capturing_option_updates ) {
1992                         return;
1993                 }
1994
1995                 remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
1996
1997                 foreach ( array_keys( $this->_captured_options ) as $option_name ) {
1998                         remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1999                 }
2000
2001                 $this->_captured_options = array();
2002                 $this->_is_capturing_option_updates = false;
2003         }
2004
2005         /**
2006          * {@internal Missing Summary}
2007          *
2008          * See the {@see 'customize_dynamic_setting_args'} filter.
2009          *
2010          * @since 3.9.0
2011          * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2012          */
2013         public function setup_widget_addition_previews() {
2014                 _deprecated_function( __METHOD__, '4.2.0' );
2015         }
2016
2017         /**
2018          * {@internal Missing Summary}
2019          *
2020          * See the {@see 'customize_dynamic_setting_args'} filter.
2021          *
2022          * @since 3.9.0
2023          * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2024          */
2025         public function prepreview_added_sidebars_widgets() {
2026                 _deprecated_function( __METHOD__, '4.2.0' );
2027         }
2028
2029         /**
2030          * {@internal Missing Summary}
2031          *
2032          * See the {@see 'customize_dynamic_setting_args'} filter.
2033          *
2034          * @since 3.9.0
2035          * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2036          */
2037         public function prepreview_added_widget_instance() {
2038                 _deprecated_function( __METHOD__, '4.2.0' );
2039         }
2040
2041         /**
2042          * {@internal Missing Summary}
2043          *
2044          * See the {@see 'customize_dynamic_setting_args'} filter.
2045          *
2046          * @since 3.9.0
2047          * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2048          */
2049         public function remove_prepreview_filters() {
2050                 _deprecated_function( __METHOD__, '4.2.0' );
2051         }
2052 }