]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/customize/class-wp-customize-nav-menu-setting.php
WordPress 4.5
[autoinstalls/wordpress.git] / wp-includes / customize / class-wp-customize-nav-menu-setting.php
1 <?php
2 /**
3  * Customize API: WP_Customize_Nav_Menu_Setting class
4  *
5  * @package WordPress
6  * @subpackage Customize
7  * @since 4.4.0
8  */
9
10 /**
11  * Customize Setting to represent a nav_menu.
12  *
13  * Subclass of WP_Customize_Setting to represent a nav_menu taxonomy term, and
14  * the IDs for the nav_menu_items associated with the nav menu.
15  *
16  * @since 4.3.0
17  *
18  * @see wp_get_nav_menu_object()
19  * @see WP_Customize_Setting
20  */
21 class WP_Customize_Nav_Menu_Setting extends WP_Customize_Setting {
22
23         const ID_PATTERN = '/^nav_menu\[(?P<id>-?\d+)\]$/';
24
25         const TAXONOMY = 'nav_menu';
26
27         const TYPE = 'nav_menu';
28
29         /**
30          * Setting type.
31          *
32          * @since 4.3.0
33          * @access public
34          * @var string
35          */
36         public $type = self::TYPE;
37
38         /**
39          * Default setting value.
40          *
41          * @since 4.3.0
42          * @access public
43          * @var array
44          *
45          * @see wp_get_nav_menu_object()
46          */
47         public $default = array(
48                 'name'        => '',
49                 'description' => '',
50                 'parent'      => 0,
51                 'auto_add'    => false,
52         );
53
54         /**
55          * Default transport.
56          *
57          * @since 4.3.0
58          * @access public
59          * @var string
60          */
61         public $transport = 'postMessage';
62
63         /**
64          * The term ID represented by this setting instance.
65          *
66          * A negative value represents a placeholder ID for a new menu not yet saved.
67          *
68          * @since 4.3.0
69          * @access public
70          * @var int
71          */
72         public $term_id;
73
74         /**
75          * Previous (placeholder) term ID used before creating a new menu.
76          *
77          * This value will be exported to JS via the customize_save_response filter
78          * so that JavaScript can update the settings to refer to the newly-assigned
79          * term ID. This value is always negative to indicate it does not refer to
80          * a real term.
81          *
82          * @since 4.3.0
83          * @access public
84          * @var int
85          *
86          * @see WP_Customize_Nav_Menu_Setting::update()
87          * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
88          */
89         public $previous_term_id;
90
91         /**
92          * Whether or not update() was called.
93          *
94          * @since 4.3.0
95          * @access protected
96          * @var bool
97          */
98         protected $is_updated = false;
99
100         /**
101          * Status for calling the update method, used in customize_save_response filter.
102          *
103          * When status is inserted, the placeholder term ID is stored in $previous_term_id.
104          * When status is error, the error is stored in $update_error.
105          *
106          * @since 4.3.0
107          * @access public
108          * @var string updated|inserted|deleted|error
109          *
110          * @see WP_Customize_Nav_Menu_Setting::update()
111          * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
112          */
113         public $update_status;
114
115         /**
116          * Any error object returned by wp_update_nav_menu_object() when setting is updated.
117          *
118          * @since 4.3.0
119          * @access public
120          * @var WP_Error
121          *
122          * @see WP_Customize_Nav_Menu_Setting::update()
123          * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
124          */
125         public $update_error;
126
127         /**
128          * Constructor.
129          *
130          * Any supplied $args override class property defaults.
131          *
132          * @since 4.3.0
133          * @access public
134          *
135          * @param WP_Customize_Manager $manager Bootstrap Customizer instance.
136          * @param string               $id      An specific ID of the setting. Can be a
137          *                                      theme mod or option name.
138          * @param array                $args    Optional. Setting arguments.
139          *
140          * @throws Exception If $id is not valid for this setting type.
141          */
142         public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
143                 if ( empty( $manager->nav_menus ) ) {
144                         throw new Exception( 'Expected WP_Customize_Manager::$nav_menus to be set.' );
145                 }
146
147                 if ( ! preg_match( self::ID_PATTERN, $id, $matches ) ) {
148                         throw new Exception( "Illegal widget setting ID: $id" );
149                 }
150
151                 $this->term_id = intval( $matches['id'] );
152
153                 parent::__construct( $manager, $id, $args );
154         }
155
156         /**
157          * Get the instance data for a given widget setting.
158          *
159          * @since 4.3.0
160          * @access public
161          *
162          * @see wp_get_nav_menu_object()
163          *
164          * @return array Instance data.
165          */
166         public function value() {
167                 if ( $this->is_previewed && $this->_previewed_blog_id === get_current_blog_id() ) {
168                         $undefined  = new stdClass(); // Symbol.
169                         $post_value = $this->post_value( $undefined );
170
171                         if ( $undefined === $post_value ) {
172                                 $value = $this->_original_value;
173                         } else {
174                                 $value = $post_value;
175                         }
176                 } else {
177                         $value = false;
178
179                         // Note that a term_id of less than one indicates a nav_menu not yet inserted.
180                         if ( $this->term_id > 0 ) {
181                                 $term = wp_get_nav_menu_object( $this->term_id );
182
183                                 if ( $term ) {
184                                         $value = wp_array_slice_assoc( (array) $term, array_keys( $this->default ) );
185
186                                         $nav_menu_options  = (array) get_option( 'nav_menu_options', array() );
187                                         $value['auto_add'] = false;
188
189                                         if ( isset( $nav_menu_options['auto_add'] ) && is_array( $nav_menu_options['auto_add'] ) ) {
190                                                 $value['auto_add'] = in_array( $term->term_id, $nav_menu_options['auto_add'] );
191                                         }
192                                 }
193                         }
194
195                         if ( ! is_array( $value ) ) {
196                                 $value = $this->default;
197                         }
198                 }
199                 return $value;
200         }
201
202         /**
203          * Handle previewing the setting.
204          *
205          * @since 4.3.0
206          * @since 4.4.0 Added boolean return value
207          * @access public
208          *
209          * @see WP_Customize_Manager::post_value()
210          *
211          * @return bool False if method short-circuited due to no-op.
212          */
213         public function preview() {
214                 if ( $this->is_previewed ) {
215                         return false;
216                 }
217
218                 $undefined = new stdClass();
219                 $is_placeholder = ( $this->term_id < 0 );
220                 $is_dirty = ( $undefined !== $this->post_value( $undefined ) );
221                 if ( ! $is_placeholder && ! $is_dirty ) {
222                         return false;
223                 }
224
225                 $this->is_previewed       = true;
226                 $this->_original_value    = $this->value();
227                 $this->_previewed_blog_id = get_current_blog_id();
228
229                 add_filter( 'wp_get_nav_menus', array( $this, 'filter_wp_get_nav_menus' ), 10, 2 );
230                 add_filter( 'wp_get_nav_menu_object', array( $this, 'filter_wp_get_nav_menu_object' ), 10, 2 );
231                 add_filter( 'default_option_nav_menu_options', array( $this, 'filter_nav_menu_options' ) );
232                 add_filter( 'option_nav_menu_options', array( $this, 'filter_nav_menu_options' ) );
233
234                 return true;
235         }
236
237         /**
238          * Filter the wp_get_nav_menus() result to ensure the inserted menu object is included, and the deleted one is removed.
239          *
240          * @since 4.3.0
241          * @access public
242          *
243          * @see wp_get_nav_menus()
244          *
245          * @param array $menus An array of menu objects.
246          * @param array $args  An array of arguments used to retrieve menu objects.
247          * @return array
248          */
249         public function filter_wp_get_nav_menus( $menus, $args ) {
250                 if ( get_current_blog_id() !== $this->_previewed_blog_id ) {
251                         return $menus;
252                 }
253
254                 $setting_value = $this->value();
255                 $is_delete = ( false === $setting_value );
256                 $index = -1;
257
258                 // Find the existing menu item's position in the list.
259                 foreach ( $menus as $i => $menu ) {
260                         if ( (int) $this->term_id === (int) $menu->term_id || (int) $this->previous_term_id === (int) $menu->term_id ) {
261                                 $index = $i;
262                                 break;
263                         }
264                 }
265
266                 if ( $is_delete ) {
267                         // Handle deleted menu by removing it from the list.
268                         if ( -1 !== $index ) {
269                                 array_splice( $menus, $index, 1 );
270                         }
271                 } else {
272                         // Handle menus being updated or inserted.
273                         $menu_obj = (object) array_merge( array(
274                                 'term_id'          => $this->term_id,
275                                 'term_taxonomy_id' => $this->term_id,
276                                 'slug'             => sanitize_title( $setting_value['name'] ),
277                                 'count'            => 0,
278                                 'term_group'       => 0,
279                                 'taxonomy'         => self::TAXONOMY,
280                                 'filter'           => 'raw',
281                         ), $setting_value );
282
283                         array_splice( $menus, $index, ( -1 === $index ? 0 : 1 ), array( $menu_obj ) );
284                 }
285
286                 // Make sure the menu objects get re-sorted after an update/insert.
287                 if ( ! $is_delete && ! empty( $args['orderby'] ) ) {
288                         $this->_current_menus_sort_orderby = $args['orderby'];
289                         usort( $menus, array( $this, '_sort_menus_by_orderby' ) );
290                 }
291                 // @todo add support for $args['hide_empty'] === true
292
293                 return $menus;
294         }
295
296         /**
297          * Temporary non-closure passing of orderby value to function.
298          *
299          * @since 4.3.0
300          * @access protected
301          * @var string
302          *
303          * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus()
304          * @see WP_Customize_Nav_Menu_Setting::_sort_menus_by_orderby()
305          */
306         protected $_current_menus_sort_orderby;
307
308         /**
309          * Sort menu objects by the class-supplied orderby property.
310          *
311          * This is a workaround for a lack of closures.
312          *
313          * @since 4.3.0
314          * @access protected
315          * @param object $menu1
316          * @param object $menu2
317          * @return int
318          *
319          * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus()
320          */
321         protected function _sort_menus_by_orderby( $menu1, $menu2 ) {
322                 $key = $this->_current_menus_sort_orderby;
323                 return strcmp( $menu1->$key, $menu2->$key );
324         }
325
326         /**
327          * Filter the wp_get_nav_menu_object() result to supply the previewed menu object.
328          *
329          * Requesting a nav_menu object by anything but ID is not supported.
330          *
331          * @since 4.3.0
332          * @access public
333          *
334          * @see wp_get_nav_menu_object()
335          *
336          * @param object|null $menu_obj Object returned by wp_get_nav_menu_object().
337          * @param string      $menu_id  ID of the nav_menu term. Requests by slug or name will be ignored.
338          * @return object|null
339          */
340         public function filter_wp_get_nav_menu_object( $menu_obj, $menu_id ) {
341                 $ok = (
342                         get_current_blog_id() === $this->_previewed_blog_id
343                         &&
344                         is_int( $menu_id )
345                         &&
346                         $menu_id === $this->term_id
347                 );
348                 if ( ! $ok ) {
349                         return $menu_obj;
350                 }
351
352                 $setting_value = $this->value();
353
354                 // Handle deleted menus.
355                 if ( false === $setting_value ) {
356                         return false;
357                 }
358
359                 // Handle sanitization failure by preventing short-circuiting.
360                 if ( null === $setting_value ) {
361                         return $menu_obj;
362                 }
363
364                 $menu_obj = (object) array_merge( array(
365                                 'term_id'          => $this->term_id,
366                                 'term_taxonomy_id' => $this->term_id,
367                                 'slug'             => sanitize_title( $setting_value['name'] ),
368                                 'count'            => 0,
369                                 'term_group'       => 0,
370                                 'taxonomy'         => self::TAXONOMY,
371                                 'filter'           => 'raw',
372                         ), $setting_value );
373
374                 return $menu_obj;
375         }
376
377         /**
378          * Filter the nav_menu_options option to include this menu's auto_add preference.
379          *
380          * @since 4.3.0
381          * @access public
382          *
383          * @param array $nav_menu_options Nav menu options including auto_add.
384          * @return array (Kaybe) modified nav menu options.
385          */
386         public function filter_nav_menu_options( $nav_menu_options ) {
387                 if ( $this->_previewed_blog_id !== get_current_blog_id() ) {
388                         return $nav_menu_options;
389                 }
390
391                 $menu = $this->value();
392                 $nav_menu_options = $this->filter_nav_menu_options_value(
393                         $nav_menu_options,
394                         $this->term_id,
395                         false === $menu ? false : $menu['auto_add']
396                 );
397
398                 return $nav_menu_options;
399         }
400
401         /**
402          * Sanitize an input.
403          *
404          * Note that parent::sanitize() erroneously does wp_unslash() on $value, but
405          * we remove that in this override.
406          *
407          * @since 4.3.0
408          * @access public
409          *
410          * @param array $value The value to sanitize.
411          * @return array|false|null Null if an input isn't valid. False if it is marked for deletion.
412          *                          Otherwise the sanitized value.
413          */
414         public function sanitize( $value ) {
415                 // Menu is marked for deletion.
416                 if ( false === $value ) {
417                         return $value;
418                 }
419
420                 // Invalid.
421                 if ( ! is_array( $value ) ) {
422                         return null;
423                 }
424
425                 $default = array(
426                         'name'        => '',
427                         'description' => '',
428                         'parent'      => 0,
429                         'auto_add'    => false,
430                 );
431                 $value = array_merge( $default, $value );
432                 $value = wp_array_slice_assoc( $value, array_keys( $default ) );
433
434                 $value['name']        = trim( esc_html( $value['name'] ) ); // This sanitization code is used in wp-admin/nav-menus.php.
435                 $value['description'] = sanitize_text_field( $value['description'] );
436                 $value['parent']      = max( 0, intval( $value['parent'] ) );
437                 $value['auto_add']    = ! empty( $value['auto_add'] );
438
439                 if ( '' === $value['name'] ) {
440                         $value['name'] = _x( '(unnamed)', 'Missing menu name.' );
441                 }
442
443                 /** This filter is documented in wp-includes/class-wp-customize-setting.php */
444                 return apply_filters( "customize_sanitize_{$this->id}", $value, $this );
445         }
446
447         /**
448          * Storage for data to be sent back to client in customize_save_response filter.
449          *
450          * @access protected
451          * @since 4.3.0
452          * @var array
453          *
454          * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
455          */
456         protected $_widget_nav_menu_updates = array();
457
458         /**
459          * Create/update the nav_menu term for this setting.
460          *
461          * Any created menus will have their assigned term IDs exported to the client
462          * via the customize_save_response filter. Likewise, any errors will be exported
463          * to the client via the customize_save_response() filter.
464          *
465          * To delete a menu, the client can send false as the value.
466          *
467          * @since 4.3.0
468          * @access protected
469          *
470          * @see wp_update_nav_menu_object()
471          *
472          * @param array|false $value {
473          *     The value to update. Note that slug cannot be updated via wp_update_nav_menu_object().
474          *     If false, then the menu will be deleted entirely.
475          *
476          *     @type string $name        The name of the menu to save.
477          *     @type string $description The term description. Default empty string.
478          *     @type int    $parent      The id of the parent term. Default 0.
479          *     @type bool   $auto_add    Whether pages will auto_add to this menu. Default false.
480          * }
481          * @return null|void
482          */
483         protected function update( $value ) {
484                 if ( $this->is_updated ) {
485                         return;
486                 }
487
488                 $this->is_updated = true;
489                 $is_placeholder   = ( $this->term_id < 0 );
490                 $is_delete        = ( false === $value );
491
492                 add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) );
493
494                 $auto_add = null;
495                 if ( $is_delete ) {
496                         // If the current setting term is a placeholder, a delete request is a no-op.
497                         if ( $is_placeholder ) {
498                                 $this->update_status = 'deleted';
499                         } else {
500                                 $r = wp_delete_nav_menu( $this->term_id );
501
502                                 if ( is_wp_error( $r ) ) {
503                                         $this->update_status = 'error';
504                                         $this->update_error  = $r;
505                                 } else {
506                                         $this->update_status = 'deleted';
507                                         $auto_add = false;
508                                 }
509                         }
510                 } else {
511                         // Insert or update menu.
512                         $menu_data = wp_array_slice_assoc( $value, array( 'description', 'parent' ) );
513                         $menu_data['menu-name'] = $value['name'];
514
515                         $menu_id = $is_placeholder ? 0 : $this->term_id;
516                         $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) );
517                         $original_name = $menu_data['menu-name'];
518                         $name_conflict_suffix = 1;
519                         while ( is_wp_error( $r ) && 'menu_exists' === $r->get_error_code() ) {
520                                 $name_conflict_suffix += 1;
521                                 /* translators: 1: original menu name, 2: duplicate count */
522                                 $menu_data['menu-name'] = sprintf( __( '%1$s (%2$d)' ), $original_name, $name_conflict_suffix );
523                                 $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) );
524                         }
525
526                         if ( is_wp_error( $r ) ) {
527                                 $this->update_status = 'error';
528                                 $this->update_error  = $r;
529                         } else {
530                                 if ( $is_placeholder ) {
531                                         $this->previous_term_id = $this->term_id;
532                                         $this->term_id          = $r;
533                                         $this->update_status    = 'inserted';
534                                 } else {
535                                         $this->update_status = 'updated';
536                                 }
537
538                                 $auto_add = $value['auto_add'];
539                         }
540                 }
541
542                 if ( null !== $auto_add ) {
543                         $nav_menu_options = $this->filter_nav_menu_options_value(
544                                 (array) get_option( 'nav_menu_options', array() ),
545                                 $this->term_id,
546                                 $auto_add
547                         );
548                         update_option( 'nav_menu_options', $nav_menu_options );
549                 }
550
551                 if ( 'inserted' === $this->update_status ) {
552                         // Make sure that new menus assigned to nav menu locations use their new IDs.
553                         foreach ( $this->manager->settings() as $setting ) {
554                                 if ( ! preg_match( '/^nav_menu_locations\[/', $setting->id ) ) {
555                                         continue;
556                                 }
557
558                                 $post_value = $setting->post_value( null );
559                                 if ( ! is_null( $post_value ) && $this->previous_term_id === intval( $post_value ) ) {
560                                         $this->manager->set_post_value( $setting->id, $this->term_id );
561                                         $setting->save();
562                                 }
563                         }
564
565                         // Make sure that any nav_menu widgets referencing the placeholder nav menu get updated and sent back to client.
566                         foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
567                                 $nav_menu_widget_setting = $this->manager->get_setting( $setting_id );
568                                 if ( ! $nav_menu_widget_setting || ! preg_match( '/^widget_nav_menu\[/', $nav_menu_widget_setting->id ) ) {
569                                         continue;
570                                 }
571
572                                 $widget_instance = $nav_menu_widget_setting->post_value(); // Note that this calls WP_Customize_Widgets::sanitize_widget_instance().
573                                 if ( empty( $widget_instance['nav_menu'] ) || intval( $widget_instance['nav_menu'] ) !== $this->previous_term_id ) {
574                                         continue;
575                                 }
576
577                                 $widget_instance['nav_menu'] = $this->term_id;
578                                 $updated_widget_instance = $this->manager->widgets->sanitize_widget_js_instance( $widget_instance );
579                                 $this->manager->set_post_value( $nav_menu_widget_setting->id, $updated_widget_instance );
580                                 $nav_menu_widget_setting->save();
581
582                                 $this->_widget_nav_menu_updates[ $nav_menu_widget_setting->id ] = $updated_widget_instance;
583                         }
584                 }
585         }
586
587         /**
588          * Updates a nav_menu_options array.
589          *
590          * @since 4.3.0
591          * @access protected
592          *
593          * @see WP_Customize_Nav_Menu_Setting::filter_nav_menu_options()
594          * @see WP_Customize_Nav_Menu_Setting::update()
595          *
596          * @param array $nav_menu_options Array as returned by get_option( 'nav_menu_options' ).
597          * @param int   $menu_id          The term ID for the given menu.
598          * @param bool  $auto_add         Whether to auto-add or not.
599          * @return array (Maybe) modified nav_menu_otions array.
600          */
601         protected function filter_nav_menu_options_value( $nav_menu_options, $menu_id, $auto_add ) {
602                 $nav_menu_options = (array) $nav_menu_options;
603                 if ( ! isset( $nav_menu_options['auto_add'] ) ) {
604                         $nav_menu_options['auto_add'] = array();
605                 }
606
607                 $i = array_search( $menu_id, $nav_menu_options['auto_add'] );
608                 if ( $auto_add && false === $i ) {
609                         array_push( $nav_menu_options['auto_add'], $this->term_id );
610                 } elseif ( ! $auto_add && false !== $i ) {
611                         array_splice( $nav_menu_options['auto_add'], $i, 1 );
612                 }
613
614                 return $nav_menu_options;
615         }
616
617         /**
618          * Export data for the JS client.
619          *
620          * @since 4.3.0
621          * @access public
622          *
623          * @see WP_Customize_Nav_Menu_Setting::update()
624          *
625          * @param array $data Additional information passed back to the 'saved' event on `wp.customize`.
626          * @return array Export data.
627          */
628         public function amend_customize_save_response( $data ) {
629                 if ( ! isset( $data['nav_menu_updates'] ) ) {
630                         $data['nav_menu_updates'] = array();
631                 }
632                 if ( ! isset( $data['widget_nav_menu_updates'] ) ) {
633                         $data['widget_nav_menu_updates'] = array();
634                 }
635
636                 $data['nav_menu_updates'][] = array(
637                         'term_id'          => $this->term_id,
638                         'previous_term_id' => $this->previous_term_id,
639                         'error'            => $this->update_error ? $this->update_error->get_error_code() : null,
640                         'status'           => $this->update_status,
641                         'saved_value'      => 'deleted' === $this->update_status ? null : $this->value(),
642                 );
643
644                 $data['widget_nav_menu_updates'] = array_merge(
645                         $data['widget_nav_menu_updates'],
646                         $this->_widget_nav_menu_updates
647                 );
648                 $this->_widget_nav_menu_updates = array();
649
650                 return $data;
651         }
652 }