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