]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-customize-nav-menus.php
Wordpress 4.6-scripts
[autoinstalls/wordpress.git] / wp-includes / class-wp-customize-nav-menus.php
1 <?php
2 /**
3  * WordPress Customize Nav Menus classes
4  *
5  * @package WordPress
6  * @subpackage Customize
7  * @since 4.3.0
8  */
9
10 /**
11  * Customize Nav Menus class.
12  *
13  * Implements menu management in the Customizer.
14  *
15  * @since 4.3.0
16  *
17  * @see WP_Customize_Manager
18  */
19 final class WP_Customize_Nav_Menus {
20
21         /**
22          * WP_Customize_Manager instance.
23          *
24          * @since 4.3.0
25          * @access public
26          * @var WP_Customize_Manager
27          */
28         public $manager;
29
30         /**
31          * Previewed Menus.
32          *
33          * @since 4.3.0
34          * @access public
35          * @var array
36          */
37         public $previewed_menus;
38
39         /**
40          * Constructor.
41          *
42          * @since 4.3.0
43          * @access public
44          *
45          * @param object $manager An instance of the WP_Customize_Manager class.
46          */
47         public function __construct( $manager ) {
48                 $this->previewed_menus = array();
49                 $this->manager         = $manager;
50
51                 // Skip useless hooks when the user can't manage nav menus anyway.
52                 if ( ! current_user_can( 'edit_theme_options' ) ) {
53                         return;
54                 }
55
56                 add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) );
57                 add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) );
58                 add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
59                 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
60
61                 // Needs to run after core Navigation section is set up.
62                 add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
63
64                 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
65                 add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
66                 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) );
67                 add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) );
68                 add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
69
70                 // Selective Refresh partials.
71                 add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
72         }
73
74         /**
75          * Adds a nonce for customizing menus.
76          *
77          * @since 4.5.0
78          * @access public
79          *
80          * @param array $nonces Array of nonces.
81          * @return array $nonces Modified array of nonces.
82          */
83         public function filter_nonces( $nonces ) {
84                 $nonces['customize-menus'] = wp_create_nonce( 'customize-menus' );
85                 return $nonces;
86         }
87
88         /**
89          * Ajax handler for loading available menu items.
90          *
91          * @since 4.3.0
92          * @access public
93          */
94         public function ajax_load_available_items() {
95                 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
96
97                 if ( ! current_user_can( 'edit_theme_options' ) ) {
98                         wp_die( -1 );
99                 }
100
101                 if ( empty( $_POST['type'] ) || empty( $_POST['object'] ) ) {
102                         wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
103                 }
104
105                 $type = sanitize_key( $_POST['type'] );
106                 $object = sanitize_key( $_POST['object'] );
107                 $page = empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] );
108                 $items = $this->load_available_items_query( $type, $object, $page );
109
110                 if ( is_wp_error( $items ) ) {
111                         wp_send_json_error( $items->get_error_code() );
112                 } else {
113                         wp_send_json_success( array( 'items' => $items ) );
114                 }
115         }
116
117         /**
118          * Performs the post_type and taxonomy queries for loading available menu items.
119          *
120          * @since 4.3.0
121          * @access public
122          *
123          * @param string $type   Optional. Accepts any custom object type and has built-in support for
124          *                         'post_type' and 'taxonomy'. Default is 'post_type'.
125          * @param string $object Optional. Accepts any registered taxonomy or post type name. Default is 'page'.
126          * @param int    $page   Optional. The page number used to generate the query offset. Default is '0'.
127          * @return WP_Error|array Returns either a WP_Error object or an array of menu items.
128          */
129         public function load_available_items_query( $type = 'post_type', $object = 'page', $page = 0 ) {
130                 $items = array();
131
132                 if ( 'post_type' === $type ) {
133                         $post_type = get_post_type_object( $object );
134                         if ( ! $post_type ) {
135                                 return new WP_Error( 'nav_menus_invalid_post_type' );
136                         }
137
138                         if ( 0 === $page && 'page' === $object ) {
139                                 // Add "Home" link. Treat as a page, but switch to custom on add.
140                                 $items[] = array(
141                                         'id'         => 'home',
142                                         'title'      => _x( 'Home', 'nav menu home label' ),
143                                         'type'       => 'custom',
144                                         'type_label' => __( 'Custom Link' ),
145                                         'object'     => '',
146                                         'url'        => home_url(),
147                                 );
148                         } elseif ( 'post' !== $object && 0 === $page && $post_type->has_archive ) {
149                                 // Add a post type archive link.
150                                 $items[] = array(
151                                         'id'         => $object . '-archive',
152                                         'title'      => $post_type->labels->archives,
153                                         'type'       => 'post_type_archive',
154                                         'type_label' => __( 'Post Type Archive' ),
155                                         'object'     => $object,
156                                         'url'        => get_post_type_archive_link( $object ),
157                                 );
158                         }
159
160                         $posts = get_posts( array(
161                                 'numberposts' => 10,
162                                 'offset'      => 10 * $page,
163                                 'orderby'     => 'date',
164                                 'order'       => 'DESC',
165                                 'post_type'   => $object,
166                         ) );
167                         foreach ( $posts as $post ) {
168                                 $post_title = $post->post_title;
169                                 if ( '' === $post_title ) {
170                                         /* translators: %d: ID of a post */
171                                         $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
172                                 }
173                                 $items[] = array(
174                                         'id'         => "post-{$post->ID}",
175                                         'title'      => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
176                                         'type'       => 'post_type',
177                                         'type_label' => get_post_type_object( $post->post_type )->labels->singular_name,
178                                         'object'     => $post->post_type,
179                                         'object_id'  => intval( $post->ID ),
180                                         'url'        => get_permalink( intval( $post->ID ) ),
181                                 );
182                         }
183                 } elseif ( 'taxonomy' === $type ) {
184                         $terms = get_terms( $object, array(
185                                 'child_of'     => 0,
186                                 'exclude'      => '',
187                                 'hide_empty'   => false,
188                                 'hierarchical' => 1,
189                                 'include'      => '',
190                                 'number'       => 10,
191                                 'offset'       => 10 * $page,
192                                 'order'        => 'DESC',
193                                 'orderby'      => 'count',
194                                 'pad_counts'   => false,
195                         ) );
196                         if ( is_wp_error( $terms ) ) {
197                                 return $terms;
198                         }
199
200                         foreach ( $terms as $term ) {
201                                 $items[] = array(
202                                         'id'         => "term-{$term->term_id}",
203                                         'title'      => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
204                                         'type'       => 'taxonomy',
205                                         'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
206                                         'object'     => $term->taxonomy,
207                                         'object_id'  => intval( $term->term_id ),
208                                         'url'        => get_term_link( intval( $term->term_id ), $term->taxonomy ),
209                                 );
210                         }
211                 }
212
213                 /**
214                  * Filters the available menu items.
215                  *
216                  * @since 4.3.0
217                  *
218                  * @param array  $items  The array of menu items.
219                  * @param string $type   The object type.
220                  * @param string $object The object name.
221                  * @param int    $page   The current page number.
222                  */
223                 $items = apply_filters( 'customize_nav_menu_available_items', $items, $type, $object, $page );
224
225                 return $items;
226         }
227
228         /**
229          * Ajax handler for searching available menu items.
230          *
231          * @since 4.3.0
232          * @access public
233          */
234         public function ajax_search_available_items() {
235                 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
236
237                 if ( ! current_user_can( 'edit_theme_options' ) ) {
238                         wp_die( -1 );
239                 }
240
241                 if ( empty( $_POST['search'] ) ) {
242                         wp_send_json_error( 'nav_menus_missing_search_parameter' );
243                 }
244
245                 $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0;
246                 if ( $p < 1 ) {
247                         $p = 1;
248                 }
249
250                 $s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
251                 $items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s ) );
252
253                 if ( empty( $items ) ) {
254                         wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
255                 } else {
256                         wp_send_json_success( array( 'items' => $items ) );
257                 }
258         }
259
260         /**
261          * Performs post queries for available-item searching.
262          *
263          * Based on WP_Editor::wp_link_query().
264          *
265          * @since 4.3.0
266          * @access public
267          *
268          * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
269          * @return array Menu items.
270          */
271         public function search_available_items_query( $args = array() ) {
272                 $items = array();
273
274                 $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
275                 $query = array(
276                         'post_type'              => array_keys( $post_type_objects ),
277                         'suppress_filters'       => true,
278                         'update_post_term_cache' => false,
279                         'update_post_meta_cache' => false,
280                         'post_status'            => 'publish',
281                         'posts_per_page'         => 20,
282                 );
283
284                 $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
285                 $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
286
287                 if ( isset( $args['s'] ) ) {
288                         $query['s'] = $args['s'];
289                 }
290
291                 // Query posts.
292                 $get_posts = new WP_Query( $query );
293
294                 // Check if any posts were found.
295                 if ( $get_posts->post_count ) {
296                         foreach ( $get_posts->posts as $post ) {
297                                 $post_title = $post->post_title;
298                                 if ( '' === $post_title ) {
299                                         /* translators: %d: ID of a post */
300                                         $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
301                                 }
302                                 $items[] = array(
303                                         'id'         => 'post-' . $post->ID,
304                                         'title'      => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
305                                         'type'       => 'post_type',
306                                         'type_label' => $post_type_objects[ $post->post_type ]->labels->singular_name,
307                                         'object'     => $post->post_type,
308                                         'object_id'  => intval( $post->ID ),
309                                         'url'        => get_permalink( intval( $post->ID ) ),
310                                 );
311                         }
312                 }
313
314                 // Query taxonomy terms.
315                 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
316                 $terms = get_terms( $taxonomies, array(
317                         'name__like' => $args['s'],
318                         'number'     => 20,
319                         'offset'     => 20 * ($args['pagenum'] - 1),
320                 ) );
321
322                 // Check if any taxonomies were found.
323                 if ( ! empty( $terms ) ) {
324                         foreach ( $terms as $term ) {
325                                 $items[] = array(
326                                         'id'         => 'term-' . $term->term_id,
327                                         'title'      => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
328                                         'type'       => 'taxonomy',
329                                         'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
330                                         'object'     => $term->taxonomy,
331                                         'object_id'  => intval( $term->term_id ),
332                                         'url'        => get_term_link( intval( $term->term_id ), $term->taxonomy ),
333                                 );
334                         }
335                 }
336
337                 /**
338                  * Filters the available menu items during a search request.
339                  *
340                  * @since 4.5.0
341                  *
342                  * @param array $items The array of menu items.
343                  * @param array $args  Includes 'pagenum' and 's' (search) arguments.
344                  */
345                 $items = apply_filters( 'customize_nav_menu_searched_items', $items, $args );
346
347                 return $items;
348         }
349
350         /**
351          * Enqueue scripts and styles for Customizer pane.
352          *
353          * @since 4.3.0
354          * @access public
355          */
356         public function enqueue_scripts() {
357                 wp_enqueue_style( 'customize-nav-menus' );
358                 wp_enqueue_script( 'customize-nav-menus' );
359
360                 $temp_nav_menu_setting      = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' );
361                 $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' );
362
363                 // Pass data to JS.
364                 $settings = array(
365                         'allMenus'             => wp_get_nav_menus(),
366                         'itemTypes'            => $this->available_item_types(),
367                         'l10n'                 => array(
368                                 'untitled'          => _x( '(no label)', 'missing menu item navigation label' ),
369                                 'unnamed'           => _x( '(unnamed)', 'Missing menu name.' ),
370                                 'custom_label'      => __( 'Custom Link' ),
371                                 /* translators: %s: menu location */
372                                 'menuLocation'      => _x( '(Currently set to: %s)', 'menu' ),
373                                 'menuNameLabel'     => __( 'Menu Name' ),
374                                 'itemAdded'         => __( 'Menu item added' ),
375                                 'itemDeleted'       => __( 'Menu item deleted' ),
376                                 'menuAdded'         => __( 'Menu created' ),
377                                 'menuDeleted'       => __( 'Menu deleted' ),
378                                 'movedUp'           => __( 'Menu item moved up' ),
379                                 'movedDown'         => __( 'Menu item moved down' ),
380                                 'movedLeft'         => __( 'Menu item moved out of submenu' ),
381                                 'movedRight'        => __( 'Menu item is now a sub-item' ),
382                                 /* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
383                                 'customizingMenus'  => sprintf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ),
384                                 /* translators: %s: title of menu item which is invalid */
385                                 'invalidTitleTpl'   => __( '%s (Invalid)' ),
386                                 /* translators: %s: title of menu item in draft status */
387                                 'pendingTitleTpl'   => __( '%s (Pending)' ),
388                                 'itemsFound'        => __( 'Number of items found: %d' ),
389                                 'itemsFoundMore'    => __( 'Additional items found: %d' ),
390                                 'itemsLoadingMore'  => __( 'Loading more results... please wait.' ),
391                                 'reorderModeOn'     => __( 'Reorder mode enabled' ),
392                                 'reorderModeOff'    => __( 'Reorder mode closed' ),
393                                 'reorderLabelOn'    => esc_attr__( 'Reorder menu items' ),
394                                 'reorderLabelOff'   => esc_attr__( 'Close reorder mode' ),
395                         ),
396                         'settingTransport'     => 'postMessage',
397                         'phpIntMax'            => PHP_INT_MAX,
398                         'defaultSettingValues' => array(
399                                 'nav_menu'      => $temp_nav_menu_setting->default,
400                                 'nav_menu_item' => $temp_nav_menu_item_setting->default,
401                         ),
402                         'locationSlugMappedToName' => get_registered_nav_menus(),
403                 );
404
405                 $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) );
406                 wp_scripts()->add_data( 'customize-nav-menus', 'data', $data );
407
408                 // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
409                 $nav_menus_l10n = array(
410                         'oneThemeLocationNoMenus' => null,
411                         'moveUp'       => __( 'Move up one' ),
412                         'moveDown'     => __( 'Move down one' ),
413                         'moveToTop'    => __( 'Move to the top' ),
414                         /* translators: %s: previous item name */
415                         'moveUnder'    => __( 'Move under %s' ),
416                         /* translators: %s: previous item name */
417                         'moveOutFrom'  => __( 'Move out from under %s' ),
418                         /* translators: %s: previous item name */
419                         'under'        => __( 'Under %s' ),
420                         /* translators: %s: previous item name */
421                         'outFrom'      => __( 'Out from under %s' ),
422                         /* translators: 1: item name, 2: item position, 3: total number of items */
423                         'menuFocus'    => __( '%1$s. Menu item %2$d of %3$d.' ),
424                         /* translators: 1: item name, 2: item position, 3: parent item name */
425                         'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
426                 );
427                 wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
428         }
429
430         /**
431          * Filters a dynamic setting's constructor args.
432          *
433          * For a dynamic setting to be registered, this filter must be employed
434          * to override the default false value with an array of args to pass to
435          * the WP_Customize_Setting constructor.
436          *
437          * @since 4.3.0
438          * @access public
439          *
440          * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
441          * @param string      $setting_id   ID for dynamic setting, usually coming from `$_POST['customized']`.
442          * @return array|false
443          */
444         public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
445                 if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) {
446                         $setting_args = array(
447                                 'type'      => WP_Customize_Nav_Menu_Setting::TYPE,
448                                 'transport' => 'postMessage',
449                         );
450                 } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) {
451                         $setting_args = array(
452                                 'type'      => WP_Customize_Nav_Menu_Item_Setting::TYPE,
453                                 'transport' => 'postMessage',
454                         );
455                 }
456                 return $setting_args;
457         }
458
459         /**
460          * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
461          *
462          * @since 4.3.0
463          * @access public
464          *
465          * @param string $setting_class WP_Customize_Setting or a subclass.
466          * @param string $setting_id    ID for dynamic setting, usually coming from `$_POST['customized']`.
467          * @param array  $setting_args  WP_Customize_Setting or a subclass.
468          * @return string
469          */
470         public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
471                 unset( $setting_id );
472
473                 if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) {
474                         $setting_class = 'WP_Customize_Nav_Menu_Setting';
475                 } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) {
476                         $setting_class = 'WP_Customize_Nav_Menu_Item_Setting';
477                 }
478                 return $setting_class;
479         }
480
481         /**
482          * Add the customizer settings and controls.
483          *
484          * @since 4.3.0
485          * @access public
486          */
487         public function customize_register() {
488
489                 // Require JS-rendered control types.
490                 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
491                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
492                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
493                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
494                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
495
496                 // Create a panel for Menus.
497                 $description = '<p>' . __( 'This panel is used for managing navigation menus for content you have already published on your site. You can create menus and add items for existing content such as pages, posts, categories, tags, formats, or custom links.' ) . '</p>';
498                 if ( current_theme_supports( 'widgets' ) ) {
499                         /* translators: URL to the widgets panel of the customizer */
500                         $description .= '<p>' . sprintf( __( 'Menus can be displayed in locations defined by your theme or in <a href="%s">widget areas</a> by adding a &#8220;Custom Menu&#8221; widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
501                 } else {
502                         $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
503                 }
504                 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
505                         'title'       => __( 'Menus' ),
506                         'description' => $description,
507                         'priority'    => 100,
508                         // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
509                 ) ) );
510                 $menus = wp_get_nav_menus();
511
512                 // Menu locations.
513                 $locations     = get_registered_nav_menus();
514                 $num_locations = count( array_keys( $locations ) );
515                 if ( 1 == $num_locations ) {
516                         $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' ) . '</p>';
517                 } else {
518                         /* translators: %s: number of menu locations */
519                         $description = '<p>' . sprintf( _n( 'Your theme supports %s menu. Select which menu appears in each location.', 'Your theme supports %s menus. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . '</p>';
520                 }
521                 if ( current_theme_supports( 'widgets' ) ) {
522                         /* translators: URL to the widgets panel of the customizer */
523                         $description .= '<p>' . sprintf( __( 'You can also place menus in <a href="%s">widget areas</a> with the &#8220;Custom Menu&#8221; widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
524                 }
525
526                 $this->manager->add_section( 'menu_locations', array(
527                         'title'       => __( 'Menu Locations' ),
528                         'panel'       => 'nav_menus',
529                         'priority'    => 5,
530                         'description' => $description,
531                 ) );
532
533                 $choices = array( '0' => __( '&mdash; Select &mdash;' ) );
534                 foreach ( $menus as $menu ) {
535                         $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '&hellip;' );
536                 }
537
538                 foreach ( $locations as $location => $description ) {
539                         $setting_id = "nav_menu_locations[{$location}]";
540
541                         $setting = $this->manager->get_setting( $setting_id );
542                         if ( $setting ) {
543                                 $setting->transport = 'postMessage';
544                                 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
545                                 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
546                         } else {
547                                 $this->manager->add_setting( $setting_id, array(
548                                         'sanitize_callback' => array( $this, 'intval_base10' ),
549                                         'theme_supports'    => 'menus',
550                                         'type'              => 'theme_mod',
551                                         'transport'         => 'postMessage',
552                                         'default'           => 0,
553                                 ) );
554                         }
555
556                         $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
557                                 'label'       => $description,
558                                 'location_id' => $location,
559                                 'section'     => 'menu_locations',
560                                 'choices'     => $choices,
561                         ) ) );
562                 }
563
564                 // Register each menu as a Customizer section, and add each menu item to each menu.
565                 foreach ( $menus as $menu ) {
566                         $menu_id = $menu->term_id;
567
568                         // Create a section for each menu.
569                         $section_id = 'nav_menu[' . $menu_id . ']';
570                         $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
571                                 'title'     => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
572                                 'priority'  => 10,
573                                 'panel'     => 'nav_menus',
574                         ) ) );
575
576                         $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
577                         $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
578                                 'transport' => 'postMessage',
579                         ) ) );
580
581                         // Add the menu contents.
582                         $menu_items = (array) wp_get_nav_menu_items( $menu_id );
583
584                         foreach ( array_values( $menu_items ) as $i => $item ) {
585
586                                 // Create a setting for each menu item (which doesn't actually manage data, currently).
587                                 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
588
589                                 $value = (array) $item;
590                                 $value['nav_menu_term_id'] = $menu_id;
591                                 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
592                                         'value'     => $value,
593                                         'transport' => 'postMessage',
594                                 ) ) );
595
596                                 // Create a control for each menu item.
597                                 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
598                                         'label'    => $item->title,
599                                         'section'  => $section_id,
600                                         'priority' => 10 + $i,
601                                 ) ) );
602                         }
603
604                         // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
605                 }
606
607                 // Add the add-new-menu section and controls.
608                 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
609                         'title'    => __( 'Add a Menu' ),
610                         'panel'    => 'nav_menus',
611                         'priority' => 999,
612                 ) ) );
613
614                 $this->manager->add_control( 'new_menu_name', array(
615                         'label'       => '',
616                         'section'     => 'add_menu',
617                         'type'        => 'text',
618                         'settings'    => array(),
619                         'input_attrs' => array(
620                                 'class'       => 'menu-name-field',
621                                 'placeholder' => __( 'New menu name' ),
622                         ),
623                 ) );
624
625                 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
626                         'section'  => 'add_menu',
627                         'settings' => array(),
628                 ) ) );
629         }
630
631         /**
632          * Get the base10 intval.
633          *
634          * This is used as a setting's sanitize_callback; we can't use just plain
635          * intval because the second argument is not what intval() expects.
636          *
637          * @since 4.3.0
638          * @access public
639          *
640          * @param mixed $value Number to convert.
641          * @return int Integer.
642          */
643         public function intval_base10( $value ) {
644                 return intval( $value, 10 );
645         }
646
647         /**
648          * Return an array of all the available item types.
649          *
650          * @since 4.3.0
651          * @access public
652          *
653          * @return array The available menu item types.
654          */
655         public function available_item_types() {
656                 $item_types = array();
657
658                 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
659                 if ( $post_types ) {
660                         foreach ( $post_types as $slug => $post_type ) {
661                                 $item_types[] = array(
662                                         'title'  => $post_type->labels->name,
663                                         'type'   => 'post_type',
664                                         'object' => $post_type->name,
665                                 );
666                         }
667                 }
668
669                 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
670                 if ( $taxonomies ) {
671                         foreach ( $taxonomies as $slug => $taxonomy ) {
672                                 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
673                                         continue;
674                                 }
675                                 $item_types[] = array(
676                                         'title'  => $taxonomy->labels->name,
677                                         'type'   => 'taxonomy',
678                                         'object' => $taxonomy->name,
679                                 );
680                         }
681                 }
682
683                 /**
684                  * Filters the available menu item types.
685                  *
686                  * @since 4.3.0
687                  *
688                  * @param array $item_types Custom menu item types.
689                  */
690                 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
691
692                 return $item_types;
693         }
694
695         /**
696          * Print the JavaScript templates used to render Menu Customizer components.
697          *
698          * Templates are imported into the JS use wp.template.
699          *
700          * @since 4.3.0
701          * @access public
702          */
703         public function print_templates() {
704                 ?>
705                 <script type="text/html" id="tmpl-available-menu-item">
706                         <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
707                                 <div class="menu-item-bar">
708                                         <div class="menu-item-handle">
709                                                 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
710                                                 <span class="item-title" aria-hidden="true">
711                                                         <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
712                                                 </span>
713                                                 <button type="button" class="button-link item-add">
714                                                         <span class="screen-reader-text"><?php
715                                                                 /* translators: 1: Title of a menu item, 2: Type of a menu item */
716                                                                 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
717                                                         ?></span>
718                                                 </button>
719                                         </div>
720                                 </div>
721                         </li>
722                 </script>
723
724                 <script type="text/html" id="tmpl-menu-item-reorder-nav">
725                         <div class="menu-item-reorder-nav">
726                                 <?php
727                                 printf(
728                                         '<button type="button" class="menus-move-up">%1$s</button><button type="button" class="menus-move-down">%2$s</button><button type="button" class="menus-move-left">%3$s</button><button type="button" class="menus-move-right">%4$s</button>',
729                                         __( 'Move up' ),
730                                         __( 'Move down' ),
731                                         __( 'Move one level up' ),
732                                         __( 'Move one level down' )
733                                 );
734                                 ?>
735                         </div>
736                 </script>
737         <?php
738         }
739
740         /**
741          * Print the html template used to render the add-menu-item frame.
742          *
743          * @since 4.3.0
744          * @access public
745          */
746         public function available_items_template() {
747                 ?>
748                 <div id="available-menu-items" class="accordion-container">
749                         <div class="customize-section-title">
750                                 <button type="button" class="customize-section-back" tabindex="-1">
751                                         <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
752                                 </button>
753                                 <h3>
754                                         <span class="customize-action">
755                                                 <?php
756                                                         /* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
757                                                         printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
758                                                 ?>
759                                         </span>
760                                         <?php _e( 'Add Menu Items' ); ?>
761                                 </h3>
762                         </div>
763                         <div id="available-menu-items-search" class="accordion-section cannot-expand">
764                                 <div class="accordion-section-title">
765                                         <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
766                                         <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ) ?>" aria-describedby="menu-items-search-desc" />
767                                         <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
768                                         <span class="spinner"></span>
769                                 </div>
770                                 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
771                                 <ul class="accordion-section-content" data-type="search"></ul>
772                         </div>
773                         <div id="new-custom-menu-item" class="accordion-section">
774                                 <h4 class="accordion-section-title" role="presentation">
775                                         <?php _e( 'Custom Links' ); ?>
776                                         <button type="button" class="button-link" aria-expanded="false">
777                                                 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
778                                                 <span class="toggle-indicator" aria-hidden="true"></span>
779                                         </button>
780                                 </h4>
781                                 <div class="accordion-section-content customlinkdiv">
782                                         <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
783                                         <p id="menu-item-url-wrap" class="wp-clearfix">
784                                                 <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
785                                                 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
786                                         </p>
787                                         <p id="menu-item-name-wrap" class="wp-clearfix">
788                                                 <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
789                                                 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
790                                         </p>
791                                         <p class="button-controls">
792                                                 <span class="add-to-menu">
793                                                         <input type="submit" class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-custom-menu-item" id="custom-menu-item-submit">
794                                                         <span class="spinner"></span>
795                                                 </span>
796                                         </p>
797                                 </div>
798                         </div>
799                         <?php
800                         // Containers for per-post-type item browsing; items added with JS.
801                         foreach ( $this->available_item_types() as $available_item_type ) {
802                                 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
803                                 ?>
804                                 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
805                                         <h4 class="accordion-section-title" role="presentation">
806                                                 <?php echo esc_html( $available_item_type['title'] ); ?>
807                                                 <span class="spinner"></span>
808                                                 <span class="no-items"><?php _e( 'No items' ); ?></span>
809                                                 <button type="button" class="button-link" aria-expanded="false">
810                                                         <span class="screen-reader-text"><?php
811                                                         /* translators: %s: Title of a section with menu items */
812                                                         printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
813                                                         <span class="toggle-indicator" aria-hidden="true"></span>
814                                                 </button>
815                                         </h4>
816                                         <ul class="accordion-section-content" data-type="<?php echo esc_attr( $available_item_type['type'] ); ?>" data-object="<?php echo esc_attr( $available_item_type['object'] ); ?>"></ul>
817                                 </div>
818                                 <?php
819                         }
820                         ?>
821                 </div><!-- #available-menu-items -->
822         <?php
823         }
824
825         //
826         // Start functionality specific to partial-refresh of menu changes in Customizer preview.
827         //
828
829         /**
830          * Nav menu args used for each instance, keyed by the args HMAC.
831          *
832          * @since 4.3.0
833          * @access public
834          * @var array
835          */
836         public $preview_nav_menu_instance_args = array();
837
838         /**
839          * Filters arguments for dynamic nav_menu selective refresh partials.
840          *
841          * @since 4.5.0
842          * @access public
843          *
844          * @param array|false $partial_args Partial args.
845          * @param string      $partial_id   Partial ID.
846          * @return array Partial args.
847          */
848         public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
849
850                 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
851                         if ( false === $partial_args ) {
852                                 $partial_args = array();
853                         }
854                         $partial_args = array_merge(
855                                 $partial_args,
856                                 array(
857                                         'type'                => 'nav_menu_instance',
858                                         'render_callback'     => array( $this, 'render_nav_menu_partial' ),
859                                         'container_inclusive' => true,
860                                         'settings'            => array(), // Empty because the nav menu instance may relate to a menu or a location.
861                                         'capability'          => 'edit_theme_options',
862                                 )
863                         );
864                 }
865
866                 return $partial_args;
867         }
868
869         /**
870          * Add hooks for the Customizer preview.
871          *
872          * @since 4.3.0
873          * @access public
874          */
875         public function customize_preview_init() {
876                 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
877                 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
878                 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
879                 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
880                 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
881         }
882
883         /**
884          * Keep track of the arguments that are being passed to wp_nav_menu().
885          *
886          * @since 4.3.0
887          * @access public
888          * @see wp_nav_menu()
889          * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
890          *
891          * @param array $args An array containing wp_nav_menu() arguments.
892          * @return array Arguments.
893          */
894         public function filter_wp_nav_menu_args( $args ) {
895                 /*
896                  * The following conditions determine whether or not this instance of
897                  * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
898                  * selective refreshed if...
899                  */
900                 $can_partial_refresh = (
901                         // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
902                         ! empty( $args['echo'] )
903                         &&
904                         // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
905                         ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
906                         &&
907                         // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
908                         ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
909                         // ...and if it has a theme location assigned or an assigned menu to display,
910                         && (
911                                 ! empty( $args['theme_location'] )
912                                 ||
913                                 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
914                         )
915                         &&
916                         // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
917                         (
918                                 ! empty( $args['container'] )
919                                 ||
920                                 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
921                         )
922                 );
923                 $args['can_partial_refresh'] = $can_partial_refresh;
924
925                 $exported_args = $args;
926
927                 // Empty out args which may not be JSON-serializable.
928                 if ( ! $can_partial_refresh ) {
929                         $exported_args['fallback_cb'] = '';
930                         $exported_args['walker'] = '';
931                 }
932
933                 /*
934                  * Replace object menu arg with a term_id menu arg, as this exports better
935                  * to JS and is easier to compare hashes.
936                  */
937                 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
938                         $exported_args['menu'] = $exported_args['menu']->term_id;
939                 }
940
941                 ksort( $exported_args );
942                 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
943
944                 $args['customize_preview_nav_menus_args'] = $exported_args;
945                 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
946                 return $args;
947         }
948
949         /**
950          * Prepares wp_nav_menu() calls for partial refresh.
951          *
952          * Injects attributes into container element.
953          *
954          * @since 4.3.0
955          * @access public
956          *
957          * @see wp_nav_menu()
958          *
959          * @param string $nav_menu_content The HTML content for the navigation menu.
960          * @param object $args             An object containing wp_nav_menu() arguments.
961          * @return null
962          */
963         public function filter_wp_nav_menu( $nav_menu_content, $args ) {
964                 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
965                         $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
966                         $attributes .= ' data-customize-partial-type="nav_menu_instance"';
967                         $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
968                         $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
969                 }
970                 return $nav_menu_content;
971         }
972
973         /**
974          * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
975          * submitted in the Ajax request.
976          *
977          * Note that the array is expected to be pre-sorted.
978          *
979          * @since 4.3.0
980          * @access public
981          *
982          * @param array $args The arguments to hash.
983          * @return string Hashed nav menu arguments.
984          */
985         public function hash_nav_menu_args( $args ) {
986                 return wp_hash( serialize( $args ) );
987         }
988
989         /**
990          * Enqueue scripts for the Customizer preview.
991          *
992          * @since 4.3.0
993          * @access public
994          */
995         public function customize_preview_enqueue_deps() {
996                 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
997                 wp_enqueue_style( 'customize-preview' );
998         }
999
1000         /**
1001          * Exports data from PHP to JS.
1002          *
1003          * @since 4.3.0
1004          * @access public
1005          */
1006         public function export_preview_data() {
1007
1008                 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1009                 $exports = array(
1010                         'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1011                 );
1012                 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1013         }
1014
1015         /**
1016          * Export any wp_nav_menu() calls during the rendering of any partials.
1017          *
1018          * @since 4.5.0
1019          * @access public
1020          *
1021          * @param array $response Response.
1022          * @return array Response.
1023          */
1024         public function export_partial_rendered_nav_menu_instances( $response ) {
1025                 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1026                 return $response;
1027         }
1028
1029         /**
1030          * Render a specific menu via wp_nav_menu() using the supplied arguments.
1031          *
1032          * @since 4.3.0
1033          * @access public
1034          *
1035          * @see wp_nav_menu()
1036          *
1037          * @param WP_Customize_Partial $partial       Partial.
1038          * @param array                $nav_menu_args Nav menu args supplied as container context.
1039          * @return string|false
1040          */
1041         public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1042                 unset( $partial );
1043
1044                 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1045                         // Error: missing_args_hmac.
1046                         return false;
1047                 }
1048
1049                 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1050                 unset( $nav_menu_args['args_hmac'] );
1051
1052                 ksort( $nav_menu_args );
1053                 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1054                         // Error: args_hmac_mismatch.
1055                         return false;
1056                 }
1057
1058                 ob_start();
1059                 wp_nav_menu( $nav_menu_args );
1060                 $content = ob_get_clean();
1061
1062                 return $content;
1063         }
1064 }