]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-customize-nav-menus.php
WordPress 4.5
[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                  * Filter 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                  * Filter 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          * Filter 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                         $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>';
500                 } else {
501                         $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
502                 }
503                 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
504                         'title'       => __( 'Menus' ),
505                         'description' => $description,
506                         'priority'    => 100,
507                         // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
508                 ) ) );
509                 $menus = wp_get_nav_menus();
510
511                 // Menu locations.
512                 $locations     = get_registered_nav_menus();
513                 $num_locations = count( array_keys( $locations ) );
514                 if ( 1 == $num_locations ) {
515                         $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' );
516                 } else {
517                         $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 ) );
518                 }
519                 $description  .= '</p><p>' . __( 'You can also place menus in widget areas with the Custom Menu widget.' ) . '</p>';
520
521                 $this->manager->add_section( 'menu_locations', array(
522                         'title'       => __( 'Menu Locations' ),
523                         'panel'       => 'nav_menus',
524                         'priority'    => 5,
525                         'description' => $description,
526                 ) );
527
528                 $choices = array( '0' => __( '&mdash; Select &mdash;' ) );
529                 foreach ( $menus as $menu ) {
530                         $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '&hellip;' );
531                 }
532
533                 foreach ( $locations as $location => $description ) {
534                         $setting_id = "nav_menu_locations[{$location}]";
535
536                         $setting = $this->manager->get_setting( $setting_id );
537                         if ( $setting ) {
538                                 $setting->transport = 'postMessage';
539                                 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
540                                 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
541                         } else {
542                                 $this->manager->add_setting( $setting_id, array(
543                                         'sanitize_callback' => array( $this, 'intval_base10' ),
544                                         'theme_supports'    => 'menus',
545                                         'type'              => 'theme_mod',
546                                         'transport'         => 'postMessage',
547                                         'default'           => 0,
548                                 ) );
549                         }
550
551                         $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
552                                 'label'       => $description,
553                                 'location_id' => $location,
554                                 'section'     => 'menu_locations',
555                                 'choices'     => $choices,
556                         ) ) );
557                 }
558
559                 // Register each menu as a Customizer section, and add each menu item to each menu.
560                 foreach ( $menus as $menu ) {
561                         $menu_id = $menu->term_id;
562
563                         // Create a section for each menu.
564                         $section_id = 'nav_menu[' . $menu_id . ']';
565                         $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
566                                 'title'     => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
567                                 'priority'  => 10,
568                                 'panel'     => 'nav_menus',
569                         ) ) );
570
571                         $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
572                         $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
573                                 'transport' => 'postMessage',
574                         ) ) );
575
576                         // Add the menu contents.
577                         $menu_items = (array) wp_get_nav_menu_items( $menu_id );
578
579                         foreach ( array_values( $menu_items ) as $i => $item ) {
580
581                                 // Create a setting for each menu item (which doesn't actually manage data, currently).
582                                 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
583
584                                 $value = (array) $item;
585                                 $value['nav_menu_term_id'] = $menu_id;
586                                 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
587                                         'value'     => $value,
588                                         'transport' => 'postMessage',
589                                 ) ) );
590
591                                 // Create a control for each menu item.
592                                 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
593                                         'label'    => $item->title,
594                                         'section'  => $section_id,
595                                         'priority' => 10 + $i,
596                                 ) ) );
597                         }
598
599                         // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
600                 }
601
602                 // Add the add-new-menu section and controls.
603                 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
604                         'title'    => __( 'Add a Menu' ),
605                         'panel'    => 'nav_menus',
606                         'priority' => 999,
607                 ) ) );
608
609                 $this->manager->add_control( 'new_menu_name', array(
610                         'label'       => '',
611                         'section'     => 'add_menu',
612                         'type'        => 'text',
613                         'settings'    => array(),
614                         'input_attrs' => array(
615                                 'class'       => 'menu-name-field',
616                                 'placeholder' => __( 'New menu name' ),
617                         ),
618                 ) );
619
620                 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
621                         'section'  => 'add_menu',
622                         'settings' => array(),
623                 ) ) );
624         }
625
626         /**
627          * Get the base10 intval.
628          *
629          * This is used as a setting's sanitize_callback; we can't use just plain
630          * intval because the second argument is not what intval() expects.
631          *
632          * @since 4.3.0
633          * @access public
634          *
635          * @param mixed $value Number to convert.
636          * @return int Integer.
637          */
638         public function intval_base10( $value ) {
639                 return intval( $value, 10 );
640         }
641
642         /**
643          * Return an array of all the available item types.
644          *
645          * @since 4.3.0
646          * @access public
647          *
648          * @return array The available menu item types.
649          */
650         public function available_item_types() {
651                 $item_types = array();
652
653                 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
654                 if ( $post_types ) {
655                         foreach ( $post_types as $slug => $post_type ) {
656                                 $item_types[] = array(
657                                         'title'  => $post_type->labels->name,
658                                         'type'   => 'post_type',
659                                         'object' => $post_type->name,
660                                 );
661                         }
662                 }
663
664                 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
665                 if ( $taxonomies ) {
666                         foreach ( $taxonomies as $slug => $taxonomy ) {
667                                 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
668                                         continue;
669                                 }
670                                 $item_types[] = array(
671                                         'title'  => $taxonomy->labels->name,
672                                         'type'   => 'taxonomy',
673                                         'object' => $taxonomy->name,
674                                 );
675                         }
676                 }
677
678                 /**
679                  * Filter the available menu item types.
680                  *
681                  * @since 4.3.0
682                  *
683                  * @param array $item_types Custom menu item types.
684                  */
685                 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
686
687                 return $item_types;
688         }
689
690         /**
691          * Print the JavaScript templates used to render Menu Customizer components.
692          *
693          * Templates are imported into the JS use wp.template.
694          *
695          * @since 4.3.0
696          * @access public
697          */
698         public function print_templates() {
699                 ?>
700                 <script type="text/html" id="tmpl-available-menu-item">
701                         <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
702                                 <div class="menu-item-bar">
703                                         <div class="menu-item-handle">
704                                                 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
705                                                 <span class="item-title" aria-hidden="true">
706                                                         <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
707                                                 </span>
708                                                 <button type="button" class="button-link item-add">
709                                                         <span class="screen-reader-text"><?php
710                                                                 /* translators: 1: Title of a menu item, 2: Type of a menu item */
711                                                                 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
712                                                         ?></span>
713                                                 </button>
714                                         </div>
715                                 </div>
716                         </li>
717                 </script>
718
719                 <script type="text/html" id="tmpl-menu-item-reorder-nav">
720                         <div class="menu-item-reorder-nav">
721                                 <?php
722                                 printf(
723                                         '<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>',
724                                         __( 'Move up' ),
725                                         __( 'Move down' ),
726                                         __( 'Move one level up' ),
727                                         __( 'Move one level down' )
728                                 );
729                                 ?>
730                         </div>
731                 </script>
732         <?php
733         }
734
735         /**
736          * Print the html template used to render the add-menu-item frame.
737          *
738          * @since 4.3.0
739          * @access public
740          */
741         public function available_items_template() {
742                 ?>
743                 <div id="available-menu-items" class="accordion-container">
744                         <div class="customize-section-title">
745                                 <button type="button" class="customize-section-back" tabindex="-1">
746                                         <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
747                                 </button>
748                                 <h3>
749                                         <span class="customize-action">
750                                                 <?php
751                                                         /* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
752                                                         printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
753                                                 ?>
754                                         </span>
755                                         <?php _e( 'Add Menu Items' ); ?>
756                                 </h3>
757                         </div>
758                         <div id="available-menu-items-search" class="accordion-section cannot-expand">
759                                 <div class="accordion-section-title">
760                                         <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
761                                         <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ) ?>" aria-describedby="menu-items-search-desc" />
762                                         <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
763                                         <span class="spinner"></span>
764                                         <span class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></span>
765                                 </div>
766                                 <ul class="accordion-section-content" data-type="search"></ul>
767                         </div>
768                         <div id="new-custom-menu-item" class="accordion-section">
769                                 <h4 class="accordion-section-title" role="presentation">
770                                         <?php _e( 'Custom Links' ); ?>
771                                         <button type="button" class="button-link" aria-expanded="false">
772                                                 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
773                                                 <span class="toggle-indicator" aria-hidden="true"></span>
774                                         </button>
775                                 </h4>
776                                 <div class="accordion-section-content customlinkdiv">
777                                         <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
778                                         <p id="menu-item-url-wrap" class="wp-clearfix">
779                                                 <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
780                                                 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
781                                         </p>
782                                         <p id="menu-item-name-wrap" class="wp-clearfix">
783                                                 <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
784                                                 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
785                                         </p>
786                                         <p class="button-controls">
787                                                 <span class="add-to-menu">
788                                                         <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">
789                                                         <span class="spinner"></span>
790                                                 </span>
791                                         </p>
792                                 </div>
793                         </div>
794                         <?php
795                         // Containers for per-post-type item browsing; items added with JS.
796                         foreach ( $this->available_item_types() as $available_item_type ) {
797                                 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
798                                 ?>
799                                 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
800                                         <h4 class="accordion-section-title" role="presentation">
801                                                 <?php echo esc_html( $available_item_type['title'] ); ?>
802                                                 <span class="spinner"></span>
803                                                 <span class="no-items"><?php _e( 'No items' ); ?></span>
804                                                 <button type="button" class="button-link" aria-expanded="false">
805                                                         <span class="screen-reader-text"><?php
806                                                         /* translators: %s: Title of a section with menu items */
807                                                         printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
808                                                         <span class="toggle-indicator" aria-hidden="true"></span>
809                                                 </button>
810                                         </h4>
811                                         <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>
812                                 </div>
813                                 <?php
814                         }
815                         ?>
816                 </div><!-- #available-menu-items -->
817         <?php
818         }
819
820         //
821         // Start functionality specific to partial-refresh of menu changes in Customizer preview.
822         //
823
824         /**
825          * Nav menu args used for each instance, keyed by the args HMAC.
826          *
827          * @since 4.3.0
828          * @access public
829          * @var array
830          */
831         public $preview_nav_menu_instance_args = array();
832
833         /**
834          * Filter arguments for dynamic nav_menu selective refresh partials.
835          *
836          * @since 4.5.0
837          * @access public
838          *
839          * @param array|false $partial_args Partial args.
840          * @param string      $partial_id   Partial ID.
841          * @return array Partial args.
842          */
843         public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
844
845                 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
846                         if ( false === $partial_args ) {
847                                 $partial_args = array();
848                         }
849                         $partial_args = array_merge(
850                                 $partial_args,
851                                 array(
852                                         'type'                => 'nav_menu_instance',
853                                         'render_callback'     => array( $this, 'render_nav_menu_partial' ),
854                                         'container_inclusive' => true,
855                                         'settings'            => array(), // Empty because the nav menu instance may relate to a menu or a location.
856                                         'capability'          => 'edit_theme_options',
857                                 )
858                         );
859                 }
860
861                 return $partial_args;
862         }
863
864         /**
865          * Add hooks for the Customizer preview.
866          *
867          * @since 4.3.0
868          * @access public
869          */
870         public function customize_preview_init() {
871                 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
872                 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
873                 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
874                 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
875                 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
876         }
877
878         /**
879          * Keep track of the arguments that are being passed to wp_nav_menu().
880          *
881          * @since 4.3.0
882          * @access public
883          * @see wp_nav_menu()
884          * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
885          *
886          * @param array $args An array containing wp_nav_menu() arguments.
887          * @return array Arguments.
888          */
889         public function filter_wp_nav_menu_args( $args ) {
890                 /*
891                  * The following conditions determine whether or not this instance of
892                  * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
893                  * selective refreshed if...
894                  */
895                 $can_partial_refresh = (
896                         // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
897                         ! empty( $args['echo'] )
898                         &&
899                         // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
900                         ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
901                         &&
902                         // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
903                         ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
904                         // ...and if it has a theme location assigned or an assigned menu to display,
905                         && (
906                                 ! empty( $args['theme_location'] )
907                                 ||
908                                 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
909                         )
910                         &&
911                         // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
912                         (
913                                 ! empty( $args['container'] )
914                                 ||
915                                 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
916                         )
917                 );
918                 $args['can_partial_refresh'] = $can_partial_refresh;
919
920                 $exported_args = $args;
921
922                 // Empty out args which may not be JSON-serializable.
923                 if ( ! $can_partial_refresh ) {
924                         $exported_args['fallback_cb'] = '';
925                         $exported_args['walker'] = '';
926                 }
927
928                 /*
929                  * Replace object menu arg with a term_id menu arg, as this exports better
930                  * to JS and is easier to compare hashes.
931                  */
932                 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
933                         $exported_args['menu'] = $exported_args['menu']->term_id;
934                 }
935
936                 ksort( $exported_args );
937                 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
938
939                 $args['customize_preview_nav_menus_args'] = $exported_args;
940                 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
941                 return $args;
942         }
943
944         /**
945          * Prepares wp_nav_menu() calls for partial refresh.
946          *
947          * Injects attributes into container element.
948          *
949          * @since 4.3.0
950          * @access public
951          *
952          * @see wp_nav_menu()
953          *
954          * @param string $nav_menu_content The HTML content for the navigation menu.
955          * @param object $args             An object containing wp_nav_menu() arguments.
956          * @return null
957          */
958         public function filter_wp_nav_menu( $nav_menu_content, $args ) {
959                 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
960                         $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
961                         $attributes .= ' data-customize-partial-type="nav_menu_instance"';
962                         $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
963                         $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
964                 }
965                 return $nav_menu_content;
966         }
967
968         /**
969          * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
970          * submitted in the Ajax request.
971          *
972          * Note that the array is expected to be pre-sorted.
973          *
974          * @since 4.3.0
975          * @access public
976          *
977          * @param array $args The arguments to hash.
978          * @return string Hashed nav menu arguments.
979          */
980         public function hash_nav_menu_args( $args ) {
981                 return wp_hash( serialize( $args ) );
982         }
983
984         /**
985          * Enqueue scripts for the Customizer preview.
986          *
987          * @since 4.3.0
988          * @access public
989          */
990         public function customize_preview_enqueue_deps() {
991                 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
992                 wp_enqueue_style( 'customize-preview' );
993         }
994
995         /**
996          * Exports data from PHP to JS.
997          *
998          * @since 4.3.0
999          * @access public
1000          */
1001         public function export_preview_data() {
1002
1003                 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1004                 $exports = array(
1005                         'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1006                 );
1007                 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1008         }
1009
1010         /**
1011          * Export any wp_nav_menu() calls during the rendering of any partials.
1012          *
1013          * @since 4.5.0
1014          * @access public
1015          *
1016          * @param array $response Response.
1017          * @return array Response.
1018          */
1019         public function export_partial_rendered_nav_menu_instances( $response ) {
1020                 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1021                 return $response;
1022         }
1023
1024         /**
1025          * Render a specific menu via wp_nav_menu() using the supplied arguments.
1026          *
1027          * @since 4.3.0
1028          * @access public
1029          *
1030          * @see wp_nav_menu()
1031          *
1032          * @param WP_Customize_Partial $partial       Partial.
1033          * @param array                $nav_menu_args Nav menu args supplied as container context.
1034          * @return string|false
1035          */
1036         public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1037                 unset( $partial );
1038
1039                 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1040                         // Error: missing_args_hmac.
1041                         return false;
1042                 }
1043
1044                 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1045                 unset( $nav_menu_args['args_hmac'] );
1046
1047                 ksort( $nav_menu_args );
1048                 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1049                         // Error: args_hmac_mismatch.
1050                         return false;
1051                 }
1052
1053                 ob_start();
1054                 wp_nav_menu( $nav_menu_args );
1055                 $content = ob_get_clean();
1056
1057                 return $content;
1058         }
1059 }