]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-widget.php
WordPress 4.5
[autoinstalls/wordpress.git] / wp-includes / class-wp-widget.php
1 <?php
2 /**
3  * Widget API: WP_Widget base class
4  *
5  * @package WordPress
6  * @subpackage Widgets
7  * @since 4.4.0
8  */
9
10 /**
11  * Core base class extended to register widgets.
12  *
13  * This class must be extended for each widget and WP_Widget::widget(), WP_Widget::update()
14  * and WP_Widget::form() need to be overridden.
15  *
16  * @since 2.8.0
17  * @since 4.4.0 Moved to its own file from wp-includes/widgets.php
18  */
19 class WP_Widget {
20
21         /**
22          * Root ID for all widgets of this type.
23          *
24          * @since 2.8.0
25          * @access public
26          * @var mixed|string
27          */
28         public $id_base;
29
30         /**
31          * Name for this widget type.
32          *
33          * @since 2.8.0
34          * @access public
35          * @var string
36          */
37         public $name;
38
39         /**
40          * Option array passed to wp_register_sidebar_widget().
41          *
42          * @since 2.8.0
43          * @access public
44          * @var array
45          */
46         public $widget_options;
47
48         /**
49          * Option array passed to wp_register_widget_control().
50          *
51          * @since 2.8.0
52          * @access public
53          * @var array
54          */
55         public $control_options;
56
57         /**
58          * Unique ID number of the current instance.
59          *
60          * @since 2.8.0
61          * @access public
62          * @var bool|int
63          */
64         public $number = false;
65
66         /**
67          * Unique ID string of the current instance (id_base-number).
68          *
69          * @since 2.8.0
70          * @access public
71          * @var bool|string
72          */
73         public $id = false;
74
75         /**
76          * Whether the widget data has been updated.
77          *
78          * Set to true when the data is updated after a POST submit - ensures it does
79          * not happen twice.
80          *
81          * @since 2.8.0
82          * @access public
83          * @var bool
84          */
85         public $updated = false;
86
87         //
88         // Member functions that must be overriden by subclasses.
89         //
90
91         /**
92          * Echoes the widget content.
93          *
94          * Sub-classes should over-ride this function to generate their widget code.
95          *
96          * @since 2.8.0
97          * @access public
98          *
99          * @param array $args     Display arguments including 'before_title', 'after_title',
100          *                        'before_widget', and 'after_widget'.
101          * @param array $instance The settings for the particular instance of the widget.
102          */
103         public function widget( $args, $instance ) {
104                 die('function WP_Widget::widget() must be over-ridden in a sub-class.');
105         }
106
107         /**
108          * Updates a particular instance of a widget.
109          *
110          * This function should check that `$new_instance` is set correctly. The newly-calculated
111          * value of `$instance` should be returned. If false is returned, the instance won't be
112          * saved/updated.
113          *
114          * @since 2.8.0
115          * @access public
116          *
117          * @param array $new_instance New settings for this instance as input by the user via
118          *                            WP_Widget::form().
119          * @param array $old_instance Old settings for this instance.
120          * @return array Settings to save or bool false to cancel saving.
121          */
122         public function update( $new_instance, $old_instance ) {
123                 return $new_instance;
124         }
125
126         /**
127          * Outputs the settings update form.
128          *
129          * @since 2.8.0
130          * @access public
131          *
132          * @param array $instance Current settings.
133          * @return string Default return is 'noform'.
134          */
135         public function form( $instance ) {
136                 echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>';
137                 return 'noform';
138         }
139
140         // Functions you'll need to call.
141
142         /**
143          * PHP5 constructor.
144          *
145          * @since 2.8.0
146          * @access public
147          *
148          * @param string $id_base         Optional Base ID for the widget, lowercase and unique. If left empty,
149          *                                a portion of the widget's class name will be used Has to be unique.
150          * @param string $name            Name for the widget displayed on the configuration page.
151          * @param array  $widget_options  Optional. Widget options. See wp_register_sidebar_widget() for information
152          *                                on accepted arguments. Default empty array.
153          * @param array  $control_options Optional. Widget control options. See wp_register_widget_control() for
154          *                                information on accepted arguments. Default empty array.
155          */
156         public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
157                 $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
158                 $this->name = $name;
159                 $this->option_name = 'widget_' . $this->id_base;
160                 $this->widget_options = wp_parse_args( $widget_options, array( 'classname' => $this->option_name, 'customize_selective_refresh' => false ) );
161                 $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) );
162         }
163
164         /**
165          * PHP4 constructor.
166          *
167          * @since 2.8.0
168          * @access public
169          *
170          * @see __construct()
171          * 
172          * @param string $id_base         Optional Base ID for the widget, lowercase and unique. If left empty,
173          *                                a portion of the widget's class name will be used Has to be unique.
174          * @param string $name            Name for the widget displayed on the configuration page.
175          * @param array  $widget_options  Optional. Widget options. See wp_register_sidebar_widget() for information
176          *                                on accepted arguments. Default empty array.
177          * @param array  $control_options Optional. Widget control options. See wp_register_widget_control() for
178          *                                information on accepted arguments. Default empty array.
179          */
180         public function WP_Widget( $id_base, $name, $widget_options = array(), $control_options = array() ) {
181                 _deprecated_constructor( 'WP_Widget', '4.3.0', get_class( $this ) );
182                 WP_Widget::__construct( $id_base, $name, $widget_options, $control_options );
183         }
184
185         /**
186          * Constructs name attributes for use in form() fields
187          *
188          * This function should be used in form() methods to create name attributes for fields
189          * to be saved by update()
190          *
191          * @since 2.8.0
192          * @since 4.4.0 Array format field names are now accepted.
193          * @access public
194          *
195          * @param string $field_name Field name
196          * @return string Name attribute for $field_name
197          */
198         public function get_field_name($field_name) {
199                 if ( false === $pos = strpos( $field_name, '[' ) ) {
200                         return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
201                 } else {
202                         return 'widget-' . $this->id_base . '[' . $this->number . '][' . substr_replace( $field_name, '][', $pos, strlen( '[' ) );
203                 }
204         }
205
206         /**
207          * Constructs id attributes for use in WP_Widget::form() fields.
208          *
209          * This function should be used in form() methods to create id attributes
210          * for fields to be saved by WP_Widget::update().
211          *
212          * @since 2.8.0
213          * @since 4.4.0 Array format field IDs are now accepted.
214          * @access public
215          *
216          * @param string $field_name Field name.
217          * @return string ID attribute for `$field_name`.
218          */
219         public function get_field_id( $field_name ) {
220                 return 'widget-' . $this->id_base . '-' . $this->number . '-' . trim( str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ), '-' );
221         }
222
223         /**
224          * Register all widget instances of this widget class.
225          *
226          * @since 2.8.0
227          * @access public
228          */
229         public function _register() {
230                 $settings = $this->get_settings();
231                 $empty = true;
232
233                 // When $settings is an array-like object, get an intrinsic array for use with array_keys().
234                 if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
235                         $settings = $settings->getArrayCopy();
236                 }
237
238                 if ( is_array( $settings ) ) {
239                         foreach ( array_keys( $settings ) as $number ) {
240                                 if ( is_numeric( $number ) ) {
241                                         $this->_set( $number );
242                                         $this->_register_one( $number );
243                                         $empty = false;
244                                 }
245                         }
246                 }
247
248                 if ( $empty ) {
249                         // If there are none, we register the widget's existence with a generic template.
250                         $this->_set( 1 );
251                         $this->_register_one();
252                 }
253         }
254
255         /**
256          * Sets the internal order number for the widget instance.
257          *
258          * @since 2.8.0
259          * @access public
260          *
261          * @param int $number The unique order number of this widget instance compared to other
262          *                    instances of the same class.
263          */
264         public function _set($number) {
265                 $this->number = $number;
266                 $this->id = $this->id_base . '-' . $number;
267         }
268
269         /**
270          * Retrieves the widget display callback.
271          *
272          * @since 2.8.0
273          * @access public
274          *
275          * @return callable Display callback.
276          */
277         public function _get_display_callback() {
278                 return array($this, 'display_callback');
279         }
280
281         /**
282          * Retrieves the widget update callback.
283          *
284          * @since 2.8.0
285          * @access public
286          *
287          * @return callable Update callback.
288          */
289         public function _get_update_callback() {
290                 return array($this, 'update_callback');
291         }
292
293         /**
294          * Retrieves the form callback.
295          *
296          * @since 2.8.0
297          * @access public
298          *
299          * @return callable Form callback.
300          */
301         public function _get_form_callback() {
302                 return array($this, 'form_callback');
303         }
304
305         /**
306          * Determines whether the current request is inside the Customizer preview.
307          *
308          * If true -- the current request is inside the Customizer preview, then
309          * the object cache gets suspended and widgets should check this to decide
310          * whether they should store anything persistently to the object cache,
311          * to transients, or anywhere else.
312          *
313          * @since 3.9.0
314          * @access public
315          *
316          * @global WP_Customize_Manager $wp_customize
317          *
318          * @return bool True if within the Customizer preview, false if not.
319          */
320         public function is_preview() {
321                 global $wp_customize;
322                 return ( isset( $wp_customize ) && $wp_customize->is_preview() ) ;
323         }
324
325         /**
326          * Generates the actual widget content (Do NOT override).
327          *
328          * Finds the instance and calls WP_Widget::widget().
329          *
330          * @since 2.8.0
331          * @access public
332          *
333          * @param array     $args        Display arguments. See WP_Widget::widget() for information
334          *                               on accepted arguments.
335          * @param int|array $widget_args {
336          *     Optional. Internal order number of the widget instance, or array of multi-widget arguments.
337          *     Default 1.
338          *
339          *     @type int $number Number increment used for multiples of the same widget.
340          * }
341          */
342         public function display_callback( $args, $widget_args = 1 ) {
343                 if ( is_numeric( $widget_args ) ) {
344                         $widget_args = array( 'number' => $widget_args );
345                 }
346
347                 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
348                 $this->_set( $widget_args['number'] );
349                 $instances = $this->get_settings();
350
351                 if ( array_key_exists( $this->number, $instances ) ) {
352                         $instance = $instances[ $this->number ];
353
354                         /**
355                          * Filter the settings for a particular widget instance.
356                          *
357                          * Returning false will effectively short-circuit display of the widget.
358                          *
359                          * @since 2.8.0
360                          *
361                          * @param array     $instance The current widget instance's settings.
362                          * @param WP_Widget $this     The current widget instance.
363                          * @param array     $args     An array of default widget arguments.
364                          */
365                         $instance = apply_filters( 'widget_display_callback', $instance, $this, $args );
366
367                         if ( false === $instance ) {
368                                 return;
369                         }
370
371                         $was_cache_addition_suspended = wp_suspend_cache_addition();
372                         if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
373                                 wp_suspend_cache_addition( true );
374                         }
375
376                         $this->widget( $args, $instance );
377
378                         if ( $this->is_preview() ) {
379                                 wp_suspend_cache_addition( $was_cache_addition_suspended );
380                         }
381                 }
382         }
383
384         /**
385          * Handles changed settings (Do NOT override).
386          *
387          * @since 2.8.0
388          * @access public
389          *
390          * @global array $wp_registered_widgets
391          *
392          * @param int $deprecated Not used.
393          */
394         public function update_callback( $deprecated = 1 ) {
395                 global $wp_registered_widgets;
396
397                 $all_instances = $this->get_settings();
398
399                 // We need to update the data
400                 if ( $this->updated )
401                         return;
402
403                 if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
404                         // Delete the settings for this instance of the widget
405                         if ( isset($_POST['the-widget-id']) )
406                                 $del_id = $_POST['the-widget-id'];
407                         else
408                                 return;
409
410                         if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
411                                 $number = $wp_registered_widgets[$del_id]['params'][0]['number'];
412
413                                 if ( $this->id_base . '-' . $number == $del_id )
414                                         unset($all_instances[$number]);
415                         }
416                 } else {
417                         if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
418                                 $settings = $_POST['widget-' . $this->id_base];
419                         } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
420                                 $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
421                                 $settings = array( $num => array() );
422                         } else {
423                                 return;
424                         }
425
426                         foreach ( $settings as $number => $new_instance ) {
427                                 $new_instance = stripslashes_deep($new_instance);
428                                 $this->_set($number);
429
430                                 $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
431
432                                 $was_cache_addition_suspended = wp_suspend_cache_addition();
433                                 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
434                                         wp_suspend_cache_addition( true );
435                                 }
436
437                                 $instance = $this->update( $new_instance, $old_instance );
438
439                                 if ( $this->is_preview() ) {
440                                         wp_suspend_cache_addition( $was_cache_addition_suspended );
441                                 }
442
443                                 /**
444                                  * Filter a widget's settings before saving.
445                                  *
446                                  * Returning false will effectively short-circuit the widget's ability
447                                  * to update settings.
448                                  *
449                                  * @since 2.8.0
450                                  *
451                                  * @param array     $instance     The current widget instance's settings.
452                                  * @param array     $new_instance Array of new widget settings.
453                                  * @param array     $old_instance Array of old widget settings.
454                                  * @param WP_Widget $this         The current widget instance.
455                                  */
456                                 $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
457                                 if ( false !== $instance ) {
458                                         $all_instances[$number] = $instance;
459                                 }
460
461                                 break; // run only once
462                         }
463                 }
464
465                 $this->save_settings($all_instances);
466                 $this->updated = true;
467         }
468
469         /**
470          * Generates the widget control form (Do NOT override).
471          *
472          * @since 2.8.0
473          * @access public
474          *
475          * @param int|array $widget_args {
476          *     Optional. Internal order number of the widget instance, or array of multi-widget arguments.
477          *     Default 1.
478          *
479          *     @type int $number Number increment used for multiples of the same widget.
480          * }
481          * @return string|null
482          */
483         public function form_callback( $widget_args = 1 ) {
484                 if ( is_numeric($widget_args) )
485                         $widget_args = array( 'number' => $widget_args );
486
487                 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
488                 $all_instances = $this->get_settings();
489
490                 if ( -1 == $widget_args['number'] ) {
491                         // We echo out a form where 'number' can be set later
492                         $this->_set('__i__');
493                         $instance = array();
494                 } else {
495                         $this->_set($widget_args['number']);
496                         $instance = $all_instances[ $widget_args['number'] ];
497                 }
498
499                 /**
500                  * Filter the widget instance's settings before displaying the control form.
501                  *
502                  * Returning false effectively short-circuits display of the control form.
503                  *
504                  * @since 2.8.0
505                  *
506                  * @param array     $instance The current widget instance's settings.
507                  * @param WP_Widget $this     The current widget instance.
508                  */
509                 $instance = apply_filters( 'widget_form_callback', $instance, $this );
510
511                 $return = null;
512                 if ( false !== $instance ) {
513                         $return = $this->form($instance);
514
515                         /**
516                          * Fires at the end of the widget control form.
517                          *
518                          * Use this hook to add extra fields to the widget form. The hook
519                          * is only fired if the value passed to the 'widget_form_callback'
520                          * hook is not false.
521                          *
522                          * Note: If the widget has no form, the text echoed from the default
523                          * form method can be hidden using CSS.
524                          *
525                          * @since 2.8.0
526                          *
527                          * @param WP_Widget $this     The widget instance, passed by reference.
528                          * @param null      $return   Return null if new fields are added.
529                          * @param array     $instance An array of the widget's settings.
530                          */
531                         do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
532                 }
533                 return $return;
534         }
535
536         /**
537          * Registers an instance of the widget class.
538          *
539          * @since 2.8.0
540          * @access public
541          *
542          * @param integer $number Optional. The unique order number of this widget instance
543          *                        compared to other instances of the same class. Default -1.
544          */
545         public function _register_one( $number = -1 ) {
546                 wp_register_sidebar_widget(     $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
547                 _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
548                 _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
549         }
550
551         /**
552          * Saves the settings for all instances of the widget class.
553          *
554          * @since 2.8.0
555          * @access public
556          *
557          * @param array $settings Multi-dimensional array of widget instance settings.
558          */
559         public function save_settings( $settings ) {
560                 $settings['_multiwidget'] = 1;
561                 update_option( $this->option_name, $settings );
562         }
563
564         /**
565          * Retrieves the settings for all instances of the widget class.
566          *
567          * @since 2.8.0
568          * @access public
569          *
570          * @return array Multi-dimensional array of widget instance settings.
571          */
572         public function get_settings() {
573
574                 $settings = get_option( $this->option_name );
575
576                 if ( false === $settings ) {
577                         if ( isset( $this->alt_option_name ) ) {
578                                 $settings = get_option( $this->alt_option_name );
579                         } else {
580                                 // Save an option so it can be autoloaded next time.
581                                 $this->save_settings( array() );
582                         }
583                 }
584
585                 if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) {
586                         $settings = array();
587                 }
588
589                 if ( ! empty( $settings ) && ! isset( $settings['_multiwidget'] ) ) {
590                         // Old format, convert if single widget.
591                         $settings = wp_convert_widget_settings( $this->id_base, $this->option_name, $settings );
592                 }
593
594                 unset( $settings['_multiwidget'], $settings['__i__'] );
595                 return $settings;
596         }
597 }