]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/widgets.php
Wordpress 3.3
[autoinstalls/wordpress.git] / wp-includes / widgets.php
1 <?php
2 /**
3  * API for creating dynamic sidebar without hardcoding functionality into
4  * themes. Includes both internal WordPress routines and theme use routines.
5  *
6  * This functionality was found in a plugin before WordPress 2.2 release which
7  * included it in the core from that point on.
8  *
9  * @link http://codex.wordpress.org/Plugins/WordPress_Widgets WordPress Widgets
10  * @link http://codex.wordpress.org/Plugins/WordPress_Widgets_Api Widgets API
11  *
12  * @package WordPress
13  * @subpackage Widgets
14  */
15
16 /**
17  * This class must be extended for each widget and WP_Widget::widget(), WP_Widget::update()
18  * and WP_Widget::form() need to be over-ridden.
19  *
20  * @package WordPress
21  * @subpackage Widgets
22  * @since 2.8
23  */
24 class WP_Widget {
25
26         var $id_base;                   // Root id for all widgets of this type.
27         var $name;                              // Name for this widget type.
28         var $widget_options;    // Option array passed to wp_register_sidebar_widget()
29         var $control_options;   // Option array passed to wp_register_widget_control()
30
31         var $number = false;    // Unique ID number of the current instance.
32         var $id = false;                // Unique ID string of the current instance (id_base-number)
33         var $updated = false;   // Set true when we update the data after a POST submit - makes sure we don't do it twice.
34
35         // Member functions that you must over-ride.
36
37         /** Echo the widget content.
38          *
39          * Subclasses should over-ride this function to generate their widget code.
40          *
41          * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
42          * @param array $instance The settings for the particular instance of the widget
43          */
44         function widget($args, $instance) {
45                 die('function WP_Widget::widget() must be over-ridden in a sub-class.');
46         }
47
48         /** Update a particular instance.
49          *
50          * This function should check that $new_instance is set correctly.
51          * The newly calculated value of $instance should be returned.
52          * If "false" is returned, the instance won't be saved/updated.
53          *
54          * @param array $new_instance New settings for this instance as input by the user via form()
55          * @param array $old_instance Old settings for this instance
56          * @return array Settings to save or bool false to cancel saving
57          */
58         function update($new_instance, $old_instance) {
59                 return $new_instance;
60         }
61
62         /** Echo the settings update form
63          *
64          * @param array $instance Current settings
65          */
66         function form($instance) {
67                 echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>';
68                 return 'noform';
69         }
70
71         // Functions you'll need to call.
72
73         /**
74          * PHP4 constructor
75          */
76         function WP_Widget( $id_base = false, $name, $widget_options = array(), $control_options = array() ) {
77                 WP_Widget::__construct( $id_base, $name, $widget_options, $control_options );
78         }
79
80         /**
81          * PHP5 constructor
82          *
83          * @param string $id_base Optional Base ID for the widget, lower case,
84          * if left empty a portion of the widget's class name will be used. Has to be unique.
85          * @param string $name Name for the widget displayed on the configuration page.
86          * @param array $widget_options Optional Passed to wp_register_sidebar_widget()
87          *       - description: shown on the configuration page
88          *       - classname
89          * @param array $control_options Optional Passed to wp_register_widget_control()
90          *       - width: required if more than 250px
91          *       - height: currently not used but may be needed in the future
92          */
93         function __construct( $id_base = false, $name, $widget_options = array(), $control_options = array() ) {
94                 $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
95                 $this->name = $name;
96                 $this->option_name = 'widget_' . $this->id_base;
97                 $this->widget_options = wp_parse_args( $widget_options, array('classname' => $this->option_name) );
98                 $this->control_options = wp_parse_args( $control_options, array('id_base' => $this->id_base) );
99         }
100
101         /**
102          * Constructs name attributes for use in form() fields
103          *
104          * This function should be used in form() methods to create name attributes for fields to be saved by update()
105          *
106          * @param string $field_name Field name
107          * @return string Name attribute for $field_name
108          */
109         function get_field_name($field_name) {
110                 return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
111         }
112
113         /**
114          * Constructs id attributes for use in form() fields
115          *
116          * This function should be used in form() methods to create id attributes for fields to be saved by update()
117          *
118          * @param string $field_name Field name
119          * @return string ID attribute for $field_name
120          */
121         function get_field_id($field_name) {
122                 return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name;
123         }
124
125         // Private Functions. Don't worry about these.
126
127         function _register() {
128                 $settings = $this->get_settings();
129                 $empty = true;
130
131                 if ( is_array($settings) ) {
132                         foreach ( array_keys($settings) as $number ) {
133                                 if ( is_numeric($number) ) {
134                                         $this->_set($number);
135                                         $this->_register_one($number);
136                                         $empty = false;
137                                 }
138                         }
139                 }
140
141                 if ( $empty ) {
142                         // If there are none, we register the widget's existence with a
143                         // generic template
144                         $this->_set(1);
145                         $this->_register_one();
146                 }
147         }
148
149         function _set($number) {
150                 $this->number = $number;
151                 $this->id = $this->id_base . '-' . $number;
152         }
153
154         function _get_display_callback() {
155                 return array(&$this, 'display_callback');
156         }
157
158         function _get_update_callback() {
159                 return array(&$this, 'update_callback');
160         }
161
162         function _get_form_callback() {
163                 return array(&$this, 'form_callback');
164         }
165
166         /** Generate the actual widget content.
167          *      Just finds the instance and calls widget().
168          *      Do NOT over-ride this function. */
169         function display_callback( $args, $widget_args = 1 ) {
170                 if ( is_numeric($widget_args) )
171                         $widget_args = array( 'number' => $widget_args );
172
173                 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
174                 $this->_set( $widget_args['number'] );
175                 $instance = $this->get_settings();
176
177                 if ( array_key_exists( $this->number, $instance ) ) {
178                         $instance = $instance[$this->number];
179                         // filters the widget's settings, return false to stop displaying the widget
180                         $instance = apply_filters('widget_display_callback', $instance, $this, $args);
181                         if ( false !== $instance )
182                                 $this->widget($args, $instance);
183                 }
184         }
185
186         /** Deal with changed settings.
187          *      Do NOT over-ride this function. */
188         function update_callback( $widget_args = 1 ) {
189                 global $wp_registered_widgets;
190
191                 if ( is_numeric($widget_args) )
192                         $widget_args = array( 'number' => $widget_args );
193
194                 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
195                 $all_instances = $this->get_settings();
196
197                 // We need to update the data
198                 if ( $this->updated )
199                         return;
200
201                 $sidebars_widgets = wp_get_sidebars_widgets();
202
203                 if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
204                         // Delete the settings for this instance of the widget
205                         if ( isset($_POST['the-widget-id']) )
206                                 $del_id = $_POST['the-widget-id'];
207                         else
208                                 return;
209
210                         if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
211                                 $number = $wp_registered_widgets[$del_id]['params'][0]['number'];
212
213                                 if ( $this->id_base . '-' . $number == $del_id )
214                                         unset($all_instances[$number]);
215                         }
216                 } else {
217                         if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
218                                 $settings = $_POST['widget-' . $this->id_base];
219                         } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
220                                 $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
221                                 $settings = array( $num => array() );
222                         } else {
223                                 return;
224                         }
225
226                         foreach ( $settings as $number => $new_instance ) {
227                                 $new_instance = stripslashes_deep($new_instance);
228                                 $this->_set($number);
229
230                                 $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
231
232                                 $instance = $this->update($new_instance, $old_instance);
233
234                                 // filters the widget's settings before saving, return false to cancel saving (keep the old settings if updating)
235                                 $instance = apply_filters('widget_update_callback', $instance, $new_instance, $old_instance, $this);
236                                 if ( false !== $instance )
237                                         $all_instances[$number] = $instance;
238
239                                 break; // run only once
240                         }
241                 }
242
243                 $this->save_settings($all_instances);
244                 $this->updated = true;
245         }
246
247         /** Generate the control form.
248          *      Do NOT over-ride this function. */
249         function form_callback( $widget_args = 1 ) {
250                 if ( is_numeric($widget_args) )
251                         $widget_args = array( 'number' => $widget_args );
252
253                 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
254                 $all_instances = $this->get_settings();
255
256                 if ( -1 == $widget_args['number'] ) {
257                         // We echo out a form where 'number' can be set later
258                         $this->_set('__i__');
259                         $instance = array();
260                 } else {
261                         $this->_set($widget_args['number']);
262                         $instance = $all_instances[ $widget_args['number'] ];
263                 }
264
265                 // filters the widget admin form before displaying, return false to stop displaying it
266                 $instance = apply_filters('widget_form_callback', $instance, $this);
267
268                 $return = null;
269                 if ( false !== $instance ) {
270                         $return = $this->form($instance);
271                         // add extra fields in the widget form - be sure to set $return to null if you add any
272                         // if the widget has no form the text echoed from the default form method can be hidden using css
273                         do_action_ref_array( 'in_widget_form', array(&$this, &$return, $instance) );
274                 }
275                 return $return;
276         }
277
278         /** Helper function: Registers a single instance. */
279         function _register_one($number = -1) {
280                 wp_register_sidebar_widget(     $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
281                 _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
282                 _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
283         }
284
285         function save_settings($settings) {
286                 $settings['_multiwidget'] = 1;
287                 update_option( $this->option_name, $settings );
288         }
289
290         function get_settings() {
291                 $settings = get_option($this->option_name);
292
293                 if ( false === $settings && isset($this->alt_option_name) )
294                         $settings = get_option($this->alt_option_name);
295
296                 if ( !is_array($settings) )
297                         $settings = array();
298
299                 if ( !empty($settings) && !array_key_exists('_multiwidget', $settings) ) {
300                         // old format, convert if single widget
301                         $settings = wp_convert_widget_settings($this->id_base, $this->option_name, $settings);
302                 }
303
304                 unset($settings['_multiwidget'], $settings['__i__']);
305                 return $settings;
306         }
307 }
308
309 /**
310  * Singleton that registers and instantiates WP_Widget classes.
311  *
312  * @package WordPress
313  * @subpackage Widgets
314  * @since 2.8
315  */
316 class WP_Widget_Factory {
317         var $widgets = array();
318
319         function WP_Widget_Factory() {
320                 add_action( 'widgets_init', array( &$this, '_register_widgets' ), 100 );
321         }
322
323         function register($widget_class) {
324                 $this->widgets[$widget_class] = new $widget_class();
325         }
326
327         function unregister($widget_class) {
328                 if ( isset($this->widgets[$widget_class]) )
329                         unset($this->widgets[$widget_class]);
330         }
331
332         function _register_widgets() {
333                 global $wp_registered_widgets;
334                 $keys = array_keys($this->widgets);
335                 $registered = array_keys($wp_registered_widgets);
336                 $registered = array_map('_get_widget_id_base', $registered);
337
338                 foreach ( $keys as $key ) {
339                         // don't register new widget if old widget with the same id is already registered
340                         if ( in_array($this->widgets[$key]->id_base, $registered, true) ) {
341                                 unset($this->widgets[$key]);
342                                 continue;
343                         }
344
345                         $this->widgets[$key]->_register();
346                 }
347         }
348 }
349
350 /* Global Variables */
351
352 /** @ignore */
353 global $wp_registered_sidebars, $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates;
354
355 /**
356  * Stores the sidebars, since many themes can have more than one.
357  *
358  * @global array $wp_registered_sidebars
359  * @since 2.2.0
360  */
361 $wp_registered_sidebars = array();
362
363 /**
364  * Stores the registered widgets.
365  *
366  * @global array $wp_registered_widgets
367  * @since 2.2.0
368  */
369 $wp_registered_widgets = array();
370
371 /**
372  * Stores the registered widget control (options).
373  *
374  * @global array $wp_registered_widget_controls
375  * @since 2.2.0
376  */
377 $wp_registered_widget_controls = array();
378 $wp_registered_widget_updates = array();
379
380 /**
381  * Private
382  */
383 $_wp_sidebars_widgets = array();
384
385 /**
386  * Private
387  */
388  $GLOBALS['_wp_deprecated_widgets_callbacks'] = array(
389         'wp_widget_pages',
390         'wp_widget_pages_control',
391         'wp_widget_calendar',
392         'wp_widget_calendar_control',
393         'wp_widget_archives',
394         'wp_widget_archives_control',
395         'wp_widget_links',
396         'wp_widget_meta',
397         'wp_widget_meta_control',
398         'wp_widget_search',
399         'wp_widget_recent_entries',
400         'wp_widget_recent_entries_control',
401         'wp_widget_tag_cloud',
402         'wp_widget_tag_cloud_control',
403         'wp_widget_categories',
404         'wp_widget_categories_control',
405         'wp_widget_text',
406         'wp_widget_text_control',
407         'wp_widget_rss',
408         'wp_widget_rss_control',
409         'wp_widget_recent_comments',
410         'wp_widget_recent_comments_control'
411  );
412
413 /* Template tags & API functions */
414
415 /**
416  * Register a widget
417  *
418  * Registers a WP_Widget widget
419  *
420  * @since 2.8.0
421  *
422  * @see WP_Widget
423  * @see WP_Widget_Factory
424  * @uses WP_Widget_Factory
425  *
426  * @param string $widget_class The name of a class that extends WP_Widget
427  */
428 function register_widget($widget_class) {
429         global $wp_widget_factory;
430
431         $wp_widget_factory->register($widget_class);
432 }
433
434 /**
435  * Unregister a widget
436  *
437  * Unregisters a WP_Widget widget. Useful for unregistering default widgets.
438  * Run within a function hooked to the widgets_init action.
439  *
440  * @since 2.8.0
441  *
442  * @see WP_Widget
443  * @see WP_Widget_Factory
444  * @uses WP_Widget_Factory
445  *
446  * @param string $widget_class The name of a class that extends WP_Widget
447  */
448 function unregister_widget($widget_class) {
449         global $wp_widget_factory;
450
451         $wp_widget_factory->unregister($widget_class);
452 }
453
454 /**
455  * Creates multiple sidebars.
456  *
457  * If you wanted to quickly create multiple sidebars for a theme or internally.
458  * This function will allow you to do so. If you don't pass the 'name' and/or
459  * 'id' in $args, then they will be built for you.
460  *
461  * The default for the name is "Sidebar #", with '#' being replaced with the
462  * number the sidebar is currently when greater than one. If first sidebar, the
463  * name will be just "Sidebar". The default for id is "sidebar-" followed by the
464  * number the sidebar creation is currently at. If the id is provided, and multiple
465  * sidebars are being defined, the id will have "-2" appended, and so on.
466  *
467  * @since 2.2.0
468  *
469  * @see register_sidebar() The second parameter is documented by register_sidebar() and is the same here.
470  * @uses parse_str() Converts a string to an array to be used in the rest of the function.
471  * @uses register_sidebar() Sends single sidebar information [name, id] to this
472  *      function to handle building the sidebar.
473  *
474  * @param int $number Number of sidebars to create.
475  * @param string|array $args Builds Sidebar based off of 'name' and 'id' values.
476  */
477 function register_sidebars($number = 1, $args = array()) {
478         global $wp_registered_sidebars;
479         $number = (int) $number;
480
481         if ( is_string($args) )
482                 parse_str($args, $args);
483
484         for ( $i = 1; $i <= $number; $i++ ) {
485                 $_args = $args;
486
487                 if ( $number > 1 )
488                         $_args['name'] = isset($args['name']) ? sprintf($args['name'], $i) : sprintf(__('Sidebar %d'), $i);
489                 else
490                         $_args['name'] = isset($args['name']) ? $args['name'] : __('Sidebar');
491
492                 // Custom specified ID's are suffixed if they exist already.
493                 // Automatically generated sidebar names need to be suffixed regardless starting at -0
494                 if ( isset($args['id']) ) {
495                         $_args['id'] = $args['id'];
496                         $n = 2; // Start at -2 for conflicting custom ID's
497                         while ( isset($wp_registered_sidebars[$_args['id']]) )
498                                 $_args['id'] = $args['id'] . '-' . $n++;
499                 } else {
500                         $n = count($wp_registered_sidebars);
501                         do {
502                                 $_args['id'] = 'sidebar-' . ++$n;
503                         } while ( isset($wp_registered_sidebars[$_args['id']]) );
504                 }
505                 register_sidebar($_args);
506         }
507 }
508
509 /**
510  * Builds the definition for a single sidebar and returns the ID.
511  *
512  * The $args parameter takes either a string or an array with 'name' and 'id'
513  * contained in either usage. It will be noted that the values will be applied
514  * to all sidebars, so if creating more than one, it will be advised to allow
515  * for WordPress to create the defaults for you.
516  *
517  * Example for string would be <code>'name=whatever;id=whatever1'</code> and for
518  * the array it would be <code>array(
519  *    'name' => 'whatever',
520  *    'id' => 'whatever1')</code>.
521  *
522  * name - The name of the sidebar, which presumably the title which will be
523  *     displayed.
524  * id - The unique identifier by which the sidebar will be called by.
525  * before_widget - The content that will prepended to the widgets when they are
526  *     displayed.
527  * after_widget - The content that will be appended to the widgets when they are
528  *     displayed.
529  * before_title - The content that will be prepended to the title when displayed.
530  * after_title - the content that will be appended to the title when displayed.
531  *
532  * <em>Content</em> is assumed to be HTML and should be formatted as such, but
533  * doesn't have to be.
534  *
535  * @since 2.2.0
536  * @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID.
537  *
538  * @param string|array $args Builds Sidebar based off of 'name' and 'id' values
539  * @return string The sidebar id that was added.
540  */
541 function register_sidebar($args = array()) {
542         global $wp_registered_sidebars;
543
544         $i = count($wp_registered_sidebars) + 1;
545
546         $defaults = array(
547                 'name' => sprintf(__('Sidebar %d'), $i ),
548                 'id' => "sidebar-$i",
549                 'description' => '',
550                 'class' => '',
551                 'before_widget' => '<li id="%1$s" class="widget %2$s">',
552                 'after_widget' => "</li>\n",
553                 'before_title' => '<h2 class="widgettitle">',
554                 'after_title' => "</h2>\n",
555         );
556
557         $sidebar = wp_parse_args( $args, $defaults );
558
559         $wp_registered_sidebars[$sidebar['id']] = $sidebar;
560
561         add_theme_support('widgets');
562
563         do_action( 'register_sidebar', $sidebar );
564
565         return $sidebar['id'];
566 }
567
568 /**
569  * Removes a sidebar from the list.
570  *
571  * @since 2.2.0
572  *
573  * @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID.
574  *
575  * @param string $name The ID of the sidebar when it was added.
576  */
577 function unregister_sidebar( $name ) {
578         global $wp_registered_sidebars;
579
580         if ( isset( $wp_registered_sidebars[$name] ) )
581                 unset( $wp_registered_sidebars[$name] );
582 }
583
584 /**
585  * Register widget for use in sidebars.
586  *
587  * The default widget option is 'classname' that can be override.
588  *
589  * The function can also be used to unregister widgets when $output_callback
590  * parameter is an empty string.
591  *
592  * @since 2.2.0
593  *
594  * @uses $wp_registered_widgets Uses stored registered widgets.
595  * @uses $wp_register_widget_defaults Retrieves widget defaults.
596  *
597  * @param int|string $id Widget ID.
598  * @param string $name Widget display title.
599  * @param callback $output_callback Run when widget is called.
600  * @param array|string $options Optional. Widget Options.
601  * @param mixed $params,... Widget parameters to add to widget.
602  * @return null Will return if $output_callback is empty after removing widget.
603  */
604 function wp_register_sidebar_widget($id, $name, $output_callback, $options = array()) {
605         global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates, $_wp_deprecated_widgets_callbacks;
606
607         $id = strtolower($id);
608
609         if ( empty($output_callback) ) {
610                 unset($wp_registered_widgets[$id]);
611                 return;
612         }
613
614         $id_base = _get_widget_id_base($id);
615         if ( in_array($output_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($output_callback) ) {
616                 if ( isset($wp_registered_widget_controls[$id]) )
617                         unset($wp_registered_widget_controls[$id]);
618
619                 if ( isset($wp_registered_widget_updates[$id_base]) )
620                         unset($wp_registered_widget_updates[$id_base]);
621
622                 return;
623         }
624
625         $defaults = array('classname' => $output_callback);
626         $options = wp_parse_args($options, $defaults);
627         $widget = array(
628                 'name' => $name,
629                 'id' => $id,
630                 'callback' => $output_callback,
631                 'params' => array_slice(func_get_args(), 4)
632         );
633         $widget = array_merge($widget, $options);
634
635         if ( is_callable($output_callback) && ( !isset($wp_registered_widgets[$id]) || did_action( 'widgets_init' ) ) ) {
636                 do_action( 'wp_register_sidebar_widget', $widget );
637                 $wp_registered_widgets[$id] = $widget;
638         }
639 }
640
641 /**
642  * Retrieve description for widget.
643  *
644  * When registering widgets, the options can also include 'description' that
645  * describes the widget for display on the widget administration panel or
646  * in the theme.
647  *
648  * @since 2.5.0
649  *
650  * @param int|string $id Widget ID.
651  * @return string Widget description, if available. Null on failure to retrieve description.
652  */
653 function wp_widget_description( $id ) {
654         if ( !is_scalar($id) )
655                 return;
656
657         global $wp_registered_widgets;
658
659         if ( isset($wp_registered_widgets[$id]['description']) )
660                 return esc_html( $wp_registered_widgets[$id]['description'] );
661 }
662
663 /**
664  * Retrieve description for a sidebar.
665  *
666  * When registering sidebars a 'description' parameter can be included that
667  * describes the sidebar for display on the widget administration panel.
668  *
669  * @since 2.9.0
670  *
671  * @param int|string $id sidebar ID.
672  * @return string Sidebar description, if available. Null on failure to retrieve description.
673  */
674 function wp_sidebar_description( $id ) {
675         if ( !is_scalar($id) )
676                 return;
677
678         global $wp_registered_sidebars;
679
680         if ( isset($wp_registered_sidebars[$id]['description']) )
681                 return esc_html( $wp_registered_sidebars[$id]['description'] );
682 }
683
684
685 /**
686  * Remove widget from sidebar.
687  *
688  * @since 2.2.0
689  *
690  * @param int|string $id Widget ID.
691  */
692 function wp_unregister_sidebar_widget($id) {
693         do_action( 'wp_unregister_sidebar_widget', $id );
694
695         wp_register_sidebar_widget($id, '', '');
696         wp_unregister_widget_control($id);
697 }
698
699 /**
700  * Registers widget control callback for customizing options.
701  *
702  * The options contains the 'height', 'width', and 'id_base' keys. The 'height'
703  * option is never used. The 'width' option is the width of the fully expanded
704  * control form, but try hard to use the default width. The 'id_base' is for
705  * multi-widgets (widgets which allow multiple instances such as the text
706  * widget), an id_base must be provided. The widget id will end up looking like
707  * {$id_base}-{$unique_number}.
708  *
709  * @since 2.2.0
710  *
711  * @param int|string $id Sidebar ID.
712  * @param string $name Sidebar display name.
713  * @param callback $control_callback Run when sidebar is displayed.
714  * @param array|string $options Optional. Widget options. See above long description.
715  * @param mixed $params,... Optional. Additional parameters to add to widget.
716  */
717 function wp_register_widget_control($id, $name, $control_callback, $options = array()) {
718         global $wp_registered_widget_controls, $wp_registered_widget_updates, $wp_registered_widgets, $_wp_deprecated_widgets_callbacks;
719
720         $id = strtolower($id);
721         $id_base = _get_widget_id_base($id);
722
723         if ( empty($control_callback) ) {
724                 unset($wp_registered_widget_controls[$id]);
725                 unset($wp_registered_widget_updates[$id_base]);
726                 return;
727         }
728
729         if ( in_array($control_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($control_callback) ) {
730                 if ( isset($wp_registered_widgets[$id]) )
731                         unset($wp_registered_widgets[$id]);
732
733                 return;
734         }
735
736         if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) )
737                 return;
738
739         $defaults = array('width' => 250, 'height' => 200 ); // height is never used
740         $options = wp_parse_args($options, $defaults);
741         $options['width'] = (int) $options['width'];
742         $options['height'] = (int) $options['height'];
743
744         $widget = array(
745                 'name' => $name,
746                 'id' => $id,
747                 'callback' => $control_callback,
748                 'params' => array_slice(func_get_args(), 4)
749         );
750         $widget = array_merge($widget, $options);
751
752         $wp_registered_widget_controls[$id] = $widget;
753
754         if ( isset($wp_registered_widget_updates[$id_base]) )
755                 return;
756
757         if ( isset($widget['params'][0]['number']) )
758                 $widget['params'][0]['number'] = -1;
759
760         unset($widget['width'], $widget['height'], $widget['name'], $widget['id']);
761         $wp_registered_widget_updates[$id_base] = $widget;
762 }
763
764 function _register_widget_update_callback($id_base, $update_callback, $options = array()) {
765         global $wp_registered_widget_updates;
766
767         if ( isset($wp_registered_widget_updates[$id_base]) ) {
768                 if ( empty($update_callback) )
769                         unset($wp_registered_widget_updates[$id_base]);
770                 return;
771         }
772
773         $widget = array(
774                 'callback' => $update_callback,
775                 'params' => array_slice(func_get_args(), 3)
776         );
777
778         $widget = array_merge($widget, $options);
779         $wp_registered_widget_updates[$id_base] = $widget;
780 }
781
782 function _register_widget_form_callback($id, $name, $form_callback, $options = array()) {
783         global $wp_registered_widget_controls;
784
785         $id = strtolower($id);
786
787         if ( empty($form_callback) ) {
788                 unset($wp_registered_widget_controls[$id]);
789                 return;
790         }
791
792         if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) )
793                 return;
794
795         $defaults = array('width' => 250, 'height' => 200 );
796         $options = wp_parse_args($options, $defaults);
797         $options['width'] = (int) $options['width'];
798         $options['height'] = (int) $options['height'];
799
800         $widget = array(
801                 'name' => $name,
802                 'id' => $id,
803                 'callback' => $form_callback,
804                 'params' => array_slice(func_get_args(), 4)
805         );
806         $widget = array_merge($widget, $options);
807
808         $wp_registered_widget_controls[$id] = $widget;
809 }
810
811 /**
812  * Remove control callback for widget.
813  *
814  * @since 2.2.0
815  * @uses wp_register_widget_control() Unregisters by using empty callback.
816  *
817  * @param int|string $id Widget ID.
818  */
819 function wp_unregister_widget_control($id) {
820         return wp_register_widget_control($id, '', '');
821 }
822
823 /**
824  * Display dynamic sidebar.
825  *
826  * By default it displays the default sidebar or 'sidebar-1'. The 'sidebar-1' is
827  * not named by the theme, the actual name is '1', but 'sidebar-' is added to
828  * the registered sidebars for the name. If you named your sidebar 'after-post',
829  * then the parameter $index will still be 'after-post', but the lookup will be
830  * for 'sidebar-after-post'.
831  *
832  * It is confusing for the $index parameter, but just know that it should just
833  * work. When you register the sidebar in the theme, you will use the same name
834  * for this function or "Pay no heed to the man behind the curtain." Just accept
835  * it as an oddity of WordPress sidebar register and display.
836  *
837  * @since 2.2.0
838  *
839  * @param int|string $index Optional, default is 1. Name or ID of dynamic sidebar.
840  * @return bool True, if widget sidebar was found and called. False if not found or not called.
841  */
842 function dynamic_sidebar($index = 1) {
843         global $wp_registered_sidebars, $wp_registered_widgets;
844
845         if ( is_int($index) ) {
846                 $index = "sidebar-$index";
847         } else {
848                 $index = sanitize_title($index);
849                 foreach ( (array) $wp_registered_sidebars as $key => $value ) {
850                         if ( sanitize_title($value['name']) == $index ) {
851                                 $index = $key;
852                                 break;
853                         }
854                 }
855         }
856
857         $sidebars_widgets = wp_get_sidebars_widgets();
858         if ( empty( $sidebars_widgets ) )
859                 return false;
860
861         if ( empty($wp_registered_sidebars[$index]) || !array_key_exists($index, $sidebars_widgets) || !is_array($sidebars_widgets[$index]) || empty($sidebars_widgets[$index]) )
862                 return false;
863
864         $sidebar = $wp_registered_sidebars[$index];
865
866         $did_one = false;
867         foreach ( (array) $sidebars_widgets[$index] as $id ) {
868
869                 if ( !isset($wp_registered_widgets[$id]) ) continue;
870
871                 $params = array_merge(
872                         array( array_merge( $sidebar, array('widget_id' => $id, 'widget_name' => $wp_registered_widgets[$id]['name']) ) ),
873                         (array) $wp_registered_widgets[$id]['params']
874                 );
875
876                 // Substitute HTML id and class attributes into before_widget
877                 $classname_ = '';
878                 foreach ( (array) $wp_registered_widgets[$id]['classname'] as $cn ) {
879                         if ( is_string($cn) )
880                                 $classname_ .= '_' . $cn;
881                         elseif ( is_object($cn) )
882                                 $classname_ .= '_' . get_class($cn);
883                 }
884                 $classname_ = ltrim($classname_, '_');
885                 $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_);
886
887                 $params = apply_filters( 'dynamic_sidebar_params', $params );
888
889                 $callback = $wp_registered_widgets[$id]['callback'];
890
891                 do_action( 'dynamic_sidebar', $wp_registered_widgets[$id] );
892
893                 if ( is_callable($callback) ) {
894                         call_user_func_array($callback, $params);
895                         $did_one = true;
896                 }
897         }
898
899         return $did_one;
900 }
901
902 /**
903  * Whether widget is displayed on the front-end.
904  *
905  * Either $callback or $id_base can be used
906  * $id_base is the first argument when extending WP_Widget class
907  * Without the optional $widget_id parameter, returns the ID of the first sidebar
908  * in which the first instance of the widget with the given callback or $id_base is found.
909  * With the $widget_id parameter, returns the ID of the sidebar where
910  * the widget with that callback/$id_base AND that ID is found.
911  *
912  * NOTE: $widget_id and $id_base are the same for single widgets. To be effective
913  * this function has to run after widgets have initialized, at action 'init' or later.
914  *
915  * @since 2.2.0
916  *
917  * @param string $callback Optional, Widget callback to check.
918  * @param int $widget_id Optional, but needed for checking. Widget ID.
919  * @param string $id_base Optional, the base ID of a widget created by extending WP_Widget.
920  * @param bool $skip_inactive Optional, whether to check in 'wp_inactive_widgets'.
921  * @return mixed false if widget is not active or id of sidebar in which the widget is active.
922  */
923 function is_active_widget($callback = false, $widget_id = false, $id_base = false, $skip_inactive = true) {
924         global $wp_registered_widgets;
925
926         $sidebars_widgets = wp_get_sidebars_widgets();
927
928         if ( is_array($sidebars_widgets) ) {
929                 foreach ( $sidebars_widgets as $sidebar => $widgets ) {
930                         if ( $skip_inactive && 'wp_inactive_widgets' == $sidebar )
931                                 continue;
932
933                         if ( is_array($widgets) ) {
934                                 foreach ( $widgets as $widget ) {
935                                         if ( ( $callback && isset($wp_registered_widgets[$widget]['callback']) && $wp_registered_widgets[$widget]['callback'] == $callback ) || ( $id_base && _get_widget_id_base($widget) == $id_base ) ) {
936                                                 if ( !$widget_id || $widget_id == $wp_registered_widgets[$widget]['id'] )
937                                                         return $sidebar;
938                                         }
939                                 }
940                         }
941                 }
942         }
943         return false;
944 }
945
946 /**
947  * Whether the dynamic sidebar is enabled and used by theme.
948  *
949  * @since 2.2.0
950  *
951  * @return bool True, if using widgets. False, if not using widgets.
952  */
953 function is_dynamic_sidebar() {
954         global $wp_registered_widgets, $wp_registered_sidebars;
955         $sidebars_widgets = get_option('sidebars_widgets');
956         foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) {
957                 if ( count($sidebars_widgets[$index]) ) {
958                         foreach ( (array) $sidebars_widgets[$index] as $widget )
959                                 if ( array_key_exists($widget, $wp_registered_widgets) )
960                                         return true;
961                 }
962         }
963         return false;
964 }
965
966 /**
967  * Whether a sidebar is in use.
968  *
969  * @since 2.8
970  *
971  * @param mixed $index Sidebar name, id or number to check.
972  * @return bool true if the sidebar is in use, false otherwise.
973  */
974 function is_active_sidebar( $index ) {
975         $index = ( is_int($index) ) ? "sidebar-$index" : sanitize_title($index);
976         $sidebars_widgets = wp_get_sidebars_widgets();
977         if ( !empty($sidebars_widgets[$index]) )
978                 return true;
979
980         return false;
981 }
982
983 /* Internal Functions */
984
985 /**
986  * Retrieve full list of sidebars and their widgets.
987  *
988  * Will upgrade sidebar widget list, if needed. Will also save updated list, if
989  * needed.
990  *
991  * @since 2.2.0
992  * @access private
993  *
994  * @param bool $deprecated Not used (deprecated).
995  * @return array Upgraded list of widgets to version 3 array format when called from the admin.
996  */
997 function wp_get_sidebars_widgets($deprecated = true) {
998         if ( $deprecated !== true )
999                 _deprecated_argument( __FUNCTION__, '2.8.1' );
1000
1001         global $wp_registered_widgets, $_wp_sidebars_widgets, $sidebars_widgets;
1002
1003         // If loading from front page, consult $_wp_sidebars_widgets rather than options
1004         // to see if wp_convert_widget_settings() has made manipulations in memory.
1005         if ( !is_admin() ) {
1006                 if ( empty($_wp_sidebars_widgets) )
1007                         $_wp_sidebars_widgets = get_option('sidebars_widgets', array());
1008
1009                 $sidebars_widgets = $_wp_sidebars_widgets;
1010         } else {
1011                 $sidebars_widgets = get_option('sidebars_widgets', array());
1012         }
1013
1014         if ( is_array( $sidebars_widgets ) && isset($sidebars_widgets['array_version']) )
1015                 unset($sidebars_widgets['array_version']);
1016
1017         $sidebars_widgets = apply_filters('sidebars_widgets', $sidebars_widgets);
1018         return $sidebars_widgets;
1019 }
1020
1021 /**
1022  * Set the sidebar widget option to update sidebars.
1023  *
1024  * @since 2.2.0
1025  * @access private
1026  *
1027  * @param array $sidebars_widgets Sidebar widgets and their settings.
1028  */
1029 function wp_set_sidebars_widgets( $sidebars_widgets ) {
1030         if ( !isset( $sidebars_widgets['array_version'] ) )
1031                 $sidebars_widgets['array_version'] = 3;
1032         update_option( 'sidebars_widgets', $sidebars_widgets );
1033 }
1034
1035 /**
1036  * Retrieve default registered sidebars list.
1037  *
1038  * @since 2.2.0
1039  * @access private
1040  *
1041  * @return array
1042  */
1043 function wp_get_widget_defaults() {
1044         global $wp_registered_sidebars;
1045
1046         $defaults = array();
1047
1048         foreach ( (array) $wp_registered_sidebars as $index => $sidebar )
1049                 $defaults[$index] = array();
1050
1051         return $defaults;
1052 }
1053
1054 /**
1055  * Convert the widget settings from single to multi-widget format.
1056  *
1057  * @since 2.8.0
1058  *
1059  * @return array
1060  */
1061 function wp_convert_widget_settings($base_name, $option_name, $settings) {
1062         // This test may need expanding.
1063         $single = $changed = false;
1064         if ( empty($settings) ) {
1065                 $single = true;
1066         } else {
1067                 foreach ( array_keys($settings) as $number ) {
1068                         if ( 'number' == $number )
1069                                 continue;
1070                         if ( !is_numeric($number) ) {
1071                                 $single = true;
1072                                 break;
1073                         }
1074                 }
1075         }
1076
1077         if ( $single ) {
1078                 $settings = array( 2 => $settings );
1079
1080                 // If loading from the front page, update sidebar in memory but don't save to options
1081                 if ( is_admin() ) {
1082                         $sidebars_widgets = get_option('sidebars_widgets');
1083                 } else {
1084                         if ( empty($GLOBALS['_wp_sidebars_widgets']) )
1085                                 $GLOBALS['_wp_sidebars_widgets'] = get_option('sidebars_widgets', array());
1086                         $sidebars_widgets = &$GLOBALS['_wp_sidebars_widgets'];
1087                 }
1088
1089                 foreach ( (array) $sidebars_widgets as $index => $sidebar ) {
1090                         if ( is_array($sidebar) ) {
1091                                 foreach ( $sidebar as $i => $name ) {
1092                                         if ( $base_name == $name ) {
1093                                                 $sidebars_widgets[$index][$i] = "$name-2";
1094                                                 $changed = true;
1095                                                 break 2;
1096                                         }
1097                                 }
1098                         }
1099                 }
1100
1101                 if ( is_admin() && $changed )
1102                         update_option('sidebars_widgets', $sidebars_widgets);
1103         }
1104
1105         $settings['_multiwidget'] = 1;
1106         if ( is_admin() )
1107                 update_option( $option_name, $settings );
1108
1109         return $settings;
1110 }
1111
1112 /**
1113  * Output an arbitrary widget as a template tag
1114  *
1115  * @since 2.8
1116  *
1117  * @param string $widget the widget's PHP class name (see default-widgets.php)
1118  * @param array $instance the widget's instance settings
1119  * @param array $args the widget's sidebar args
1120  * @return void
1121  **/
1122 function the_widget($widget, $instance = array(), $args = array()) {
1123         global $wp_widget_factory;
1124
1125         $widget_obj = $wp_widget_factory->widgets[$widget];
1126         if ( !is_a($widget_obj, 'WP_Widget') )
1127                 return;
1128
1129         $before_widget = sprintf('<div class="widget %s">', $widget_obj->widget_options['classname'] );
1130         $default_args = array( 'before_widget' => $before_widget, 'after_widget' => "</div>", 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>' );
1131
1132         $args = wp_parse_args($args, $default_args);
1133         $instance = wp_parse_args($instance);
1134
1135         do_action( 'the_widget', $widget, $instance, $args );
1136
1137         $widget_obj->_set(-1);
1138         $widget_obj->widget($args, $instance);
1139 }
1140
1141 /**
1142  * Private
1143  */
1144 function _get_widget_id_base($id) {
1145         return preg_replace( '/-[0-9]+$/', '', $id );
1146 }
1147
1148 /**
1149  * Handle sidebars config after theme change
1150  *
1151  * @access private
1152  * @since 3.3
1153  */
1154 function _wp_sidebars_changed() {
1155         global $sidebars_widgets;
1156
1157         if ( ! is_array( $sidebars_widgets ) )
1158                 $sidebars_widgets = wp_get_sidebars_widgets();
1159
1160         retrieve_widgets(true);
1161 }
1162
1163 // look for "lost" widgets, this has to run at least on each theme change
1164 function retrieve_widgets($theme_changed = false) {
1165         global $wp_registered_widget_updates, $wp_registered_sidebars, $sidebars_widgets, $wp_registered_widgets;
1166
1167         $registered_sidebar_keys = array_keys( $wp_registered_sidebars );
1168         $orphaned = 0;
1169
1170         $old_sidebars_widgets = get_theme_mod( 'sidebars_widgets' );
1171         if ( is_array( $old_sidebars_widgets ) ) {
1172                 // time() that sidebars were stored is in $old_sidebars_widgets['time']
1173                 $_sidebars_widgets = $old_sidebars_widgets['data'];
1174                 remove_theme_mod( 'sidebars_widgets' );
1175
1176                 foreach ( $_sidebars_widgets as $sidebar => $widgets ) {
1177                         if ( 'wp_inactive_widgets' == $sidebar || 'orphaned_widgets' == substr( $sidebar, 0, 16 ) )
1178                                 continue;
1179
1180                         if ( !in_array( $sidebar, $registered_sidebar_keys ) ) {
1181                                 $_sidebars_widgets['orphaned_widgets_' . ++$orphaned] = $widgets;
1182                                 unset( $_sidebars_widgets[$sidebar] );
1183                         }
1184                 }
1185         } else {
1186                 if ( empty( $sidebars_widgets ) )
1187                         return;
1188
1189                 unset( $sidebars_widgets['array_version'] );
1190
1191                 $old = array_keys($sidebars_widgets);
1192                 sort($old);
1193                 sort($registered_sidebar_keys);
1194
1195                 if ( $old == $registered_sidebar_keys )
1196                         return;
1197
1198                 $_sidebars_widgets = array(
1199                         'wp_inactive_widgets' => !empty( $sidebars_widgets['wp_inactive_widgets'] ) ? $sidebars_widgets['wp_inactive_widgets'] : array()
1200                 );
1201
1202                 unset( $sidebars_widgets['wp_inactive_widgets'] );
1203
1204                 foreach ( $wp_registered_sidebars as $id => $settings ) {
1205                         if ( $theme_changed ) {
1206                                 $_sidebars_widgets[$id] = array_shift( $sidebars_widgets );
1207                         } else {
1208                                 // no theme change, grab only sidebars that are currently registered
1209                                 if ( isset( $sidebars_widgets[$id] ) ) {
1210                                         $_sidebars_widgets[$id] = $sidebars_widgets[$id];
1211                                         unset( $sidebars_widgets[$id] );
1212                                 }
1213                         }
1214                 }
1215
1216                 foreach ( $sidebars_widgets as $val ) {
1217                         if ( is_array($val) && ! empty( $val ) )
1218                                 $_sidebars_widgets['orphaned_widgets_' . ++$orphaned] = $val;
1219                 }
1220         }
1221
1222         // discard invalid, theme-specific widgets from sidebars
1223         $shown_widgets = array();
1224
1225         foreach ( $_sidebars_widgets as $sidebar => $widgets ) {
1226                 if ( !is_array($widgets) )
1227                         continue;
1228
1229                 $_widgets = array();
1230                 foreach ( $widgets as $widget ) {
1231                         if ( isset($wp_registered_widgets[$widget]) )
1232                                 $_widgets[] = $widget;
1233                 }
1234
1235                 $_sidebars_widgets[$sidebar] = $_widgets;
1236                 $shown_widgets = array_merge($shown_widgets, $_widgets);
1237         }
1238
1239         $sidebars_widgets = $_sidebars_widgets;
1240         unset($_sidebars_widgets, $_widgets);
1241
1242         // find hidden/lost multi-widget instances
1243         $lost_widgets = array();
1244         foreach ( $wp_registered_widgets as $key => $val ) {
1245                 if ( in_array($key, $shown_widgets, true) )
1246                         continue;
1247
1248                 $number = preg_replace('/.+?-([0-9]+)$/', '$1', $key);
1249
1250                 if ( 2 > (int) $number )
1251                         continue;
1252
1253                 $lost_widgets[] = $key;
1254         }
1255
1256         $sidebars_widgets['wp_inactive_widgets'] = array_merge($lost_widgets, (array) $sidebars_widgets['wp_inactive_widgets']);
1257         wp_set_sidebars_widgets($sidebars_widgets);
1258
1259         return $sidebars_widgets;
1260 }