WordPress 4.7
[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                 // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499
52                 add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
53                 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
54                 add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
55
56                 // Skip remaining hooks when the user can't manage nav menus anyway.
57                 if ( ! current_user_can( 'edit_theme_options' ) ) {
58                         return;
59                 }
60
61                 add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) );
62                 add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) );
63                 add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
64                 add_action( 'wp_ajax_customize-nav-menus-insert-auto-draft', array( $this, 'ajax_insert_auto_draft_post' ) );
65                 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
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                 add_action( 'customize_preview_init', array( $this, 'make_auto_draft_status_previewable' ) );
70                 add_action( 'customize_save_nav_menus_created_posts', array( $this, 'save_nav_menus_created_posts' ) );
71
72                 // Selective Refresh partials.
73                 add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
74         }
75
76         /**
77          * Adds a nonce for customizing menus.
78          *
79          * @since 4.5.0
80          * @access public
81          *
82          * @param array $nonces Array of nonces.
83          * @return array $nonces Modified array of nonces.
84          */
85         public function filter_nonces( $nonces ) {
86                 $nonces['customize-menus'] = wp_create_nonce( 'customize-menus' );
87                 return $nonces;
88         }
89
90         /**
91          * Ajax handler for loading available menu items.
92          *
93          * @since 4.3.0
94          * @access public
95          */
96         public function ajax_load_available_items() {
97                 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
98
99                 if ( ! current_user_can( 'edit_theme_options' ) ) {
100                         wp_die( -1 );
101                 }
102
103                 $all_items = array();
104                 $item_types = array();
105                 if ( isset( $_POST['item_types'] ) && is_array( $_POST['item_types'] ) ) {
106                         $item_types = wp_unslash( $_POST['item_types'] );
107                 } elseif ( isset( $_POST['type'] ) && isset( $_POST['object'] ) ) { // Back compat.
108                         $item_types[] = array(
109                                 'type' => wp_unslash( $_POST['type'] ),
110                                 'object' => wp_unslash( $_POST['object'] ),
111                                 'page' => empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] ),
112                         );
113                 } else {
114                         wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
115                 }
116
117                 foreach ( $item_types as $item_type ) {
118                         if ( empty( $item_type['type'] ) || empty( $item_type['object'] ) ) {
119                                 wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
120                         }
121                         $type = sanitize_key( $item_type['type'] );
122                         $object = sanitize_key( $item_type['object'] );
123                         $page = empty( $item_type['page'] ) ? 0 : absint( $item_type['page'] );
124                         $items = $this->load_available_items_query( $type, $object, $page );
125                         if ( is_wp_error( $items ) ) {
126                                 wp_send_json_error( $items->get_error_code() );
127                         }
128                         $all_items[ $item_type['type'] . ':' . $item_type['object'] ] = $items;
129                 }
130
131                 wp_send_json_success( array( 'items' => $all_items ) );
132         }
133
134         /**
135          * Performs the post_type and taxonomy queries for loading available menu items.
136          *
137          * @since 4.3.0
138          * @access public
139          *
140          * @param string $type   Optional. Accepts any custom object type and has built-in support for
141          *                         'post_type' and 'taxonomy'. Default is 'post_type'.
142          * @param string $object Optional. Accepts any registered taxonomy or post type name. Default is 'page'.
143          * @param int    $page   Optional. The page number used to generate the query offset. Default is '0'.
144          * @return WP_Error|array Returns either a WP_Error object or an array of menu items.
145          */
146         public function load_available_items_query( $type = 'post_type', $object = 'page', $page = 0 ) {
147                 $items = array();
148
149                 if ( 'post_type' === $type ) {
150                         $post_type = get_post_type_object( $object );
151                         if ( ! $post_type ) {
152                                 return new WP_Error( 'nav_menus_invalid_post_type' );
153                         }
154
155                         if ( 0 === $page && 'page' === $object ) {
156                                 // Add "Home" link. Treat as a page, but switch to custom on add.
157                                 $items[] = array(
158                                         'id'         => 'home',
159                                         'title'      => _x( 'Home', 'nav menu home label' ),
160                                         'type'       => 'custom',
161                                         'type_label' => __( 'Custom Link' ),
162                                         'object'     => '',
163                                         'url'        => home_url(),
164                                 );
165                         } elseif ( 'post' !== $object && 0 === $page && $post_type->has_archive ) {
166                                 // Add a post type archive link.
167                                 $items[] = array(
168                                         'id'         => $object . '-archive',
169                                         'title'      => $post_type->labels->archives,
170                                         'type'       => 'post_type_archive',
171                                         'type_label' => __( 'Post Type Archive' ),
172                                         'object'     => $object,
173                                         'url'        => get_post_type_archive_link( $object ),
174                                 );
175                         }
176
177                         // Prepend posts with nav_menus_created_posts on first page.
178                         $posts = array();
179                         if ( 0 === $page && $this->manager->get_setting( 'nav_menus_created_posts' ) ) {
180                                 foreach ( $this->manager->get_setting( 'nav_menus_created_posts' )->value() as $post_id ) {
181                                         $auto_draft_post = get_post( $post_id );
182                                         if ( $post_type->name === $auto_draft_post->post_type ) {
183                                                 $posts[] = $auto_draft_post;
184                                         }
185                                 }
186                         }
187
188                         $posts = array_merge( $posts, get_posts( array(
189                                 'numberposts' => 10,
190                                 'offset'      => 10 * $page,
191                                 'orderby'     => 'date',
192                                 'order'       => 'DESC',
193                                 'post_type'   => $object,
194                         ) ) );
195
196                         foreach ( $posts as $post ) {
197                                 $post_title = $post->post_title;
198                                 if ( '' === $post_title ) {
199                                         /* translators: %d: ID of a post */
200                                         $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
201                                 }
202                                 $items[] = array(
203                                         'id'         => "post-{$post->ID}",
204                                         'title'      => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
205                                         'type'       => 'post_type',
206                                         'type_label' => get_post_type_object( $post->post_type )->labels->singular_name,
207                                         'object'     => $post->post_type,
208                                         'object_id'  => intval( $post->ID ),
209                                         'url'        => get_permalink( intval( $post->ID ) ),
210                                 );
211                         }
212                 } elseif ( 'taxonomy' === $type ) {
213                         $terms = get_terms( $object, array(
214                                 'child_of'     => 0,
215                                 'exclude'      => '',
216                                 'hide_empty'   => false,
217                                 'hierarchical' => 1,
218                                 'include'      => '',
219                                 'number'       => 10,
220                                 'offset'       => 10 * $page,
221                                 'order'        => 'DESC',
222                                 'orderby'      => 'count',
223                                 'pad_counts'   => false,
224                         ) );
225                         if ( is_wp_error( $terms ) ) {
226                                 return $terms;
227                         }
228
229                         foreach ( $terms as $term ) {
230                                 $items[] = array(
231                                         'id'         => "term-{$term->term_id}",
232                                         'title'      => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
233                                         'type'       => 'taxonomy',
234                                         'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
235                                         'object'     => $term->taxonomy,
236                                         'object_id'  => intval( $term->term_id ),
237                                         'url'        => get_term_link( intval( $term->term_id ), $term->taxonomy ),
238                                 );
239                         }
240                 }
241
242                 /**
243                  * Filters the available menu items.
244                  *
245                  * @since 4.3.0
246                  *
247                  * @param array  $items  The array of menu items.
248                  * @param string $type   The object type.
249                  * @param string $object The object name.
250                  * @param int    $page   The current page number.
251                  */
252                 $items = apply_filters( 'customize_nav_menu_available_items', $items, $type, $object, $page );
253
254                 return $items;
255         }
256
257         /**
258          * Ajax handler for searching available menu items.
259          *
260          * @since 4.3.0
261          * @access public
262          */
263         public function ajax_search_available_items() {
264                 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
265
266                 if ( ! current_user_can( 'edit_theme_options' ) ) {
267                         wp_die( -1 );
268                 }
269
270                 if ( empty( $_POST['search'] ) ) {
271                         wp_send_json_error( 'nav_menus_missing_search_parameter' );
272                 }
273
274                 $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0;
275                 if ( $p < 1 ) {
276                         $p = 1;
277                 }
278
279                 $s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
280                 $items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s ) );
281
282                 if ( empty( $items ) ) {
283                         wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
284                 } else {
285                         wp_send_json_success( array( 'items' => $items ) );
286                 }
287         }
288
289         /**
290          * Performs post queries for available-item searching.
291          *
292          * Based on WP_Editor::wp_link_query().
293          *
294          * @since 4.3.0
295          * @access public
296          *
297          * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
298          * @return array Menu items.
299          */
300         public function search_available_items_query( $args = array() ) {
301                 $items = array();
302
303                 $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
304                 $query = array(
305                         'post_type'              => array_keys( $post_type_objects ),
306                         'suppress_filters'       => true,
307                         'update_post_term_cache' => false,
308                         'update_post_meta_cache' => false,
309                         'post_status'            => 'publish',
310                         'posts_per_page'         => 20,
311                 );
312
313                 $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
314                 $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
315
316                 if ( isset( $args['s'] ) ) {
317                         $query['s'] = $args['s'];
318                 }
319
320                 $posts = array();
321
322                 // Prepend list of posts with nav_menus_created_posts search results on first page.
323                 $nav_menus_created_posts_setting = $this->manager->get_setting( 'nav_menus_created_posts' );
324                 if ( 1 === $args['pagenum'] && $nav_menus_created_posts_setting && count( $nav_menus_created_posts_setting ) > 0 ) {
325                         $stub_post_query = new WP_Query( array_merge(
326                                 $query,
327                                 array(
328                                         'post_status' => 'auto-draft',
329                                         'post__in' => $nav_menus_created_posts_setting->value(),
330                                         'posts_per_page' => -1,
331                                 )
332                         ) );
333                         $posts = array_merge( $posts, $stub_post_query->posts );
334                 }
335
336                 // Query posts.
337                 $get_posts = new WP_Query( $query );
338                 $posts = array_merge( $posts, $get_posts->posts );
339
340                 // Create items for posts.
341                 foreach ( $posts as $post ) {
342                         $post_title = $post->post_title;
343                         if ( '' === $post_title ) {
344                                 /* translators: %d: ID of a post */
345                                 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
346                         }
347                         $items[] = array(
348                                 'id'         => 'post-' . $post->ID,
349                                 'title'      => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
350                                 'type'       => 'post_type',
351                                 'type_label' => $post_type_objects[ $post->post_type ]->labels->singular_name,
352                                 'object'     => $post->post_type,
353                                 'object_id'  => intval( $post->ID ),
354                                 'url'        => get_permalink( intval( $post->ID ) ),
355                         );
356                 }
357
358                 // Query taxonomy terms.
359                 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
360                 $terms = get_terms( $taxonomies, array(
361                         'name__like' => $args['s'],
362                         'number'     => 20,
363                         'offset'     => 20 * ($args['pagenum'] - 1),
364                 ) );
365
366                 // Check if any taxonomies were found.
367                 if ( ! empty( $terms ) ) {
368                         foreach ( $terms as $term ) {
369                                 $items[] = array(
370                                         'id'         => 'term-' . $term->term_id,
371                                         'title'      => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
372                                         'type'       => 'taxonomy',
373                                         'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
374                                         'object'     => $term->taxonomy,
375                                         'object_id'  => intval( $term->term_id ),
376                                         'url'        => get_term_link( intval( $term->term_id ), $term->taxonomy ),
377                                 );
378                         }
379                 }
380
381                 /**
382                  * Filters the available menu items during a search request.
383                  *
384                  * @since 4.5.0
385                  *
386                  * @param array $items The array of menu items.
387                  * @param array $args  Includes 'pagenum' and 's' (search) arguments.
388                  */
389                 $items = apply_filters( 'customize_nav_menu_searched_items', $items, $args );
390
391                 return $items;
392         }
393
394         /**
395          * Enqueue scripts and styles for Customizer pane.
396          *
397          * @since 4.3.0
398          * @access public
399          */
400         public function enqueue_scripts() {
401                 wp_enqueue_style( 'customize-nav-menus' );
402                 wp_enqueue_script( 'customize-nav-menus' );
403
404                 $temp_nav_menu_setting      = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' );
405                 $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' );
406
407                 // Pass data to JS.
408                 $settings = array(
409                         'allMenus'             => wp_get_nav_menus(),
410                         'itemTypes'            => $this->available_item_types(),
411                         'l10n'                 => array(
412                                 'untitled'          => _x( '(no label)', 'missing menu item navigation label' ),
413                                 'unnamed'           => _x( '(unnamed)', 'Missing menu name.' ),
414                                 'custom_label'      => __( 'Custom Link' ),
415                                 'page_label'        => get_post_type_object( 'page' )->labels->singular_name,
416                                 /* translators: %s: menu location */
417                                 'menuLocation'      => _x( '(Currently set to: %s)', 'menu' ),
418                                 'menuNameLabel'     => __( 'Menu Name' ),
419                                 'itemAdded'         => __( 'Menu item added' ),
420                                 'itemDeleted'       => __( 'Menu item deleted' ),
421                                 'menuAdded'         => __( 'Menu created' ),
422                                 'menuDeleted'       => __( 'Menu deleted' ),
423                                 'movedUp'           => __( 'Menu item moved up' ),
424                                 'movedDown'         => __( 'Menu item moved down' ),
425                                 'movedLeft'         => __( 'Menu item moved out of submenu' ),
426                                 'movedRight'        => __( 'Menu item is now a sub-item' ),
427                                 /* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
428                                 'customizingMenus'  => sprintf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ),
429                                 /* translators: %s: title of menu item which is invalid */
430                                 'invalidTitleTpl'   => __( '%s (Invalid)' ),
431                                 /* translators: %s: title of menu item in draft status */
432                                 'pendingTitleTpl'   => __( '%s (Pending)' ),
433                                 'itemsFound'        => __( 'Number of items found: %d' ),
434                                 'itemsFoundMore'    => __( 'Additional items found: %d' ),
435                                 'itemsLoadingMore'  => __( 'Loading more results... please wait.' ),
436                                 'reorderModeOn'     => __( 'Reorder mode enabled' ),
437                                 'reorderModeOff'    => __( 'Reorder mode closed' ),
438                                 'reorderLabelOn'    => esc_attr__( 'Reorder menu items' ),
439                                 'reorderLabelOff'   => esc_attr__( 'Close reorder mode' ),
440                         ),
441                         'settingTransport'     => 'postMessage',
442                         'phpIntMax'            => PHP_INT_MAX,
443                         'defaultSettingValues' => array(
444                                 'nav_menu'      => $temp_nav_menu_setting->default,
445                                 'nav_menu_item' => $temp_nav_menu_item_setting->default,
446                         ),
447                         'locationSlugMappedToName' => get_registered_nav_menus(),
448                 );
449
450                 $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) );
451                 wp_scripts()->add_data( 'customize-nav-menus', 'data', $data );
452
453                 // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
454                 $nav_menus_l10n = array(
455                         'oneThemeLocationNoMenus' => null,
456                         'moveUp'       => __( 'Move up one' ),
457                         'moveDown'     => __( 'Move down one' ),
458                         'moveToTop'    => __( 'Move to the top' ),
459                         /* translators: %s: previous item name */
460                         'moveUnder'    => __( 'Move under %s' ),
461                         /* translators: %s: previous item name */
462                         'moveOutFrom'  => __( 'Move out from under %s' ),
463                         /* translators: %s: previous item name */
464                         'under'        => __( 'Under %s' ),
465                         /* translators: %s: previous item name */
466                         'outFrom'      => __( 'Out from under %s' ),
467                         /* translators: 1: item name, 2: item position, 3: total number of items */
468                         'menuFocus'    => __( '%1$s. Menu item %2$d of %3$d.' ),
469                         /* translators: 1: item name, 2: item position, 3: parent item name */
470                         'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
471                 );
472                 wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
473         }
474
475         /**
476          * Filters a dynamic setting's constructor args.
477          *
478          * For a dynamic setting to be registered, this filter must be employed
479          * to override the default false value with an array of args to pass to
480          * the WP_Customize_Setting constructor.
481          *
482          * @since 4.3.0
483          * @access public
484          *
485          * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
486          * @param string      $setting_id   ID for dynamic setting, usually coming from `$_POST['customized']`.
487          * @return array|false
488          */
489         public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
490                 if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) {
491                         $setting_args = array(
492                                 'type'      => WP_Customize_Nav_Menu_Setting::TYPE,
493                                 'transport' => 'postMessage',
494                         );
495                 } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) {
496                         $setting_args = array(
497                                 'type'      => WP_Customize_Nav_Menu_Item_Setting::TYPE,
498                                 'transport' => 'postMessage',
499                         );
500                 }
501                 return $setting_args;
502         }
503
504         /**
505          * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
506          *
507          * @since 4.3.0
508          * @access public
509          *
510          * @param string $setting_class WP_Customize_Setting or a subclass.
511          * @param string $setting_id    ID for dynamic setting, usually coming from `$_POST['customized']`.
512          * @param array  $setting_args  WP_Customize_Setting or a subclass.
513          * @return string
514          */
515         public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
516                 unset( $setting_id );
517
518                 if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) {
519                         $setting_class = 'WP_Customize_Nav_Menu_Setting';
520                 } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) {
521                         $setting_class = 'WP_Customize_Nav_Menu_Item_Setting';
522                 }
523                 return $setting_class;
524         }
525
526         /**
527          * Add the customizer settings and controls.
528          *
529          * @since 4.3.0
530          * @access public
531          */
532         public function customize_register() {
533
534                 /*
535                  * Preview settings for nav menus early so that the sections and controls will be added properly.
536                  * See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L506-L543
537                  */
538                 $nav_menus_setting_ids = array();
539                 foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
540                         if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
541                                 $nav_menus_setting_ids[] = $setting_id;
542                         }
543                 }
544                 $this->manager->add_dynamic_settings( $nav_menus_setting_ids );
545                 foreach ( $nav_menus_setting_ids as $setting_id ) {
546                         $setting = $this->manager->get_setting( $setting_id );
547                         if ( $setting ) {
548                                 $setting->preview();
549                         }
550                 }
551
552                 // Require JS-rendered control types.
553                 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
554                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
555                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
556                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
557                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
558
559                 // Create a panel for Menus.
560                 $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>';
561                 if ( current_theme_supports( 'widgets' ) ) {
562                         /* translators: URL to the widgets panel of the customizer */
563                         $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>';
564                 } else {
565                         $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
566                 }
567                 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
568                         'title'       => __( 'Menus' ),
569                         'description' => $description,
570                         'priority'    => 100,
571                         // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
572                 ) ) );
573                 $menus = wp_get_nav_menus();
574
575                 // Menu locations.
576                 $locations     = get_registered_nav_menus();
577                 $num_locations = count( array_keys( $locations ) );
578                 if ( 1 == $num_locations ) {
579                         $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' ) . '</p>';
580                 } else {
581                         /* translators: %s: number of menu locations */
582                         $description = '<p>' . sprintf( _n( 'Your theme supports %s menu. Select which menu appears in each location.', 'Your theme supports %s menus. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . '</p>';
583                 }
584                 if ( current_theme_supports( 'widgets' ) ) {
585                         /* translators: URL to the widgets panel of the customizer */
586                         $description .= '<p>' . sprintf( __( 'You can also place menus in <a href="%s">widget areas</a> with the &#8220;Custom Menu&#8221; widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
587                 }
588
589                 $this->manager->add_section( 'menu_locations', array(
590                         'title'       => __( 'Menu Locations' ),
591                         'panel'       => 'nav_menus',
592                         'priority'    => 5,
593                         'description' => $description,
594                 ) );
595
596                 $choices = array( '0' => __( '&mdash; Select &mdash;' ) );
597                 foreach ( $menus as $menu ) {
598                         $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '&hellip;' );
599                 }
600
601                 foreach ( $locations as $location => $description ) {
602                         $setting_id = "nav_menu_locations[{$location}]";
603
604                         $setting = $this->manager->get_setting( $setting_id );
605                         if ( $setting ) {
606                                 $setting->transport = 'postMessage';
607                                 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
608                                 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
609                         } else {
610                                 $this->manager->add_setting( $setting_id, array(
611                                         'sanitize_callback' => array( $this, 'intval_base10' ),
612                                         'theme_supports'    => 'menus',
613                                         'type'              => 'theme_mod',
614                                         'transport'         => 'postMessage',
615                                         'default'           => 0,
616                                 ) );
617                         }
618
619                         $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
620                                 'label'       => $description,
621                                 'location_id' => $location,
622                                 'section'     => 'menu_locations',
623                                 'choices'     => $choices,
624                         ) ) );
625                 }
626
627                 // Register each menu as a Customizer section, and add each menu item to each menu.
628                 foreach ( $menus as $menu ) {
629                         $menu_id = $menu->term_id;
630
631                         // Create a section for each menu.
632                         $section_id = 'nav_menu[' . $menu_id . ']';
633                         $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
634                                 'title'     => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
635                                 'priority'  => 10,
636                                 'panel'     => 'nav_menus',
637                         ) ) );
638
639                         $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
640                         $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
641                                 'transport' => 'postMessage',
642                         ) ) );
643
644                         // Add the menu contents.
645                         $menu_items = (array) wp_get_nav_menu_items( $menu_id );
646
647                         foreach ( array_values( $menu_items ) as $i => $item ) {
648
649                                 // Create a setting for each menu item (which doesn't actually manage data, currently).
650                                 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
651
652                                 $value = (array) $item;
653                                 if ( empty( $value['post_title'] ) ) {
654                                         $value['title'] = '';
655                                 }
656
657                                 $value['nav_menu_term_id'] = $menu_id;
658                                 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
659                                         'value'     => $value,
660                                         'transport' => 'postMessage',
661                                 ) ) );
662
663                                 // Create a control for each menu item.
664                                 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
665                                         'label'    => $item->title,
666                                         'section'  => $section_id,
667                                         'priority' => 10 + $i,
668                                 ) ) );
669                         }
670
671                         // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
672                 }
673
674                 // Add the add-new-menu section and controls.
675                 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
676                         'title'    => __( 'Add a Menu' ),
677                         'panel'    => 'nav_menus',
678                         'priority' => 999,
679                 ) ) );
680
681                 $this->manager->add_control( 'new_menu_name', array(
682                         'label'       => '',
683                         'section'     => 'add_menu',
684                         'type'        => 'text',
685                         'settings'    => array(),
686                         'input_attrs' => array(
687                                 'class'       => 'menu-name-field',
688                                 'placeholder' => __( 'New menu name' ),
689                         ),
690                 ) );
691
692                 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
693                         'section'  => 'add_menu',
694                         'settings' => array(),
695                 ) ) );
696
697                 $this->manager->add_setting( new WP_Customize_Filter_Setting( $this->manager, 'nav_menus_created_posts', array(
698                         'transport' => 'postMessage',
699                         'type' => 'option', // To prevent theme prefix in changeset.
700                         'default' => array(),
701                         'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
702                 ) ) );
703         }
704
705         /**
706          * Get the base10 intval.
707          *
708          * This is used as a setting's sanitize_callback; we can't use just plain
709          * intval because the second argument is not what intval() expects.
710          *
711          * @since 4.3.0
712          * @access public
713          *
714          * @param mixed $value Number to convert.
715          * @return int Integer.
716          */
717         public function intval_base10( $value ) {
718                 return intval( $value, 10 );
719         }
720
721         /**
722          * Return an array of all the available item types.
723          *
724          * @since 4.3.0
725          * @since 4.7.0  Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
726          * @access public
727          *
728          * @return array The available menu item types.
729          */
730         public function available_item_types() {
731                 $item_types = array();
732
733                 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
734                 if ( $post_types ) {
735                         foreach ( $post_types as $slug => $post_type ) {
736                                 $item_types[] = array(
737                                         'title'  => $post_type->labels->name,
738                                         'type_label' => $post_type->labels->singular_name,
739                                         'type' => 'post_type',
740                                         'object' => $post_type->name,
741                                 );
742                         }
743                 }
744
745                 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
746                 if ( $taxonomies ) {
747                         foreach ( $taxonomies as $slug => $taxonomy ) {
748                                 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
749                                         continue;
750                                 }
751                                 $item_types[] = array(
752                                         'title' => $taxonomy->labels->name,
753                                         'type_label' => $taxonomy->labels->singular_name,
754                                         'type' => 'taxonomy',
755                                         'object' => $taxonomy->name,
756                                 );
757                         }
758                 }
759
760                 /**
761                  * Filters the available menu item types.
762                  *
763                  * @since 4.3.0
764                  * @since 4.7.0  Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
765                  *
766                  * @param array $item_types Custom menu item types.
767                  */
768                 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
769
770                 return $item_types;
771         }
772
773         /**
774          * Add a new `auto-draft` post.
775          *
776          * @access public
777          * @since 4.7.0
778          *
779          * @param array $postarr {
780          *     Post array. Note that post_status is overridden to be `auto-draft`.
781          *
782          *     @var string $post_title   Post title. Required.
783          *     @var string $post_type    Post type. Required.
784          *     @var string $post_name    Post name.
785          *     @var string $post_content Post content.
786          * }
787          * @return WP_Post|WP_Error Inserted auto-draft post object or error.
788          */
789         public function insert_auto_draft_post( $postarr ) {
790                 if ( ! isset( $postarr['post_type'] ) || ! post_type_exists( $postarr['post_type'] )  ) {
791                         return new WP_Error( 'unknown_post_type', __( 'Unknown post type' ) );
792                 }
793                 if ( empty( $postarr['post_title'] ) ) {
794                         return new WP_Error( 'empty_title', __( 'Empty title' ) );
795                 }
796                 if ( ! empty( $postarr['post_status'] ) ) {
797                         return new WP_Error( 'status_forbidden', __( 'Status is forbidden' ) );
798                 }
799
800                 $postarr['post_status'] = 'auto-draft';
801
802                 // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set.
803                 if ( empty( $postarr['post_name'] ) ) {
804                         $postarr['post_name'] = sanitize_title( $postarr['post_title'] );
805                 }
806                 if ( ! isset( $postarr['meta_input'] ) ) {
807                         $postarr['meta_input'] = array();
808                 }
809                 $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
810                 unset( $postarr['post_name'] );
811
812                 add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
813                 $r = wp_insert_post( wp_slash( $postarr ), true );
814                 remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
815
816                 if ( is_wp_error( $r ) ) {
817                         return $r;
818                 } else {
819                         return get_post( $r );
820                 }
821         }
822
823         /**
824          * Ajax handler for adding a new auto-draft post.
825          *
826          * @access public
827          * @since 4.7.0
828          */
829         public function ajax_insert_auto_draft_post() {
830                 if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) {
831                         wp_send_json_error( 'bad_nonce', 400 );
832                 }
833
834                 if ( ! current_user_can( 'customize' ) ) {
835                         wp_send_json_error( 'customize_not_allowed', 403 );
836                 }
837
838                 if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
839                         wp_send_json_error( 'missing_params', 400 );
840                 }
841
842                 $params = wp_unslash( $_POST['params'] );
843                 $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
844                 if ( ! empty( $illegal_params ) ) {
845                         wp_send_json_error( 'illegal_params', 400 );
846                 }
847
848                 $params = array_merge(
849                         array(
850                                 'post_type' => '',
851                                 'post_title' => '',
852                         ),
853                         $params
854                 );
855
856                 if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) {
857                         status_header( 400 );
858                         wp_send_json_error( 'missing_post_type_param' );
859                 }
860
861                 $post_type_object = get_post_type_object( $params['post_type'] );
862                 if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
863                         status_header( 403 );
864                         wp_send_json_error( 'insufficient_post_permissions' );
865                 }
866
867                 $params['post_title'] = trim( $params['post_title'] );
868                 if ( '' === $params['post_title'] ) {
869                         status_header( 400 );
870                         wp_send_json_error( 'missing_post_title' );
871                 }
872
873                 $r = $this->insert_auto_draft_post( $params );
874                 if ( is_wp_error( $r ) ) {
875                         $error = $r;
876                         if ( ! empty( $post_type_object->labels->singular_name ) ) {
877                                 $singular_name = $post_type_object->labels->singular_name;
878                         } else {
879                                 $singular_name = __( 'Post' );
880                         }
881
882                         $data = array(
883                                 /* translators: %1$s is the post type name and %2$s is the error message. */
884                                 'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
885                         );
886                         wp_send_json_error( $data );
887                 } else {
888                         $post = $r;
889                         $data = array(
890                                 'post_id' => $post->ID,
891                                 'url'     => get_permalink( $post->ID ),
892                         );
893                         wp_send_json_success( $data );
894                 }
895         }
896
897         /**
898          * Print the JavaScript templates used to render Menu Customizer components.
899          *
900          * Templates are imported into the JS use wp.template.
901          *
902          * @since 4.3.0
903          * @access public
904          */
905         public function print_templates() {
906                 ?>
907                 <script type="text/html" id="tmpl-available-menu-item">
908                         <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
909                                 <div class="menu-item-bar">
910                                         <div class="menu-item-handle">
911                                                 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
912                                                 <span class="item-title" aria-hidden="true">
913                                                         <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
914                                                 </span>
915                                                 <button type="button" class="button-link item-add">
916                                                         <span class="screen-reader-text"><?php
917                                                                 /* translators: 1: Title of a menu item, 2: Type of a menu item */
918                                                                 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
919                                                         ?></span>
920                                                 </button>
921                                         </div>
922                                 </div>
923                         </li>
924                 </script>
925
926                 <script type="text/html" id="tmpl-menu-item-reorder-nav">
927                         <div class="menu-item-reorder-nav">
928                                 <?php
929                                 printf(
930                                         '<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>',
931                                         __( 'Move up' ),
932                                         __( 'Move down' ),
933                                         __( 'Move one level up' ),
934                                         __( 'Move one level down' )
935                                 );
936                                 ?>
937                         </div>
938                 </script>
939         <?php
940         }
941
942         /**
943          * Print the html template used to render the add-menu-item frame.
944          *
945          * @since 4.3.0
946          * @access public
947          */
948         public function available_items_template() {
949                 ?>
950                 <div id="available-menu-items" class="accordion-container">
951                         <div class="customize-section-title">
952                                 <button type="button" class="customize-section-back" tabindex="-1">
953                                         <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
954                                 </button>
955                                 <h3>
956                                         <span class="customize-action">
957                                                 <?php
958                                                         /* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
959                                                         printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
960                                                 ?>
961                                         </span>
962                                         <?php _e( 'Add Menu Items' ); ?>
963                                 </h3>
964                         </div>
965                         <div id="available-menu-items-search" class="accordion-section cannot-expand">
966                                 <div class="accordion-section-title">
967                                         <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
968                                         <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ) ?>" aria-describedby="menu-items-search-desc" />
969                                         <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
970                                         <span class="spinner"></span>
971                                 </div>
972                                 <div class="search-icon" aria-hidden="true"></div>
973                                 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
974                                 <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul>
975                         </div>
976                         <?php
977
978                         // Ensure the page post type comes first in the list.
979                         $item_types = $this->available_item_types();
980                         $page_item_type = null;
981                         foreach ( $item_types as $i => $item_type ) {
982                                 if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
983                                         $page_item_type = $item_type;
984                                         unset( $item_types[ $i ] );
985                                 }
986                         }
987
988                         $this->print_custom_links_available_menu_item();
989                         if ( $page_item_type ) {
990                                 $this->print_post_type_container( $page_item_type );
991                         }
992                         // Containers for per-post-type item browsing; items are added with JS.
993                         foreach ( $item_types as $item_type ) {
994                                 $this->print_post_type_container( $item_type );
995                         }
996                         ?>
997                 </div><!-- #available-menu-items -->
998         <?php
999         }
1000
1001         /**
1002          * Print the markup for new menu items.
1003          *
1004          * To be used in the template #available-menu-items.
1005          *
1006          * @since 4.7.0
1007          * @access private
1008          *
1009          * @param array $available_item_type Menu item data to output, including title, type, and label.
1010          * @return void
1011          */
1012         protected function print_post_type_container( $available_item_type ) {
1013                 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
1014                 ?>
1015                 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
1016                         <h4 class="accordion-section-title" role="presentation">
1017                                 <?php echo esc_html( $available_item_type['title'] ); ?>
1018                                 <span class="spinner"></span>
1019                                 <span class="no-items"><?php _e( 'No items' ); ?></span>
1020                                 <button type="button" class="button-link" aria-expanded="false">
1021                                         <span class="screen-reader-text"><?php
1022                                                 /* translators: %s: Title of a section with menu items */
1023                                                 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
1024                                         <span class="toggle-indicator" aria-hidden="true"></span>
1025                                 </button>
1026                         </h4>
1027                         <div class="accordion-section-content">
1028                                 <?php if ( 'post_type' === $available_item_type['type'] ) : ?>
1029                                         <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?>
1030                                         <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?>
1031                                                 <div class="new-content-item">
1032                                                         <input type="text" class="create-item-input" placeholder="<?php echo esc_attr( $post_type_obj->labels->add_new_item ); ?>">
1033                                                         <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
1034                                                 </div>
1035                                         <?php endif; ?>
1036                                 <?php endif; ?>
1037                                 <ul class="available-menu-items-list" data-type="<?php echo esc_attr( $available_item_type['type'] ); ?>" data-object="<?php echo esc_attr( $available_item_type['object'] ); ?>" data-type_label="<?php echo esc_attr( isset( $available_item_type['type_label'] ) ? $available_item_type['type_label'] : $available_item_type['type'] ); ?>"></ul>
1038                         </div>
1039                 </div>
1040                 <?php
1041         }
1042
1043         /**
1044          * Print the markup for available menu item custom links.
1045          *
1046          * @since 4.7.0
1047          * @access private
1048          *
1049          * @return void
1050          */
1051         protected function print_custom_links_available_menu_item() {
1052                 ?>
1053                 <div id="new-custom-menu-item" class="accordion-section">
1054                         <h4 class="accordion-section-title" role="presentation">
1055                                 <?php _e( 'Custom Links' ); ?>
1056                                 <button type="button" class="button-link" aria-expanded="false">
1057                                         <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
1058                                         <span class="toggle-indicator" aria-hidden="true"></span>
1059                                 </button>
1060                         </h4>
1061                         <div class="accordion-section-content customlinkdiv">
1062                                 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
1063                                 <p id="menu-item-url-wrap" class="wp-clearfix">
1064                                         <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
1065                                         <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
1066                                 </p>
1067                                 <p id="menu-item-name-wrap" class="wp-clearfix">
1068                                         <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
1069                                         <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
1070                                 </p>
1071                                 <p class="button-controls">
1072                                         <span class="add-to-menu">
1073                                                 <input type="submit" class="button submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-custom-menu-item" id="custom-menu-item-submit">
1074                                                 <span class="spinner"></span>
1075                                         </span>
1076                                 </p>
1077                         </div>
1078                 </div>
1079                 <?php
1080         }
1081
1082         //
1083         // Start functionality specific to partial-refresh of menu changes in Customizer preview.
1084         //
1085
1086         /**
1087          * Nav menu args used for each instance, keyed by the args HMAC.
1088          *
1089          * @since 4.3.0
1090          * @access public
1091          * @var array
1092          */
1093         public $preview_nav_menu_instance_args = array();
1094
1095         /**
1096          * Filters arguments for dynamic nav_menu selective refresh partials.
1097          *
1098          * @since 4.5.0
1099          * @access public
1100          *
1101          * @param array|false $partial_args Partial args.
1102          * @param string      $partial_id   Partial ID.
1103          * @return array Partial args.
1104          */
1105         public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1106
1107                 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
1108                         if ( false === $partial_args ) {
1109                                 $partial_args = array();
1110                         }
1111                         $partial_args = array_merge(
1112                                 $partial_args,
1113                                 array(
1114                                         'type'                => 'nav_menu_instance',
1115                                         'render_callback'     => array( $this, 'render_nav_menu_partial' ),
1116                                         'container_inclusive' => true,
1117                                         'settings'            => array(), // Empty because the nav menu instance may relate to a menu or a location.
1118                                         'capability'          => 'edit_theme_options',
1119                                 )
1120                         );
1121                 }
1122
1123                 return $partial_args;
1124         }
1125
1126         /**
1127          * Add hooks for the Customizer preview.
1128          *
1129          * @since 4.3.0
1130          * @access public
1131          */
1132         public function customize_preview_init() {
1133                 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
1134                 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
1135                 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
1136                 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
1137                 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
1138         }
1139
1140         /**
1141          * Make the auto-draft status protected so that it can be queried.
1142          *
1143          * @since 4.7.0
1144          * @access public
1145          */
1146         public function make_auto_draft_status_previewable() {
1147                 global $wp_post_statuses;
1148                 $wp_post_statuses['auto-draft']->protected = true;
1149         }
1150
1151         /**
1152          * Sanitize post IDs for auto-draft posts created for nav menu items to be published.
1153          *
1154          * @since 4.7.0
1155          * @access public
1156          *
1157          * @param array $value Post IDs.
1158          * @returns array Post IDs.
1159          */
1160         public function sanitize_nav_menus_created_posts( $value ) {
1161                 $post_ids = array();
1162                 foreach ( wp_parse_id_list( $value ) as $post_id ) {
1163                         if ( empty( $post_id ) ) {
1164                                 continue;
1165                         }
1166                         $post = get_post( $post_id );
1167                         if ( 'auto-draft' !== $post->post_status ) {
1168                                 continue;
1169                         }
1170                         $post_type_obj = get_post_type_object( $post->post_type );
1171                         if ( ! $post_type_obj ) {
1172                                 continue;
1173                         }
1174                         if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( $post_type_obj->cap->edit_post, $post_id ) ) {
1175                                 continue;
1176                         }
1177                         $post_ids[] = $post->ID;
1178                 }
1179                 return $post_ids;
1180         }
1181
1182         /**
1183          * Publish the auto-draft posts that were created for nav menu items.
1184          *
1185          * The post IDs will have been sanitized by already by
1186          * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to
1187          * remove any post IDs for which the user cannot publish or for which the
1188          * post is not an auto-draft.
1189          *
1190          * @since 4.7.0
1191          * @access public
1192          *
1193          * @param WP_Customize_Setting $setting Customizer setting object.
1194          */
1195         public function save_nav_menus_created_posts( $setting ) {
1196                 $post_ids = $setting->post_value();
1197                 if ( ! empty( $post_ids ) ) {
1198                         foreach ( $post_ids as $post_id ) {
1199                                 $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
1200                                 $args = array(
1201                                         'ID' => $post_id,
1202                                         'post_status' => $target_status,
1203                                 );
1204                                 $post_name = get_post_meta( $post_id, '_customize_draft_post_name', true );
1205                                 if ( $post_name ) {
1206                                         $args['post_name'] = $post_name;
1207                                 }
1208
1209                                 // Note that wp_publish_post() cannot be used because unique slugs need to be assigned.
1210                                 wp_update_post( wp_slash( $args ) );
1211
1212                                 delete_post_meta( $post_id, '_customize_draft_post_name' );
1213                         }
1214                 }
1215         }
1216
1217         /**
1218          * Keep track of the arguments that are being passed to wp_nav_menu().
1219          *
1220          * @since 4.3.0
1221          * @access public
1222          * @see wp_nav_menu()
1223          * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
1224          *
1225          * @param array $args An array containing wp_nav_menu() arguments.
1226          * @return array Arguments.
1227          */
1228         public function filter_wp_nav_menu_args( $args ) {
1229                 /*
1230                  * The following conditions determine whether or not this instance of
1231                  * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
1232                  * selective refreshed if...
1233                  */
1234                 $can_partial_refresh = (
1235                         // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
1236                         ! empty( $args['echo'] )
1237                         &&
1238                         // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
1239                         ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
1240                         &&
1241                         // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
1242                         ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
1243                         // ...and if it has a theme location assigned or an assigned menu to display,
1244                         && (
1245                                 ! empty( $args['theme_location'] )
1246                                 ||
1247                                 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
1248                         )
1249                         &&
1250                         // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
1251                         (
1252                                 ! empty( $args['container'] )
1253                                 ||
1254                                 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
1255                         )
1256                 );
1257                 $args['can_partial_refresh'] = $can_partial_refresh;
1258
1259                 $exported_args = $args;
1260
1261                 // Empty out args which may not be JSON-serializable.
1262                 if ( ! $can_partial_refresh ) {
1263                         $exported_args['fallback_cb'] = '';
1264                         $exported_args['walker'] = '';
1265                 }
1266
1267                 /*
1268                  * Replace object menu arg with a term_id menu arg, as this exports better
1269                  * to JS and is easier to compare hashes.
1270                  */
1271                 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
1272                         $exported_args['menu'] = $exported_args['menu']->term_id;
1273                 }
1274
1275                 ksort( $exported_args );
1276                 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
1277
1278                 $args['customize_preview_nav_menus_args'] = $exported_args;
1279                 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
1280                 return $args;
1281         }
1282
1283         /**
1284          * Prepares wp_nav_menu() calls for partial refresh.
1285          *
1286          * Injects attributes into container element.
1287          *
1288          * @since 4.3.0
1289          * @access public
1290          *
1291          * @see wp_nav_menu()
1292          *
1293          * @param string $nav_menu_content The HTML content for the navigation menu.
1294          * @param object $args             An object containing wp_nav_menu() arguments.
1295          * @return null
1296          */
1297         public function filter_wp_nav_menu( $nav_menu_content, $args ) {
1298                 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
1299                         $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
1300                         $attributes .= ' data-customize-partial-type="nav_menu_instance"';
1301                         $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
1302                         $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
1303                 }
1304                 return $nav_menu_content;
1305         }
1306
1307         /**
1308          * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
1309          * submitted in the Ajax request.
1310          *
1311          * Note that the array is expected to be pre-sorted.
1312          *
1313          * @since 4.3.0
1314          * @access public
1315          *
1316          * @param array $args The arguments to hash.
1317          * @return string Hashed nav menu arguments.
1318          */
1319         public function hash_nav_menu_args( $args ) {
1320                 return wp_hash( serialize( $args ) );
1321         }
1322
1323         /**
1324          * Enqueue scripts for the Customizer preview.
1325          *
1326          * @since 4.3.0
1327          * @access public
1328          */
1329         public function customize_preview_enqueue_deps() {
1330                 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
1331                 wp_enqueue_style( 'customize-preview' );
1332         }
1333
1334         /**
1335          * Exports data from PHP to JS.
1336          *
1337          * @since 4.3.0
1338          * @access public
1339          */
1340         public function export_preview_data() {
1341
1342                 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1343                 $exports = array(
1344                         'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1345                 );
1346                 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1347         }
1348
1349         /**
1350          * Export any wp_nav_menu() calls during the rendering of any partials.
1351          *
1352          * @since 4.5.0
1353          * @access public
1354          *
1355          * @param array $response Response.
1356          * @return array Response.
1357          */
1358         public function export_partial_rendered_nav_menu_instances( $response ) {
1359                 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1360                 return $response;
1361         }
1362
1363         /**
1364          * Render a specific menu via wp_nav_menu() using the supplied arguments.
1365          *
1366          * @since 4.3.0
1367          * @access public
1368          *
1369          * @see wp_nav_menu()
1370          *
1371          * @param WP_Customize_Partial $partial       Partial.
1372          * @param array                $nav_menu_args Nav menu args supplied as container context.
1373          * @return string|false
1374          */
1375         public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1376                 unset( $partial );
1377
1378                 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1379                         // Error: missing_args_hmac.
1380                         return false;
1381                 }
1382
1383                 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1384                 unset( $nav_menu_args['args_hmac'] );
1385
1386                 ksort( $nav_menu_args );
1387                 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1388                         // Error: args_hmac_mismatch.
1389                         return false;
1390                 }
1391
1392                 ob_start();
1393                 wp_nav_menu( $nav_menu_args );
1394                 $content = ob_get_clean();
1395
1396                 return $content;
1397         }
1398 }