]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-customize-widgets.php
WordPress 4.1.1
[autoinstalls/wordpress.git] / wp-includes / class-wp-customize-widgets.php
1 <?php
2 /**
3  * Customize Widgets Class
4  *
5  * Implements widget management in the Customizer.
6  *
7  * @package WordPress
8  * @subpackage Customize
9  * @since 3.9.0
10  */
11 final class WP_Customize_Widgets {
12
13         /**
14          * WP_Customize_Manager instance.
15          *
16          * @since 3.9.0
17          * @access public
18          * @var WP_Customize_Manager
19          */
20         public $manager;
21
22         /**
23          * All id_bases for widgets defined in core.
24          *
25          * @since 3.9.0
26          * @access protected
27          * @var array
28          */
29         protected $core_widget_id_bases = array(
30                 'archives', 'calendar', 'categories', 'links', 'meta',
31                 'nav_menu', 'pages', 'recent-comments', 'recent-posts',
32                 'rss', 'search', 'tag_cloud', 'text',
33         );
34
35         /**
36          * @since 3.9.0
37          * @access protected
38          * @var
39          */
40         protected $_customized;
41
42         /**
43          * @since 3.9.0
44          * @access protected
45          * @var array
46          */
47         protected $_prepreview_added_filters = array();
48
49         /**
50          * @since 3.9.0
51          * @access protected
52          * @var array
53          */
54         protected $rendered_sidebars = array();
55
56         /**
57          * @since 3.9.0
58          * @access protected
59          * @var array
60          */
61         protected $rendered_widgets = array();
62
63         /**
64          * @since 3.9.0
65          * @access protected
66          * @var array
67          */
68         protected $old_sidebars_widgets = array();
69
70         /**
71          * Initial loader.
72          *
73          * @since 3.9.0
74          * @access public
75          *
76          * @param WP_Customize_Manager $manager Customize manager bootstrap instance.
77          */
78         public function __construct( $manager ) {
79                 $this->manager = $manager;
80
81                 add_action( 'after_setup_theme',                       array( $this, 'setup_widget_addition_previews' ) );
82                 add_action( 'wp_loaded',                               array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
83                 add_action( 'customize_controls_init',                 array( $this, 'customize_controls_init' ) );
84                 add_action( 'customize_register',                      array( $this, 'schedule_customize_register' ), 1 );
85                 add_action( 'customize_controls_enqueue_scripts',      array( $this, 'enqueue_scripts' ) );
86                 add_action( 'customize_controls_print_styles',         array( $this, 'print_styles' ) );
87                 add_action( 'customize_controls_print_scripts',        array( $this, 'print_scripts' ) );
88                 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
89                 add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
90                 add_action( 'customize_preview_init',                  array( $this, 'customize_preview_init' ) );
91
92                 add_action( 'dynamic_sidebar',                         array( $this, 'tally_rendered_widgets' ) );
93                 add_filter( 'is_active_sidebar',                       array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
94                 add_filter( 'dynamic_sidebar_has_widgets',             array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
95         }
96
97         /**
98          * Get an unslashed post value or return a default.
99          *
100          * @since 3.9.0
101          *
102          * @access protected
103          *
104          * @param string $name    Post value.
105          * @param mixed  $default Default post value.
106          * @return mixed Unslashed post value or default value.
107          */
108         protected function get_post_value( $name, $default = null ) {
109                 if ( ! isset( $_POST[ $name ] ) ) {
110                         return $default;
111                 }
112
113                 return wp_unslash( $_POST[$name] );
114         }
115
116         /**
117          * Set up widget addition previews.
118          *
119          * Since the widgets get registered on 'widgets_init' before the Customizer
120          * settings are set up on 'customize_register', we have to filter the options
121          * similarly to how the setting previewer will filter the options later.
122          *
123          * @since 3.9.0
124          *
125          * @access public
126          */
127         public function setup_widget_addition_previews() {
128                 $is_customize_preview = false;
129
130                 if ( ! empty( $this->manager ) && ! is_admin() && 'on' === $this->get_post_value( 'wp_customize' ) ) {
131                         $is_customize_preview = check_ajax_referer( 'preview-customize_' . $this->manager->get_stylesheet(), 'nonce', false );
132                 }
133
134                 $is_ajax_widget_update = false;
135                 if ( $this->manager->doing_ajax() && 'update-widget' === $this->get_post_value( 'action' ) ) {
136                         $is_ajax_widget_update = check_ajax_referer( 'update-widget', 'nonce', false );
137                 }
138
139                 $is_ajax_customize_save = false;
140                 if ( $this->manager->doing_ajax() && 'customize_save' === $this->get_post_value( 'action' ) ) {
141                         $is_ajax_customize_save = check_ajax_referer( 'save-customize_' . $this->manager->get_stylesheet(), 'nonce', false );
142                 }
143
144                 $is_valid_request = ( $is_ajax_widget_update || $is_customize_preview || $is_ajax_customize_save );
145                 if ( ! $is_valid_request ) {
146                         return;
147                 }
148
149                 // Input from Customizer preview.
150                 if ( isset( $_POST['customized'] ) ) {
151                         $this->_customized = json_decode( $this->get_post_value( 'customized' ), true );
152                 } else { // Input from ajax widget update request.
153                         $this->_customized = array();
154                         $id_base = $this->get_post_value( 'id_base' );
155                         $widget_number = $this->get_post_value( 'widget_number', false );
156                         $option_name = 'widget_' . $id_base;
157                         $this->_customized[ $option_name ] = array();
158                         if ( preg_match( '/^[0-9]+$/', $widget_number ) ) {
159                                 $option_name .= '[' . $widget_number . ']';
160                                 $this->_customized[ $option_name ][ $widget_number ] = array();
161                         }
162                 }
163
164                 $function = array( $this, 'prepreview_added_sidebars_widgets' );
165
166                 $hook = 'option_sidebars_widgets';
167                 add_filter( $hook, $function );
168                 $this->_prepreview_added_filters[] = compact( 'hook', 'function' );
169
170                 $hook = 'default_option_sidebars_widgets';
171                 add_filter( $hook, $function );
172                 $this->_prepreview_added_filters[] = compact( 'hook', 'function' );
173
174                 $function = array( $this, 'prepreview_added_widget_instance' );
175                 foreach ( $this->_customized as $setting_id => $value ) {
176                         if ( preg_match( '/^(widget_.+?)(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
177                                 $option = $matches[1];
178
179                                 $hook = sprintf( 'option_%s', $option );
180                                 if ( ! has_filter( $hook, $function ) ) {
181                                         add_filter( $hook, $function );
182                                         $this->_prepreview_added_filters[] = compact( 'hook', 'function' );
183                                 }
184
185                                 $hook = sprintf( 'default_option_%s', $option );
186                                 if ( ! has_filter( $hook, $function ) ) {
187                                         add_filter( $hook, $function );
188                                         $this->_prepreview_added_filters[] = compact( 'hook', 'function' );
189                                 }
190
191                                 /*
192                                  * Make sure the option is registered so that the update_option()
193                                  * won't fail due to the filters providing a default value, which
194                                  * causes the update_option() to get confused.
195                                  */
196                                 add_option( $option, array() );
197                         }
198                 }
199         }
200
201         /**
202          * Ensure that newly-added widgets will appear in the widgets_sidebars.
203          *
204          * This is necessary because the Customizer's setting preview filters
205          * are added after the widgets_init action, which is too late for the
206          * widgets to be set up properly.
207          *
208          * @since 3.9.0
209          * @access public
210          *
211          * @param array $sidebars_widgets Associative array of sidebars and their widgets.
212          * @return array Filtered array of sidebars and their widgets.
213          */
214         public function prepreview_added_sidebars_widgets( $sidebars_widgets ) {
215                 foreach ( $this->_customized as $setting_id => $value ) {
216                         if ( preg_match( '/^sidebars_widgets\[(.+?)\]$/', $setting_id, $matches ) ) {
217                                 $sidebar_id = $matches[1];
218                                 $sidebars_widgets[ $sidebar_id ] = $value;
219                         }
220                 }
221                 return $sidebars_widgets;
222         }
223
224         /**
225          * Ensure newly-added widgets have empty instances so they
226          * will be recognized.
227          *
228          * This is necessary because the Customizer's setting preview
229          * filters are added after the widgets_init action, which is
230          * too late for the widgets to be set up properly.
231          *
232          * @since 3.9.0
233          * @access public
234          *
235          * @param array|bool|mixed $value Widget instance(s), false if open was empty.
236          * @return array|mixed Widget instance(s) with additions.
237          */
238         public function prepreview_added_widget_instance( $value = false ) {
239                 if ( ! preg_match( '/^(?:default_)?option_(widget_(.+))/', current_filter(), $matches ) ) {
240                         return $value;
241                 }
242                 $id_base = $matches[2];
243
244                 foreach ( $this->_customized as $setting_id => $setting ) {
245                         $parsed_setting_id = $this->parse_widget_setting_id( $setting_id );
246                         if ( is_wp_error( $parsed_setting_id ) || $id_base !== $parsed_setting_id['id_base'] ) {
247                                 continue;
248                         }
249                         $widget_number = $parsed_setting_id['number'];
250
251                         if ( is_null( $widget_number ) ) {
252                                 // Single widget.
253                                 if ( false === $value ) {
254                                         $value = array();
255                                 }
256                         } else {
257                                 // Multi widget.
258                                 if ( empty( $value ) ) {
259                                         $value = array( '_multiwidget' => 1 );
260                                 }
261                                 if ( ! isset( $value[ $widget_number ] ) ) {
262                                         $value[ $widget_number ] = array();
263                                 }
264                         }
265                 }
266
267                 return $value;
268         }
269
270         /**
271          * Remove pre-preview filters.
272          *
273          * Removes filters added in setup_widget_addition_previews()
274          * to ensure widgets are populating the options during
275          * 'widgets_init'.
276          *
277          * @since 3.9.0
278          * @access public
279          */
280         public function remove_prepreview_filters() {
281                 foreach ( $this->_prepreview_added_filters as $prepreview_added_filter ) {
282                         remove_filter( $prepreview_added_filter['hook'], $prepreview_added_filter['function'] );
283                 }
284                 $this->_prepreview_added_filters = array();
285         }
286
287         /**
288          * Override sidebars_widgets for theme switch.
289          *
290          * When switching a theme via the Customizer, supply any previously-configured
291          * sidebars_widgets from the target theme as the initial sidebars_widgets
292          * setting. Also store the old theme's existing settings so that they can
293          * be passed along for storing in the sidebars_widgets theme_mod when the
294          * theme gets switched.
295          *
296          * @since 3.9.0
297          * @access public
298          */
299         public function override_sidebars_widgets_for_theme_switch() {
300                 global $sidebars_widgets;
301
302                 if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
303                         return;
304                 }
305
306                 $this->old_sidebars_widgets = wp_get_sidebars_widgets();
307                 add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
308
309                 // retrieve_widgets() looks at the global $sidebars_widgets
310                 $sidebars_widgets = $this->old_sidebars_widgets;
311                 $sidebars_widgets = retrieve_widgets( 'customize' );
312                 add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
313         }
314
315         /**
316          * Filter old_sidebars_widgets_data Customizer setting.
317          *
318          * When switching themes, filter the Customizer setting
319          * old_sidebars_widgets_data to supply initial $sidebars_widgets before they
320          * were overridden by retrieve_widgets(). The value for
321          * old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
322          * theme_mod.
323          *
324          * @see WP_Customize_Widgets::handle_theme_switch()
325          * @since 3.9.0
326          * @access public
327          *
328          * @param array $old_sidebars_widgets
329          */
330         public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
331                 return $this->old_sidebars_widgets;
332         }
333
334         /**
335          * Filter sidebars_widgets option for theme switch.
336          *
337          * When switching themes, the retrieve_widgets() function is run when the
338          * Customizer initializes, and then the new sidebars_widgets here get
339          * supplied as the default value for the sidebars_widgets option.
340          *
341          * @see WP_Customize_Widgets::handle_theme_switch()
342          * @since 3.9.0
343          * @access public
344          *
345          * @param array $sidebars_widgets
346          */
347         public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
348                 $sidebars_widgets = $GLOBALS['sidebars_widgets'];
349                 $sidebars_widgets['array_version'] = 3;
350                 return $sidebars_widgets;
351         }
352
353         /**
354          * Make sure all widgets get loaded into the Customizer.
355          *
356          * Note: these actions are also fired in wp_ajax_update_widget().
357          *
358          * @since 3.9.0
359          * @access public
360          */
361         public function customize_controls_init() {
362                 /** This action is documented in wp-admin/includes/ajax-actions.php */
363                 do_action( 'load-widgets.php' );
364
365                 /** This action is documented in wp-admin/includes/ajax-actions.php */
366                 do_action( 'widgets.php' );
367
368                 /** This action is documented in wp-admin/widgets.php */
369                 do_action( 'sidebar_admin_setup' );
370         }
371
372         /**
373          * Ensure widgets are available for all types of previews.
374          *
375          * When in preview, hook to 'customize_register' for settings
376          * after WordPress is loaded so that all filters have been
377          * initialized (e.g. Widget Visibility).
378          *
379          * @since 3.9.0
380          * @access public
381          */
382         public function schedule_customize_register() {
383                 if ( is_admin() ) { // @todo for some reason, $wp_customize->is_preview() is true here?
384                         $this->customize_register();
385                 } else {
386                         add_action( 'wp', array( $this, 'customize_register' ) );
387                 }
388         }
389
390         /**
391          * Register Customizer settings and controls for all sidebars and widgets.
392          *
393          * @since 3.9.0
394          * @access public
395          */
396         public function customize_register() {
397                 global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
398
399                 $sidebars_widgets = array_merge(
400                         array( 'wp_inactive_widgets' => array() ),
401                         array_fill_keys( array_keys( $GLOBALS['wp_registered_sidebars'] ), array() ),
402                         wp_get_sidebars_widgets()
403                 );
404
405                 $new_setting_ids = array();
406
407                 /*
408                  * Register a setting for all widgets, including those which are active,
409                  * inactive, and orphaned since a widget may get suppressed from a sidebar
410                  * via a plugin (like Widget Visibility).
411                  */
412                 foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
413                         $setting_id   = $this->get_setting_id( $widget_id );
414                         $setting_args = $this->get_setting_args( $setting_id );
415
416                         $setting_args['sanitize_callback']    = array( $this, 'sanitize_widget_instance' );
417                         $setting_args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
418
419                         $this->manager->add_setting( $setting_id, $setting_args );
420
421                         $new_setting_ids[] = $setting_id;
422                 }
423
424                 /*
425                  * Add a setting which will be supplied for the theme's sidebars_widgets
426                  * theme_mod when the the theme is switched.
427                  */
428                 if ( ! $this->manager->is_theme_active() ) {
429                         $setting_id = 'old_sidebars_widgets_data';
430                         $setting_args = $this->get_setting_args( $setting_id, array(
431                                 'type' => 'global_variable',
432                         ) );
433                         $this->manager->add_setting( $setting_id, $setting_args );
434                 }
435
436                 $this->manager->add_panel( 'widgets', array(
437                         'title'       => __( 'Widgets' ),
438                         'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
439                         'priority'    => 110,
440                 ) );
441
442                 foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
443                         if ( empty( $sidebar_widget_ids ) ) {
444                                 $sidebar_widget_ids = array();
445                         }
446
447                         $is_registered_sidebar = isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] );
448                         $is_inactive_widgets   = ( 'wp_inactive_widgets' === $sidebar_id );
449                         $is_active_sidebar     = ( $is_registered_sidebar && ! $is_inactive_widgets );
450
451                         // Add setting for managing the sidebar's widgets.
452                         if ( $is_registered_sidebar || $is_inactive_widgets ) {
453                                 $setting_id   = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
454                                 $setting_args = $this->get_setting_args( $setting_id );
455
456                                 $setting_args['sanitize_callback']    = array( $this, 'sanitize_sidebar_widgets' );
457                                 $setting_args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
458
459                                 $this->manager->add_setting( $setting_id, $setting_args );
460                                 $new_setting_ids[] = $setting_id;
461
462                                 // Add section to contain controls.
463                                 $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
464                                 if ( $is_active_sidebar ) {
465
466                                         $section_args = array(
467                                                 'title' => $GLOBALS['wp_registered_sidebars'][ $sidebar_id ]['name'],
468                                                 'description' => $GLOBALS['wp_registered_sidebars'][ $sidebar_id ]['description'],
469                                                 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
470                                                 'panel' => 'widgets',
471                                                 'sidebar_id' => $sidebar_id,
472                                         );
473
474                                         /**
475                                          * Filter Customizer widget section arguments for a given sidebar.
476                                          *
477                                          * @since 3.9.0
478                                          *
479                                          * @param array      $section_args Array of Customizer widget section arguments.
480                                          * @param string     $section_id   Customizer section ID.
481                                          * @param int|string $sidebar_id   Sidebar ID.
482                                          */
483                                         $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
484
485                                         $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
486                                         $this->manager->add_section( $section );
487
488                                         $control = new WP_Widget_Area_Customize_Control( $this->manager, $setting_id, array(
489                                                 'section'    => $section_id,
490                                                 'sidebar_id' => $sidebar_id,
491                                                 'priority'   => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
492                                         ) );
493                                         $new_setting_ids[] = $setting_id;
494
495                                         $this->manager->add_control( $control );
496                                 }
497                         }
498
499                         // Add a control for each active widget (located in a sidebar).
500                         foreach ( $sidebar_widget_ids as $i => $widget_id ) {
501
502                                 // Skip widgets that may have gone away due to a plugin being deactivated.
503                                 if ( ! $is_active_sidebar || ! isset( $GLOBALS['wp_registered_widgets'][$widget_id] ) ) {
504                                         continue;
505                                 }
506
507                                 $registered_widget = $GLOBALS['wp_registered_widgets'][$widget_id];
508                                 $setting_id        = $this->get_setting_id( $widget_id );
509                                 $id_base           = $GLOBALS['wp_registered_widget_controls'][$widget_id]['id_base'];
510
511                                 $control = new WP_Widget_Form_Customize_Control( $this->manager, $setting_id, array(
512                                         'label'          => $registered_widget['name'],
513                                         'section'        => $section_id,
514                                         'sidebar_id'     => $sidebar_id,
515                                         'widget_id'      => $widget_id,
516                                         'widget_id_base' => $id_base,
517                                         'priority'       => $i,
518                                         'width'          => $wp_registered_widget_controls[$widget_id]['width'],
519                                         'height'         => $wp_registered_widget_controls[$widget_id]['height'],
520                                         'is_wide'        => $this->is_wide_widget( $widget_id ),
521                                 ) );
522                                 $this->manager->add_control( $control );
523                         }
524                 }
525
526                 /*
527                  * We have to register these settings later than customize_preview_init
528                  * so that other filters have had a chance to run.
529                  */
530                 if ( did_action( 'customize_preview_init' ) ) {
531                         foreach ( $new_setting_ids as $new_setting_id ) {
532                                 $this->manager->get_setting( $new_setting_id )->preview();
533                         }
534                 }
535                 $this->remove_prepreview_filters();
536         }
537
538         /**
539          * Covert a widget_id into its corresponding Customizer setting ID (option name).
540          *
541          * @since 3.9.0
542          * @access public
543          *
544          * @param string $widget_id Widget ID.
545          * @return string Maybe-parsed widget ID.
546          */
547         public function get_setting_id( $widget_id ) {
548                 $parsed_widget_id = $this->parse_widget_id( $widget_id );
549                 $setting_id       = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
550
551                 if ( ! is_null( $parsed_widget_id['number'] ) ) {
552                         $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
553                 }
554                 return $setting_id;
555         }
556
557         /**
558          * Determine whether the widget is considered "wide".
559          *
560          * Core widgets which may have controls wider than 250, but can
561          * still be shown in the narrow Customizer panel. The RSS and Text
562          * widgets in Core, for example, have widths of 400 and yet they
563          * still render fine in the Customizer panel. This method will
564          * return all Core widgets as being not wide, but this can be
565          * overridden with the is_wide_widget_in_customizer filter.
566          *
567          * @since 3.9.0
568          * @access public
569          *
570          * @param string $widget_id Widget ID.
571          * @return bool Whether or not the widget is a "wide" widget.
572          */
573         public function is_wide_widget( $widget_id ) {
574                 global $wp_registered_widget_controls;
575
576                 $parsed_widget_id = $this->parse_widget_id( $widget_id );
577                 $width            = $wp_registered_widget_controls[$widget_id]['width'];
578                 $is_core          = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases );
579                 $is_wide          = ( $width > 250 && ! $is_core );
580
581                 /**
582                  * Filter whether the given widget is considered "wide".
583                  *
584                  * @since 3.9.0
585                  *
586                  * @param bool   $is_wide   Whether the widget is wide, Default false.
587                  * @param string $widget_id Widget ID.
588                  */
589                 return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
590         }
591
592         /**
593          * Covert a widget ID into its id_base and number components.
594          *
595          * @since 3.9.0
596          * @access public
597          *
598          * @param string $widget_id Widget ID.
599          * @return array Array containing a widget's id_base and number components.
600          */
601         public function parse_widget_id( $widget_id ) {
602                 $parsed = array(
603                         'number' => null,
604                         'id_base' => null,
605                 );
606
607                 if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
608                         $parsed['id_base'] = $matches[1];
609                         $parsed['number']  = intval( $matches[2] );
610                 } else {
611                         // likely an old single widget
612                         $parsed['id_base'] = $widget_id;
613                 }
614                 return $parsed;
615         }
616
617         /**
618          * Convert a widget setting ID (option path) to its id_base and number components.
619          *
620          * @since 3.9.0
621          * @access public
622          *
623          * @param string $setting_id Widget setting ID.
624          * @return WP_Error|array Array containing a widget's id_base and number components,
625          *                        or a WP_Error object.
626          */
627         public function parse_widget_setting_id( $setting_id ) {
628                 if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
629                         return new WP_Error( 'widget_setting_invalid_id' );
630                 }
631
632                 $id_base = $matches[2];
633                 $number  = isset( $matches[3] ) ? intval( $matches[3] ) : null;
634
635                 return compact( 'id_base', 'number' );
636         }
637
638         /**
639          * Call admin_print_styles-widgets.php and admin_print_styles hooks to
640          * allow custom styles from plugins.
641          *
642          * @since 3.9.0
643          * @access public
644          */
645         public function print_styles() {
646                 /** This action is documented in wp-admin/admin-header.php */
647                 do_action( 'admin_print_styles-widgets.php' );
648
649                 /** This action is documented in wp-admin/admin-header.php */
650                 do_action( 'admin_print_styles' );
651         }
652
653         /**
654          * Call admin_print_scripts-widgets.php and admin_print_scripts hooks to
655          * allow custom scripts from plugins.
656          *
657          * @since 3.9.0
658          * @access public
659          */
660         public function print_scripts() {
661                 /** This action is documented in wp-admin/admin-header.php */
662                 do_action( 'admin_print_scripts-widgets.php' );
663
664                 /** This action is documented in wp-admin/admin-header.php */
665                 do_action( 'admin_print_scripts' );
666         }
667
668         /**
669          * Enqueue scripts and styles for Customizer panel and export data to JavaScript.
670          *
671          * @since 3.9.0
672          * @access public
673          */
674         public function enqueue_scripts() {
675                 wp_enqueue_style( 'customize-widgets' );
676                 wp_enqueue_script( 'customize-widgets' );
677
678                 /** This action is documented in wp-admin/admin-header.php */
679                 do_action( 'admin_enqueue_scripts', 'widgets.php' );
680
681                 /*
682                  * Export available widgets with control_tpl removed from model
683                  * since plugins need templates to be in the DOM.
684                  */
685                 $available_widgets = array();
686
687                 foreach ( $this->get_available_widgets() as $available_widget ) {
688                         unset( $available_widget['control_tpl'] );
689                         $available_widgets[] = $available_widget;
690                 }
691
692                 $widget_reorder_nav_tpl = sprintf(
693                         '<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>',
694                         __( 'Move to another area&hellip;' ),
695                         __( 'Move down' ),
696                         __( 'Move up' )
697                 );
698
699                 $move_widget_area_tpl = str_replace(
700                         array( '{description}', '{btn}' ),
701                         array(
702                                 __( 'Select an area to move this widget into:' ),
703                                 _x( 'Move', 'Move widget' ),
704                         ),
705                         '<div class="move-widget-area">
706                                 <p class="description">{description}</p>
707                                 <ul class="widget-area-select">
708                                         <% _.each( sidebars, function ( sidebar ){ %>
709                                                 <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
710                                         <% }); %>
711                                 </ul>
712                                 <div class="move-widget-actions">
713                                         <button class="move-widget-btn button-secondary" type="button">{btn}</button>
714                                 </div>
715                         </div>'
716                 );
717
718                 global $wp_scripts;
719
720                 $settings = array(
721                         'nonce'                => wp_create_nonce( 'update-widget' ),
722                         'registeredSidebars'   => array_values( $GLOBALS['wp_registered_sidebars'] ),
723                         'registeredWidgets'    => $GLOBALS['wp_registered_widgets'],
724                         'availableWidgets'     => $available_widgets, // @todo Merge this with registered_widgets
725                         'l10n' => array(
726                                 'saveBtnLabel'     => __( 'Apply' ),
727                                 'saveBtnTooltip'   => __( 'Save and preview changes before publishing them.' ),
728                                 'removeBtnLabel'   => __( 'Remove' ),
729                                 'removeBtnTooltip' => __( 'Trash widget by moving it to the inactive widgets sidebar.' ),
730                                 'error'            => __( 'An error has occurred. Please reload the page and try again.' ),
731                                 'widgetMovedUp'    => __( 'Widget moved up' ),
732                                 'widgetMovedDown'  => __( 'Widget moved down' ),
733                         ),
734                         'tpl' => array(
735                                 'widgetReorderNav' => $widget_reorder_nav_tpl,
736                                 'moveWidgetArea'   => $move_widget_area_tpl,
737                         ),
738                 );
739
740                 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
741                         unset( $registered_widget['callback'] ); // may not be JSON-serializeable
742                 }
743
744                 $wp_scripts->add_data(
745                         'customize-widgets',
746                         'data',
747                         sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
748                 );
749         }
750
751         /**
752          * Render the widget form control templates into the DOM.
753          *
754          * @since 3.9.0
755          * @access public
756          */
757         public function output_widget_control_templates() {
758                 ?>
759                 <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
760                 <div id="available-widgets">
761                         <div id="available-widgets-filter">
762                                 <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
763                                 <input type="search" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ) ?>" />
764                         </div>
765                         <?php foreach ( $this->get_available_widgets() as $available_widget ): ?>
766                                 <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">
767                                         <?php echo $available_widget['control_tpl']; ?>
768                                 </div>
769                         <?php endforeach; ?>
770                 </div><!-- #available-widgets -->
771                 </div><!-- #widgets-left -->
772                 <?php
773         }
774
775         /**
776          * Call admin_print_footer_scripts and admin_print_scripts hooks to
777          * allow custom scripts from plugins.
778          *
779          * @since 3.9.0
780          * @access public
781          */
782         public function print_footer_scripts() {
783                 /** This action is documented in wp-admin/admin-footer.php */
784                 do_action( 'admin_print_footer_scripts' );
785
786                 /** This action is documented in wp-admin/admin-footer.php */
787                 do_action( 'admin_footer-widgets.php' );
788         }
789
790         /**
791          * Get common arguments to supply when constructing a Customizer setting.
792          *
793          * @since 3.9.0
794          * @access public
795          *
796          * @param string $id        Widget setting ID.
797          * @param array  $overrides Array of setting overrides.
798          * @return array Possibly modified setting arguments.
799          */
800         public function get_setting_args( $id, $overrides = array() ) {
801                 $args = array(
802                         'type'       => 'option',
803                         'capability' => 'edit_theme_options',
804                         'transport'  => 'refresh',
805                         'default'    => array(),
806                 );
807                 $args = array_merge( $args, $overrides );
808
809                 /**
810                  * Filter the common arguments supplied when constructing a Customizer setting.
811                  *
812                  * @since 3.9.0
813                  *
814                  * @see WP_Customize_Setting
815                  *
816                  * @param array  $args Array of Customizer setting arguments.
817                  * @param string $id   Widget setting ID.
818                  */
819                 return apply_filters( 'widget_customizer_setting_args', $args, $id );
820         }
821
822         /**
823          * Make sure that sidebar widget arrays only ever contain widget IDS.
824          *
825          * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
826          *
827          * @since 3.9.0
828          * @access public
829          *
830          * @param array $widget_ids Array of widget IDs.
831          * @return array Array of sanitized widget IDs.
832          */
833         public function sanitize_sidebar_widgets( $widget_ids ) {
834                 global $wp_registered_widgets;
835
836                 $widget_ids           = array_map( 'strval', (array) $widget_ids );
837                 $sanitized_widget_ids = array();
838
839                 foreach ( $widget_ids as $widget_id ) {
840                         if ( array_key_exists( $widget_id, $wp_registered_widgets ) ) {
841                                 $sanitized_widget_ids[] = $widget_id;
842                         }
843                 }
844                 return $sanitized_widget_ids;
845         }
846
847         /**
848          * Build up an index of all available widgets for use in Backbone models.
849          *
850          * @since 3.9.0
851          * @access public
852          *
853          * @see wp_list_widgets()
854          *
855          * @return array List of available widgets.
856          */
857         public function get_available_widgets() {
858                 static $available_widgets = array();
859                 if ( ! empty( $available_widgets ) ) {
860                         return $available_widgets;
861                 }
862
863                 global $wp_registered_widgets, $wp_registered_widget_controls;
864                 require_once ABSPATH . '/wp-admin/includes/widgets.php'; // for next_widget_id_number()
865
866                 $sort = $wp_registered_widgets;
867                 usort( $sort, array( $this, '_sort_name_callback' ) );
868                 $done = array();
869
870                 foreach ( $sort as $widget ) {
871                         if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget
872                                 continue;
873                         }
874
875                         $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
876                         $done[]  = $widget['callback'];
877
878                         if ( ! isset( $widget['params'][0] ) ) {
879                                 $widget['params'][0] = array();
880                         }
881
882                         $available_widget = $widget;
883                         unset( $available_widget['callback'] ); // not serializable to JSON
884
885                         $args = array(
886                                 'widget_id'   => $widget['id'],
887                                 'widget_name' => $widget['name'],
888                                 '_display'    => 'template',
889                         );
890
891                         $is_disabled     = false;
892                         $is_multi_widget = ( isset( $wp_registered_widget_controls[$widget['id']]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
893                         if ( $is_multi_widget ) {
894                                 $id_base            = $wp_registered_widget_controls[$widget['id']]['id_base'];
895                                 $args['_temp_id']   = "$id_base-__i__";
896                                 $args['_multi_num'] = next_widget_id_number( $id_base );
897                                 $args['_add']       = 'multi';
898                         } else {
899                                 $args['_add'] = 'single';
900
901                                 if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
902                                         $is_disabled = true;
903                                 }
904                                 $id_base = $widget['id'];
905                         }
906
907                         $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) );
908                         $control_tpl = $this->get_widget_control( $list_widget_controls_args );
909
910                         // The properties here are mapped to the Backbone Widget model.
911                         $available_widget = array_merge( $available_widget, array(
912                                 'temp_id'      => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
913                                 'is_multi'     => $is_multi_widget,
914                                 'control_tpl'  => $control_tpl,
915                                 'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
916                                 'is_disabled'  => $is_disabled,
917                                 'id_base'      => $id_base,
918                                 'transport'    => 'refresh',
919                                 'width'        => $wp_registered_widget_controls[$widget['id']]['width'],
920                                 'height'       => $wp_registered_widget_controls[$widget['id']]['height'],
921                                 'is_wide'      => $this->is_wide_widget( $widget['id'] ),
922                         ) );
923
924                         $available_widgets[] = $available_widget;
925                 }
926
927                 return $available_widgets;
928         }
929
930         /**
931          * Naturally order available widgets by name.
932          *
933          * @since 3.9.0
934          * @static
935          * @access protected
936          *
937          * @param array $widget_a The first widget to compare.
938          * @param array $widget_b The second widget to compare.
939          * @return int Reorder position for the current widget comparison.
940          */
941         protected function _sort_name_callback( $widget_a, $widget_b ) {
942                 return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
943         }
944
945         /**
946          * Get the widget control markup.
947          *
948          * @since 3.9.0
949          * @access public
950          *
951          * @param array $args Widget control arguments.
952          * @return string Widget control form HTML markup.
953          */
954         public function get_widget_control( $args ) {
955                 ob_start();
956
957                 call_user_func_array( 'wp_widget_control', $args );
958                 $replacements = array(
959                         '<form action="" method="post">' => '<div class="form">',
960                         '</form>' => '</div><!-- .form -->',
961                 );
962
963                 $control_tpl = ob_get_clean();
964
965                 $control_tpl = str_replace( array_keys( $replacements ), array_values( $replacements ), $control_tpl );
966
967                 return $control_tpl;
968         }
969
970         /**
971          * Add hooks for the Customizer preview.
972          *
973          * @since 3.9.0
974          * @access public
975          */
976         public function customize_preview_init() {
977                 add_filter( 'sidebars_widgets',   array( $this, 'preview_sidebars_widgets' ), 1 );
978                 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
979                 add_action( 'wp_print_styles',    array( $this, 'print_preview_css' ), 1 );
980                 add_action( 'wp_footer',          array( $this, 'export_preview_data' ), 20 );
981         }
982
983         /**
984          * When previewing, make sure the proper previewing widgets are used.
985          *
986          * Because wp_get_sidebars_widgets() gets called early at init
987          * (via wp_convert_widget_settings()) and can set global variable
988          * $_wp_sidebars_widgets to the value of get_option( 'sidebars_widgets' )
989          * before the Customizer preview filter is added, we have to reset
990          * it after the filter has been added.
991          *
992          * @since 3.9.0
993          * @access public
994          *
995          * @param array $sidebars_widgets List of widgets for the current sidebar.
996          */
997         public function preview_sidebars_widgets( $sidebars_widgets ) {
998                 $sidebars_widgets = get_option( 'sidebars_widgets' );
999
1000                 unset( $sidebars_widgets['array_version'] );
1001                 return $sidebars_widgets;
1002         }
1003
1004         /**
1005          * Enqueue scripts for the Customizer preview.
1006          *
1007          * @since 3.9.0
1008          * @access public
1009          */
1010         public function customize_preview_enqueue() {
1011                 wp_enqueue_script( 'customize-preview-widgets' );
1012         }
1013
1014         /**
1015          * Insert default style for highlighted widget at early point so theme
1016          * stylesheet can override.
1017          *
1018          * @since 3.9.0
1019          * @access public
1020          *
1021          * @action wp_print_styles
1022          */
1023         public function print_preview_css() {
1024                 ?>
1025                 <style>
1026                 .widget-customizer-highlighted-widget {
1027                         outline: none;
1028                         -webkit-box-shadow: 0 0 2px rgba(30,140,190,0.8);
1029                         box-shadow: 0 0 2px rgba(30,140,190,0.8);
1030                         position: relative;
1031                         z-index: 1;
1032                 }
1033                 </style>
1034                 <?php
1035         }
1036
1037         /**
1038          * At the very end of the page, at the very end of the wp_footer,
1039          * communicate the sidebars that appeared on the page.
1040          *
1041          * @since 3.9.0
1042          * @access public
1043          */
1044         public function export_preview_data() {
1045
1046                 // Prepare Customizer settings to pass to JavaScript.
1047                 $settings = array(
1048                         'renderedSidebars'   => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
1049                         'renderedWidgets'    => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
1050                         'registeredSidebars' => array_values( $GLOBALS['wp_registered_sidebars'] ),
1051                         'registeredWidgets'  => $GLOBALS['wp_registered_widgets'],
1052                         'l10n'               => array(
1053                                 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
1054                         ),
1055                 );
1056                 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
1057                         unset( $registered_widget['callback'] ); // may not be JSON-serializeable
1058                 }
1059
1060                 ?>
1061                 <script type="text/javascript">
1062                         var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
1063                 </script>
1064                 <?php
1065         }
1066
1067         /**
1068          * Keep track of the widgets that were rendered.
1069          *
1070          * @since 3.9.0
1071          * @access public
1072          *
1073          * @param array $widget Rendered widget to tally.
1074          */
1075         public function tally_rendered_widgets( $widget ) {
1076                 $this->rendered_widgets[ $widget['id'] ] = true;
1077         }
1078
1079         /**
1080          * Determine if a widget is rendered on the page.
1081          *
1082          * @since 4.0.0
1083          * @access public
1084          *
1085          * @param string $widget_id Widget ID to check.
1086          * @return bool Whether the widget is rendered.
1087          */
1088         public function is_widget_rendered( $widget_id ) {
1089                 return in_array( $widget_id, $this->rendered_widgets );
1090         }
1091
1092         /**
1093          * Determine if a sidebar is rendered on the page.
1094          *
1095          * @since 4.0.0
1096          * @access public
1097          *
1098          * @param string $sidebar_id Sidebar ID to check.
1099          * @return bool Whether the sidebar is rendered.
1100          */
1101         public function is_sidebar_rendered( $sidebar_id ) {
1102                 return in_array( $sidebar_id, $this->rendered_sidebars );
1103         }
1104
1105         /**
1106          * Tally the sidebars rendered via is_active_sidebar().
1107          *
1108          * Keep track of the times that is_active_sidebar() is called
1109          * in the template, and assume that this means that the sidebar
1110          * would be rendered on the template if there were widgets
1111          * populating it.
1112          *
1113          * @since 3.9.0
1114          * @access public
1115          *
1116          * @param bool   $is_active  Whether the sidebar is active.
1117          * @param string $sidebar_id Sidebar ID.
1118          */
1119         public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
1120                 if ( isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] ) ) {
1121                         $this->rendered_sidebars[] = $sidebar_id;
1122                 }
1123                 /*
1124                  * We may need to force this to true, and also force-true the value
1125                  * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
1126                  * is an area to drop widgets into, if the sidebar is empty.
1127                  */
1128                 return $is_active;
1129         }
1130
1131         /**
1132          * Tally the sidebars rendered via dynamic_sidebar().
1133          *
1134          * Keep track of the times that dynamic_sidebar() is called in the template,
1135          * and assume this means the sidebar would be rendered on the template if
1136          * there were widgets populating it.
1137          *
1138          * @since 3.9.0
1139          * @access public
1140          *
1141          * @param bool   $has_widgets Whether the current sidebar has widgets.
1142          * @param string $sidebar_id  Sidebar ID.
1143          */
1144         public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
1145                 if ( isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] ) ) {
1146                         $this->rendered_sidebars[] = $sidebar_id;
1147                 }
1148
1149                 /*
1150                  * We may need to force this to true, and also force-true the value
1151                  * for 'is_active_sidebar' if we want to ensure there is an area to
1152                  * drop widgets into, if the sidebar is empty.
1153                  */
1154                 return $has_widgets;
1155         }
1156
1157         /**
1158          * Get MAC for a serialized widget instance string.
1159          *
1160          * Allows values posted back from JS to be rejected if any tampering of the
1161          * data has occurred.
1162          *
1163          * @since 3.9.0
1164          * @access protected
1165          *
1166          * @param string $serialized_instance Widget instance.
1167          * @return string MAC for serialized widget instance.
1168          */
1169         protected function get_instance_hash_key( $serialized_instance ) {
1170                 return wp_hash( $serialized_instance );
1171         }
1172
1173         /**
1174          * Sanitize a widget instance.
1175          *
1176          * Unserialize the JS-instance for storing in the options. It's important
1177          * that this filter only get applied to an instance once.
1178          *
1179          * @since 3.9.0
1180          * @access public
1181          *
1182          * @param array $value Widget instance to sanitize.
1183          * @return array Sanitized widget instance.
1184          */
1185         public function sanitize_widget_instance( $value ) {
1186                 if ( $value === array() ) {
1187                         return $value;
1188                 }
1189
1190                 if ( empty( $value['is_widget_customizer_js_value'] )
1191                         || empty( $value['instance_hash_key'] )
1192                         || empty( $value['encoded_serialized_instance'] ) )
1193                 {
1194                         return null;
1195                 }
1196
1197                 $decoded = base64_decode( $value['encoded_serialized_instance'], true );
1198                 if ( false === $decoded ) {
1199                         return null;
1200                 }
1201
1202                 if ( $this->get_instance_hash_key( $decoded ) !== $value['instance_hash_key'] ) {
1203                         return null;
1204                 }
1205
1206                 $instance = unserialize( $decoded );
1207                 if ( false === $instance ) {
1208                         return null;
1209                 }
1210
1211                 return $instance;
1212         }
1213
1214         /**
1215          * Convert widget instance into JSON-representable format.
1216          *
1217          * @since 3.9.0
1218          * @access public
1219          *
1220          * @param array $value Widget instance to convert to JSON.
1221          * @return array JSON-converted widget instance.
1222          */
1223         public function sanitize_widget_js_instance( $value ) {
1224                 if ( empty( $value['is_widget_customizer_js_value'] ) ) {
1225                         $serialized = serialize( $value );
1226
1227                         $value = array(
1228                                 'encoded_serialized_instance'   => base64_encode( $serialized ),
1229                                 'title'                         => empty( $value['title'] ) ? '' : $value['title'],
1230                                 'is_widget_customizer_js_value' => true,
1231                                 'instance_hash_key'             => $this->get_instance_hash_key( $serialized ),
1232                         );
1233                 }
1234                 return $value;
1235         }
1236
1237         /**
1238          * Strip out widget IDs for widgets which are no longer registered.
1239          *
1240          * One example where this might happen is when a plugin orphans a widget
1241          * in a sidebar upon deactivation.
1242          *
1243          * @since 3.9.0
1244          * @access public
1245          *
1246          * @param array $widget_ids List of widget IDs.
1247          * @return array Parsed list of widget IDs.
1248          */
1249         public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
1250                 global $wp_registered_widgets;
1251                 $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
1252                 return $widget_ids;
1253         }
1254
1255         /**
1256          * Find and invoke the widget update and control callbacks.
1257          *
1258          * Requires that $_POST be populated with the instance data.
1259          *
1260          * @since 3.9.0
1261          * @access public
1262          *
1263          * @param  string $widget_id Widget ID.
1264          * @return WP_Error|array Array containing the updated widget information.
1265          *                        A WP_Error object, otherwise.
1266          */
1267         public function call_widget_update( $widget_id ) {
1268                 global $wp_registered_widget_updates, $wp_registered_widget_controls;
1269
1270                 $this->start_capturing_option_updates();
1271                 $parsed_id   = $this->parse_widget_id( $widget_id );
1272                 $option_name = 'widget_' . $parsed_id['id_base'];
1273
1274                 /*
1275                  * If a previously-sanitized instance is provided, populate the input vars
1276                  * with its values so that the widget update callback will read this instance
1277                  */
1278                 $added_input_vars = array();
1279                 if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
1280                         $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
1281                         if ( false === $sanitized_widget_setting ) {
1282                                 $this->stop_capturing_option_updates();
1283                                 return new WP_Error( 'widget_setting_malformed' );
1284                         }
1285
1286                         $instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
1287                         if ( is_null( $instance ) ) {
1288                                 $this->stop_capturing_option_updates();
1289                                 return new WP_Error( 'widget_setting_unsanitized' );
1290                         }
1291
1292                         if ( ! is_null( $parsed_id['number'] ) ) {
1293                                 $value = array();
1294                                 $value[$parsed_id['number']] = $instance;
1295                                 $key = 'widget-' . $parsed_id['id_base'];
1296                                 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1297                                 $added_input_vars[] = $key;
1298                         } else {
1299                                 foreach ( $instance as $key => $value ) {
1300                                         $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1301                                         $added_input_vars[] = $key;
1302                                 }
1303                         }
1304                 }
1305
1306                 // Invoke the widget update callback.
1307                 foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
1308                         if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
1309                                 ob_start();
1310                                 call_user_func_array( $control['callback'], $control['params'] );
1311                                 ob_end_clean();
1312                                 break;
1313                         }
1314                 }
1315
1316                 // Clean up any input vars that were manually added
1317                 foreach ( $added_input_vars as $key ) {
1318                         unset( $_POST[$key] );
1319                         unset( $_REQUEST[$key] );
1320                 }
1321
1322                 // Make sure the expected option was updated.
1323                 if ( 0 !== $this->count_captured_options() ) {
1324                         if ( $this->count_captured_options() > 1 ) {
1325                                 $this->stop_capturing_option_updates();
1326                                 return new WP_Error( 'widget_setting_too_many_options' );
1327                         }
1328
1329                         $updated_option_name = key( $this->get_captured_options() );
1330                         if ( $updated_option_name !== $option_name ) {
1331                                 $this->stop_capturing_option_updates();
1332                                 return new WP_Error( 'widget_setting_unexpected_option' );
1333                         }
1334                 }
1335
1336                 // Obtain the widget control with the updated instance in place.
1337                 ob_start();
1338
1339                 $form = $wp_registered_widget_controls[$widget_id];
1340                 if ( $form ) {
1341                         call_user_func_array( $form['callback'], $form['params'] );
1342                 }
1343
1344                 $form = ob_get_clean();
1345
1346                 // Obtain the widget instance.
1347                 $option = get_option( $option_name );
1348
1349                 if ( null !== $parsed_id['number'] ) {
1350                         $instance = $option[$parsed_id['number']];
1351                 } else {
1352                         $instance = $option;
1353                 }
1354
1355                 $this->stop_capturing_option_updates();
1356
1357                 return compact( 'instance', 'form' );
1358         }
1359
1360         /**
1361          * Update widget settings asynchronously.
1362          *
1363          * Allows the Customizer to update a widget using its form, but return the new
1364          * instance info via Ajax instead of saving it to the options table.
1365          *
1366          * Most code here copied from wp_ajax_save_widget()
1367          *
1368          * @since 3.9.0
1369          * @access public
1370          *
1371          * @see wp_ajax_save_widget()
1372          *
1373          */
1374         public function wp_ajax_update_widget() {
1375
1376                 if ( ! is_user_logged_in() ) {
1377                         wp_die( 0 );
1378                 }
1379
1380                 check_ajax_referer( 'update-widget', 'nonce' );
1381
1382                 if ( ! current_user_can( 'edit_theme_options' ) ) {
1383                         wp_die( -1 );
1384                 }
1385
1386                 if ( ! isset( $_POST['widget-id'] ) ) {
1387                         wp_send_json_error();
1388                 }
1389
1390                 /** This action is documented in wp-admin/includes/ajax-actions.php */
1391                 do_action( 'load-widgets.php' );
1392
1393                 /** This action is documented in wp-admin/includes/ajax-actions.php */
1394                 do_action( 'widgets.php' );
1395
1396                 /** This action is documented in wp-admin/widgets.php */
1397                 do_action( 'sidebar_admin_setup' );
1398
1399                 $widget_id = $this->get_post_value( 'widget-id' );
1400                 $parsed_id = $this->parse_widget_id( $widget_id );
1401                 $id_base   = $parsed_id['id_base'];
1402
1403                 if ( isset( $_POST['widget-' . $id_base] ) && is_array( $_POST['widget-' . $id_base] ) && preg_match( '/__i__|%i%/', key( $_POST['widget-' . $id_base] ) ) ) {
1404                         wp_send_json_error();
1405                 }
1406
1407                 $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
1408                 if ( is_wp_error( $updated_widget ) ) {
1409                         wp_send_json_error();
1410                 }
1411
1412                 $form = $updated_widget['form'];
1413                 $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
1414
1415                 wp_send_json_success( compact( 'form', 'instance' ) );
1416         }
1417
1418         /***************************************************************************
1419          * Option Update Capturing
1420          ***************************************************************************/
1421
1422         /**
1423          * List of captured widget option updates.
1424          *
1425          * @since 3.9.0
1426          * @access protected
1427          * @var array $_captured_options Values updated while option capture is happening.
1428          */
1429         protected $_captured_options = array();
1430
1431         /**
1432          * Whether option capture is currently happening.
1433          *
1434          * @since 3.9.0
1435          * @access protected
1436          * @var bool $_is_current Whether option capture is currently happening or not.
1437          */
1438         protected $_is_capturing_option_updates = false;
1439
1440         /**
1441          * Determine whether the captured option update should be ignored.
1442          *
1443          * @since 3.9.0
1444          * @access protected
1445          *
1446          * @param string $option_name Option name.
1447          * @return boolean Whether the option capture is ignored.
1448          */
1449         protected function is_option_capture_ignored( $option_name ) {
1450                 return ( 0 === strpos( $option_name, '_transient_' ) );
1451         }
1452
1453         /**
1454          * Retrieve captured widget option updates.
1455          *
1456          * @since 3.9.0
1457          * @access protected
1458          *
1459          * @return array Array of captured options.
1460          */
1461         protected function get_captured_options() {
1462                 return $this->_captured_options;
1463         }
1464
1465         /**
1466          * Get the number of captured widget option updates.
1467          *
1468          * @since 3.9.0
1469          * @access protected
1470          *
1471          * @return int Number of updated options.
1472          */
1473         protected function count_captured_options() {
1474                 return count( $this->_captured_options );
1475         }
1476
1477         /**
1478          * Start keeping track of changes to widget options, caching new values.
1479          *
1480          * @since 3.9.0
1481          * @access protected
1482          */
1483         protected function start_capturing_option_updates() {
1484                 if ( $this->_is_capturing_option_updates ) {
1485                         return;
1486                 }
1487
1488                 $this->_is_capturing_option_updates = true;
1489
1490                 add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1491         }
1492
1493         /**
1494          * Pre-filter captured option values before updating.
1495          *
1496          * @since 3.9.0
1497          * @access public
1498          *
1499          * @param mixed $new_value
1500          * @param string $option_name
1501          * @param mixed $old_value
1502          * @return mixed
1503          */
1504         public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
1505                 if ( $this->is_option_capture_ignored( $option_name ) ) {
1506                         return;
1507                 }
1508
1509                 if ( ! isset( $this->_captured_options[$option_name] ) ) {
1510                         add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1511                 }
1512
1513                 $this->_captured_options[$option_name] = $new_value;
1514
1515                 return $old_value;
1516         }
1517
1518         /**
1519          * Pre-filter captured option values before retrieving.
1520          *
1521          * @since 3.9.0
1522          * @access public
1523          *
1524          * @param mixed $value Option
1525          * @return mixed
1526          */
1527         public function capture_filter_pre_get_option( $value ) {
1528                 $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
1529
1530                 if ( isset( $this->_captured_options[$option_name] ) ) {
1531                         $value = $this->_captured_options[$option_name];
1532
1533                         /** This filter is documented in wp-includes/option.php */
1534                         $value = apply_filters( 'option_' . $option_name, $value );
1535                 }
1536
1537                 return $value;
1538         }
1539
1540         /**
1541          * Undo any changes to the options since options capture began.
1542          *
1543          * @since 3.9.0
1544          * @access protected
1545          */
1546         protected function stop_capturing_option_updates() {
1547                 if ( ! $this->_is_capturing_option_updates ) {
1548                         return;
1549                 }
1550
1551                 remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1552
1553                 foreach ( array_keys( $this->_captured_options ) as $option_name ) {
1554                         remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1555                 }
1556
1557                 $this->_captured_options = array();
1558                 $this->_is_capturing_option_updates = false;
1559         }
1560 }