]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-customize-nav-menus.php
WordPress 4.7.1-scripts
[autoinstalls/wordpress.git] / wp-includes / class-wp-customize-nav-menus.php
1 <?php
2 /**
3  * WordPress Customize Nav Menus classes
4  *
5  * @package WordPress
6  * @subpackage Customize
7  * @since 4.3.0
8  */
9
10 /**
11  * Customize Nav Menus class.
12  *
13  * Implements menu management in the Customizer.
14  *
15  * @since 4.3.0
16  *
17  * @see WP_Customize_Manager
18  */
19 final class WP_Customize_Nav_Menus {
20
21         /**
22          * WP_Customize_Manager instance.
23          *
24          * @since 4.3.0
25          * @access public
26          * @var WP_Customize_Manager
27          */
28         public $manager;
29
30         /**
31          * Previewed Menus.
32          *
33          * @since 4.3.0
34          * @access public
35          * @var array
36          */
37         public $previewed_menus;
38
39         /**
40          * Constructor.
41          *
42          * @since 4.3.0
43          * @access public
44          *
45          * @param object $manager An instance of the WP_Customize_Manager class.
46          */
47         public function __construct( $manager ) {
48                 $this->previewed_menus = array();
49                 $this->manager         = $manager;
50
51                 // 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                 // Preview settings for nav menus early so that the sections and controls will be added properly.
535                 $nav_menus_setting_ids = array();
536                 foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
537                         if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
538                                 $nav_menus_setting_ids[] = $setting_id;
539                         }
540                 }
541                 $this->manager->add_dynamic_settings( $nav_menus_setting_ids );
542                 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
543                         foreach ( $nav_menus_setting_ids as $setting_id ) {
544                                 $setting = $this->manager->get_setting( $setting_id );
545                                 if ( $setting ) {
546                                         $setting->preview();
547                                 }
548                         }
549                 }
550
551                 // Require JS-rendered control types.
552                 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
553                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
554                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
555                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
556                 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
557
558                 // Create a panel for Menus.
559                 $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>';
560                 if ( current_theme_supports( 'widgets' ) ) {
561                         /* translators: URL to the widgets panel of the customizer */
562                         $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>';
563                 } else {
564                         $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
565                 }
566                 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
567                         'title'       => __( 'Menus' ),
568                         'description' => $description,
569                         'priority'    => 100,
570                         // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
571                 ) ) );
572                 $menus = wp_get_nav_menus();
573
574                 // Menu locations.
575                 $locations     = get_registered_nav_menus();
576                 $num_locations = count( array_keys( $locations ) );
577                 if ( 1 == $num_locations ) {
578                         $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' ) . '</p>';
579                 } else {
580                         /* translators: %s: number of menu locations */
581                         $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>';
582                 }
583                 if ( current_theme_supports( 'widgets' ) ) {
584                         /* translators: URL to the widgets panel of the customizer */
585                         $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>';
586                 }
587
588                 $this->manager->add_section( 'menu_locations', array(
589                         'title'       => __( 'Menu Locations' ),
590                         'panel'       => 'nav_menus',
591                         'priority'    => 5,
592                         'description' => $description,
593                 ) );
594
595                 $choices = array( '0' => __( '&mdash; Select &mdash;' ) );
596                 foreach ( $menus as $menu ) {
597                         $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '&hellip;' );
598                 }
599
600                 foreach ( $locations as $location => $description ) {
601                         $setting_id = "nav_menu_locations[{$location}]";
602
603                         $setting = $this->manager->get_setting( $setting_id );
604                         if ( $setting ) {
605                                 $setting->transport = 'postMessage';
606                                 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
607                                 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
608                         } else {
609                                 $this->manager->add_setting( $setting_id, array(
610                                         'sanitize_callback' => array( $this, 'intval_base10' ),
611                                         'theme_supports'    => 'menus',
612                                         'type'              => 'theme_mod',
613                                         'transport'         => 'postMessage',
614                                         'default'           => 0,
615                                 ) );
616                         }
617
618                         $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
619                                 'label'       => $description,
620                                 'location_id' => $location,
621                                 'section'     => 'menu_locations',
622                                 'choices'     => $choices,
623                         ) ) );
624                 }
625
626                 // Register each menu as a Customizer section, and add each menu item to each menu.
627                 foreach ( $menus as $menu ) {
628                         $menu_id = $menu->term_id;
629
630                         // Create a section for each menu.
631                         $section_id = 'nav_menu[' . $menu_id . ']';
632                         $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
633                                 'title'     => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
634                                 'priority'  => 10,
635                                 'panel'     => 'nav_menus',
636                         ) ) );
637
638                         $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
639                         $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
640                                 'transport' => 'postMessage',
641                         ) ) );
642
643                         // Add the menu contents.
644                         $menu_items = (array) wp_get_nav_menu_items( $menu_id );
645
646                         foreach ( array_values( $menu_items ) as $i => $item ) {
647
648                                 // Create a setting for each menu item (which doesn't actually manage data, currently).
649                                 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
650
651                                 $value = (array) $item;
652                                 if ( empty( $value['post_title'] ) ) {
653                                         $value['title'] = '';
654                                 }
655
656                                 $value['nav_menu_term_id'] = $menu_id;
657                                 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
658                                         'value'     => $value,
659                                         'transport' => 'postMessage',
660                                 ) ) );
661
662                                 // Create a control for each menu item.
663                                 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
664                                         'label'    => $item->title,
665                                         'section'  => $section_id,
666                                         'priority' => 10 + $i,
667                                 ) ) );
668                         }
669
670                         // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
671                 }
672
673                 // Add the add-new-menu section and controls.
674                 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
675                         'title'    => __( 'Add a Menu' ),
676                         'panel'    => 'nav_menus',
677                         'priority' => 999,
678                 ) ) );
679
680                 $this->manager->add_control( 'new_menu_name', array(
681                         'label'       => '',
682                         'section'     => 'add_menu',
683                         'type'        => 'text',
684                         'settings'    => array(),
685                         'input_attrs' => array(
686                                 'class'       => 'menu-name-field',
687                                 'placeholder' => __( 'New menu name' ),
688                         ),
689                 ) );
690
691                 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
692                         'section'  => 'add_menu',
693                         'settings' => array(),
694                 ) ) );
695
696                 $this->manager->add_setting( new WP_Customize_Filter_Setting( $this->manager, 'nav_menus_created_posts', array(
697                         'transport' => 'postMessage',
698                         'type' => 'option', // To prevent theme prefix in changeset.
699                         'default' => array(),
700                         'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
701                 ) ) );
702         }
703
704         /**
705          * Get the base10 intval.
706          *
707          * This is used as a setting's sanitize_callback; we can't use just plain
708          * intval because the second argument is not what intval() expects.
709          *
710          * @since 4.3.0
711          * @access public
712          *
713          * @param mixed $value Number to convert.
714          * @return int Integer.
715          */
716         public function intval_base10( $value ) {
717                 return intval( $value, 10 );
718         }
719
720         /**
721          * Return an array of all the available item types.
722          *
723          * @since 4.3.0
724          * @since 4.7.0  Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
725          * @access public
726          *
727          * @return array The available menu item types.
728          */
729         public function available_item_types() {
730                 $item_types = array();
731
732                 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
733                 if ( $post_types ) {
734                         foreach ( $post_types as $slug => $post_type ) {
735                                 $item_types[] = array(
736                                         'title'  => $post_type->labels->name,
737                                         'type_label' => $post_type->labels->singular_name,
738                                         'type' => 'post_type',
739                                         'object' => $post_type->name,
740                                 );
741                         }
742                 }
743
744                 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
745                 if ( $taxonomies ) {
746                         foreach ( $taxonomies as $slug => $taxonomy ) {
747                                 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
748                                         continue;
749                                 }
750                                 $item_types[] = array(
751                                         'title' => $taxonomy->labels->name,
752                                         'type_label' => $taxonomy->labels->singular_name,
753                                         'type' => 'taxonomy',
754                                         'object' => $taxonomy->name,
755                                 );
756                         }
757                 }
758
759                 /**
760                  * Filters the available menu item types.
761                  *
762                  * @since 4.3.0
763                  * @since 4.7.0  Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
764                  *
765                  * @param array $item_types Custom menu item types.
766                  */
767                 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
768
769                 return $item_types;
770         }
771
772         /**
773          * Add a new `auto-draft` post.
774          *
775          * @access public
776          * @since 4.7.0
777          *
778          * @param array $postarr {
779          *     Post array. Note that post_status is overridden to be `auto-draft`.
780          *
781          *     @var string $post_title   Post title. Required.
782          *     @var string $post_type    Post type. Required.
783          *     @var string $post_name    Post name.
784          *     @var string $post_content Post content.
785          * }
786          * @return WP_Post|WP_Error Inserted auto-draft post object or error.
787          */
788         public function insert_auto_draft_post( $postarr ) {
789                 if ( ! isset( $postarr['post_type'] ) || ! post_type_exists( $postarr['post_type'] )  ) {
790                         return new WP_Error( 'unknown_post_type', __( 'Unknown post type' ) );
791                 }
792                 if ( empty( $postarr['post_title'] ) ) {
793                         return new WP_Error( 'empty_title', __( 'Empty title' ) );
794                 }
795                 if ( ! empty( $postarr['post_status'] ) ) {
796                         return new WP_Error( 'status_forbidden', __( 'Status is forbidden' ) );
797                 }
798
799                 $postarr['post_status'] = 'auto-draft';
800
801                 // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set.
802                 if ( empty( $postarr['post_name'] ) ) {
803                         $postarr['post_name'] = sanitize_title( $postarr['post_title'] );
804                 }
805                 if ( ! isset( $postarr['meta_input'] ) ) {
806                         $postarr['meta_input'] = array();
807                 }
808                 $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
809                 unset( $postarr['post_name'] );
810
811                 add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
812                 $r = wp_insert_post( wp_slash( $postarr ), true );
813                 remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
814
815                 if ( is_wp_error( $r ) ) {
816                         return $r;
817                 } else {
818                         return get_post( $r );
819                 }
820         }
821
822         /**
823          * Ajax handler for adding a new auto-draft post.
824          *
825          * @access public
826          * @since 4.7.0
827          */
828         public function ajax_insert_auto_draft_post() {
829                 if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) {
830                         wp_send_json_error( 'bad_nonce', 400 );
831                 }
832
833                 if ( ! current_user_can( 'customize' ) ) {
834                         wp_send_json_error( 'customize_not_allowed', 403 );
835                 }
836
837                 if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
838                         wp_send_json_error( 'missing_params', 400 );
839                 }
840
841                 $params = wp_unslash( $_POST['params'] );
842                 $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
843                 if ( ! empty( $illegal_params ) ) {
844                         wp_send_json_error( 'illegal_params', 400 );
845                 }
846
847                 $params = array_merge(
848                         array(
849                                 'post_type' => '',
850                                 'post_title' => '',
851                         ),
852                         $params
853                 );
854
855                 if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) {
856                         status_header( 400 );
857                         wp_send_json_error( 'missing_post_type_param' );
858                 }
859
860                 $post_type_object = get_post_type_object( $params['post_type'] );
861                 if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
862                         status_header( 403 );
863                         wp_send_json_error( 'insufficient_post_permissions' );
864                 }
865
866                 $params['post_title'] = trim( $params['post_title'] );
867                 if ( '' === $params['post_title'] ) {
868                         status_header( 400 );
869                         wp_send_json_error( 'missing_post_title' );
870                 }
871
872                 $r = $this->insert_auto_draft_post( $params );
873                 if ( is_wp_error( $r ) ) {
874                         $error = $r;
875                         if ( ! empty( $post_type_object->labels->singular_name ) ) {
876                                 $singular_name = $post_type_object->labels->singular_name;
877                         } else {
878                                 $singular_name = __( 'Post' );
879                         }
880
881                         $data = array(
882                                 /* translators: %1$s is the post type name and %2$s is the error message. */
883                                 'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
884                         );
885                         wp_send_json_error( $data );
886                 } else {
887                         $post = $r;
888                         $data = array(
889                                 'post_id' => $post->ID,
890                                 'url'     => get_permalink( $post->ID ),
891                         );
892                         wp_send_json_success( $data );
893                 }
894         }
895
896         /**
897          * Print the JavaScript templates used to render Menu Customizer components.
898          *
899          * Templates are imported into the JS use wp.template.
900          *
901          * @since 4.3.0
902          * @access public
903          */
904         public function print_templates() {
905                 ?>
906                 <script type="text/html" id="tmpl-available-menu-item">
907                         <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
908                                 <div class="menu-item-bar">
909                                         <div class="menu-item-handle">
910                                                 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
911                                                 <span class="item-title" aria-hidden="true">
912                                                         <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
913                                                 </span>
914                                                 <button type="button" class="button-link item-add">
915                                                         <span class="screen-reader-text"><?php
916                                                                 /* translators: 1: Title of a menu item, 2: Type of a menu item */
917                                                                 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
918                                                         ?></span>
919                                                 </button>
920                                         </div>
921                                 </div>
922                         </li>
923                 </script>
924
925                 <script type="text/html" id="tmpl-menu-item-reorder-nav">
926                         <div class="menu-item-reorder-nav">
927                                 <?php
928                                 printf(
929                                         '<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>',
930                                         __( 'Move up' ),
931                                         __( 'Move down' ),
932                                         __( 'Move one level up' ),
933                                         __( 'Move one level down' )
934                                 );
935                                 ?>
936                         </div>
937                 </script>
938         <?php
939         }
940
941         /**
942          * Print the html template used to render the add-menu-item frame.
943          *
944          * @since 4.3.0
945          * @access public
946          */
947         public function available_items_template() {
948                 ?>
949                 <div id="available-menu-items" class="accordion-container">
950                         <div class="customize-section-title">
951                                 <button type="button" class="customize-section-back" tabindex="-1">
952                                         <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
953                                 </button>
954                                 <h3>
955                                         <span class="customize-action">
956                                                 <?php
957                                                         /* translators: &#9656; is the unicode right-pointing triangle, and %s is the section title in the Customizer */
958                                                         printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
959                                                 ?>
960                                         </span>
961                                         <?php _e( 'Add Menu Items' ); ?>
962                                 </h3>
963                         </div>
964                         <div id="available-menu-items-search" class="accordion-section cannot-expand">
965                                 <div class="accordion-section-title">
966                                         <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
967                                         <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ) ?>" aria-describedby="menu-items-search-desc" />
968                                         <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
969                                         <span class="spinner"></span>
970                                 </div>
971                                 <div class="search-icon" aria-hidden="true"></div>
972                                 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
973                                 <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul>
974                         </div>
975                         <?php
976
977                         // Ensure the page post type comes first in the list.
978                         $item_types = $this->available_item_types();
979                         $page_item_type = null;
980                         foreach ( $item_types as $i => $item_type ) {
981                                 if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
982                                         $page_item_type = $item_type;
983                                         unset( $item_types[ $i ] );
984                                 }
985                         }
986
987                         $this->print_custom_links_available_menu_item();
988                         if ( $page_item_type ) {
989                                 $this->print_post_type_container( $page_item_type );
990                         }
991                         // Containers for per-post-type item browsing; items are added with JS.
992                         foreach ( $item_types as $item_type ) {
993                                 $this->print_post_type_container( $item_type );
994                         }
995                         ?>
996                 </div><!-- #available-menu-items -->
997         <?php
998         }
999
1000         /**
1001          * Print the markup for new menu items.
1002          *
1003          * To be used in the template #available-menu-items.
1004          *
1005          * @since 4.7.0
1006          * @access private
1007          *
1008          * @param array $available_item_type Menu item data to output, including title, type, and label.
1009          * @return void
1010          */
1011         protected function print_post_type_container( $available_item_type ) {
1012                 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
1013                 ?>
1014                 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
1015                         <h4 class="accordion-section-title" role="presentation">
1016                                 <?php echo esc_html( $available_item_type['title'] ); ?>
1017                                 <span class="spinner"></span>
1018                                 <span class="no-items"><?php _e( 'No items' ); ?></span>
1019                                 <button type="button" class="button-link" aria-expanded="false">
1020                                         <span class="screen-reader-text"><?php
1021                                                 /* translators: %s: Title of a section with menu items */
1022                                                 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
1023                                         <span class="toggle-indicator" aria-hidden="true"></span>
1024                                 </button>
1025                         </h4>
1026                         <div class="accordion-section-content">
1027                                 <?php if ( 'post_type' === $available_item_type['type'] ) : ?>
1028                                         <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?>
1029                                         <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?>
1030                                                 <div class="new-content-item">
1031                                                         <input type="text" class="create-item-input" placeholder="<?php echo esc_attr( $post_type_obj->labels->add_new_item ); ?>">
1032                                                         <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
1033                                                 </div>
1034                                         <?php endif; ?>
1035                                 <?php endif; ?>
1036                                 <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>
1037                         </div>
1038                 </div>
1039                 <?php
1040         }
1041
1042         /**
1043          * Print the markup for available menu item custom links.
1044          *
1045          * @since 4.7.0
1046          * @access private
1047          *
1048          * @return void
1049          */
1050         protected function print_custom_links_available_menu_item() {
1051                 ?>
1052                 <div id="new-custom-menu-item" class="accordion-section">
1053                         <h4 class="accordion-section-title" role="presentation">
1054                                 <?php _e( 'Custom Links' ); ?>
1055                                 <button type="button" class="button-link" aria-expanded="false">
1056                                         <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
1057                                         <span class="toggle-indicator" aria-hidden="true"></span>
1058                                 </button>
1059                         </h4>
1060                         <div class="accordion-section-content customlinkdiv">
1061                                 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
1062                                 <p id="menu-item-url-wrap" class="wp-clearfix">
1063                                         <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
1064                                         <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
1065                                 </p>
1066                                 <p id="menu-item-name-wrap" class="wp-clearfix">
1067                                         <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
1068                                         <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
1069                                 </p>
1070                                 <p class="button-controls">
1071                                         <span class="add-to-menu">
1072                                                 <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">
1073                                                 <span class="spinner"></span>
1074                                         </span>
1075                                 </p>
1076                         </div>
1077                 </div>
1078                 <?php
1079         }
1080
1081         //
1082         // Start functionality specific to partial-refresh of menu changes in Customizer preview.
1083         //
1084
1085         /**
1086          * Nav menu args used for each instance, keyed by the args HMAC.
1087          *
1088          * @since 4.3.0
1089          * @access public
1090          * @var array
1091          */
1092         public $preview_nav_menu_instance_args = array();
1093
1094         /**
1095          * Filters arguments for dynamic nav_menu selective refresh partials.
1096          *
1097          * @since 4.5.0
1098          * @access public
1099          *
1100          * @param array|false $partial_args Partial args.
1101          * @param string      $partial_id   Partial ID.
1102          * @return array Partial args.
1103          */
1104         public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1105
1106                 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
1107                         if ( false === $partial_args ) {
1108                                 $partial_args = array();
1109                         }
1110                         $partial_args = array_merge(
1111                                 $partial_args,
1112                                 array(
1113                                         'type'                => 'nav_menu_instance',
1114                                         'render_callback'     => array( $this, 'render_nav_menu_partial' ),
1115                                         'container_inclusive' => true,
1116                                         'settings'            => array(), // Empty because the nav menu instance may relate to a menu or a location.
1117                                         'capability'          => 'edit_theme_options',
1118                                 )
1119                         );
1120                 }
1121
1122                 return $partial_args;
1123         }
1124
1125         /**
1126          * Add hooks for the Customizer preview.
1127          *
1128          * @since 4.3.0
1129          * @access public
1130          */
1131         public function customize_preview_init() {
1132                 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
1133                 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
1134                 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
1135                 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
1136                 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
1137         }
1138
1139         /**
1140          * Make the auto-draft status protected so that it can be queried.
1141          *
1142          * @since 4.7.0
1143          * @access public
1144          */
1145         public function make_auto_draft_status_previewable() {
1146                 global $wp_post_statuses;
1147                 $wp_post_statuses['auto-draft']->protected = true;
1148         }
1149
1150         /**
1151          * Sanitize post IDs for auto-draft posts created for nav menu items to be published.
1152          *
1153          * @since 4.7.0
1154          * @access public
1155          *
1156          * @param array $value Post IDs.
1157          * @returns array Post IDs.
1158          */
1159         public function sanitize_nav_menus_created_posts( $value ) {
1160                 $post_ids = array();
1161                 foreach ( wp_parse_id_list( $value ) as $post_id ) {
1162                         if ( empty( $post_id ) ) {
1163                                 continue;
1164                         }
1165                         $post = get_post( $post_id );
1166                         if ( 'auto-draft' !== $post->post_status ) {
1167                                 continue;
1168                         }
1169                         $post_type_obj = get_post_type_object( $post->post_type );
1170                         if ( ! $post_type_obj ) {
1171                                 continue;
1172                         }
1173                         if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( $post_type_obj->cap->edit_post, $post_id ) ) {
1174                                 continue;
1175                         }
1176                         $post_ids[] = $post->ID;
1177                 }
1178                 return $post_ids;
1179         }
1180
1181         /**
1182          * Publish the auto-draft posts that were created for nav menu items.
1183          *
1184          * The post IDs will have been sanitized by already by
1185          * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to
1186          * remove any post IDs for which the user cannot publish or for which the
1187          * post is not an auto-draft.
1188          *
1189          * @since 4.7.0
1190          * @access public
1191          *
1192          * @param WP_Customize_Setting $setting Customizer setting object.
1193          */
1194         public function save_nav_menus_created_posts( $setting ) {
1195                 $post_ids = $setting->post_value();
1196                 if ( ! empty( $post_ids ) ) {
1197                         foreach ( $post_ids as $post_id ) {
1198                                 $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
1199                                 $args = array(
1200                                         'ID' => $post_id,
1201                                         'post_status' => $target_status,
1202                                 );
1203                                 $post_name = get_post_meta( $post_id, '_customize_draft_post_name', true );
1204                                 if ( $post_name ) {
1205                                         $args['post_name'] = $post_name;
1206                                 }
1207
1208                                 // Note that wp_publish_post() cannot be used because unique slugs need to be assigned.
1209                                 wp_update_post( wp_slash( $args ) );
1210
1211                                 delete_post_meta( $post_id, '_customize_draft_post_name' );
1212                         }
1213                 }
1214         }
1215
1216         /**
1217          * Keep track of the arguments that are being passed to wp_nav_menu().
1218          *
1219          * @since 4.3.0
1220          * @access public
1221          * @see wp_nav_menu()
1222          * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
1223          *
1224          * @param array $args An array containing wp_nav_menu() arguments.
1225          * @return array Arguments.
1226          */
1227         public function filter_wp_nav_menu_args( $args ) {
1228                 /*
1229                  * The following conditions determine whether or not this instance of
1230                  * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
1231                  * selective refreshed if...
1232                  */
1233                 $can_partial_refresh = (
1234                         // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
1235                         ! empty( $args['echo'] )
1236                         &&
1237                         // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
1238                         ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
1239                         &&
1240                         // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
1241                         ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
1242                         // ...and if it has a theme location assigned or an assigned menu to display,
1243                         && (
1244                                 ! empty( $args['theme_location'] )
1245                                 ||
1246                                 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
1247                         )
1248                         &&
1249                         // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
1250                         (
1251                                 ! empty( $args['container'] )
1252                                 ||
1253                                 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
1254                         )
1255                 );
1256                 $args['can_partial_refresh'] = $can_partial_refresh;
1257
1258                 $exported_args = $args;
1259
1260                 // Empty out args which may not be JSON-serializable.
1261                 if ( ! $can_partial_refresh ) {
1262                         $exported_args['fallback_cb'] = '';
1263                         $exported_args['walker'] = '';
1264                 }
1265
1266                 /*
1267                  * Replace object menu arg with a term_id menu arg, as this exports better
1268                  * to JS and is easier to compare hashes.
1269                  */
1270                 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
1271                         $exported_args['menu'] = $exported_args['menu']->term_id;
1272                 }
1273
1274                 ksort( $exported_args );
1275                 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
1276
1277                 $args['customize_preview_nav_menus_args'] = $exported_args;
1278                 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
1279                 return $args;
1280         }
1281
1282         /**
1283          * Prepares wp_nav_menu() calls for partial refresh.
1284          *
1285          * Injects attributes into container element.
1286          *
1287          * @since 4.3.0
1288          * @access public
1289          *
1290          * @see wp_nav_menu()
1291          *
1292          * @param string $nav_menu_content The HTML content for the navigation menu.
1293          * @param object $args             An object containing wp_nav_menu() arguments.
1294          * @return null
1295          */
1296         public function filter_wp_nav_menu( $nav_menu_content, $args ) {
1297                 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
1298                         $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
1299                         $attributes .= ' data-customize-partial-type="nav_menu_instance"';
1300                         $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
1301                         $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
1302                 }
1303                 return $nav_menu_content;
1304         }
1305
1306         /**
1307          * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
1308          * submitted in the Ajax request.
1309          *
1310          * Note that the array is expected to be pre-sorted.
1311          *
1312          * @since 4.3.0
1313          * @access public
1314          *
1315          * @param array $args The arguments to hash.
1316          * @return string Hashed nav menu arguments.
1317          */
1318         public function hash_nav_menu_args( $args ) {
1319                 return wp_hash( serialize( $args ) );
1320         }
1321
1322         /**
1323          * Enqueue scripts for the Customizer preview.
1324          *
1325          * @since 4.3.0
1326          * @access public
1327          */
1328         public function customize_preview_enqueue_deps() {
1329                 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
1330                 wp_enqueue_style( 'customize-preview' );
1331         }
1332
1333         /**
1334          * Exports data from PHP to JS.
1335          *
1336          * @since 4.3.0
1337          * @access public
1338          */
1339         public function export_preview_data() {
1340
1341                 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1342                 $exports = array(
1343                         'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1344                 );
1345                 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1346         }
1347
1348         /**
1349          * Export any wp_nav_menu() calls during the rendering of any partials.
1350          *
1351          * @since 4.5.0
1352          * @access public
1353          *
1354          * @param array $response Response.
1355          * @return array Response.
1356          */
1357         public function export_partial_rendered_nav_menu_instances( $response ) {
1358                 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1359                 return $response;
1360         }
1361
1362         /**
1363          * Render a specific menu via wp_nav_menu() using the supplied arguments.
1364          *
1365          * @since 4.3.0
1366          * @access public
1367          *
1368          * @see wp_nav_menu()
1369          *
1370          * @param WP_Customize_Partial $partial       Partial.
1371          * @param array                $nav_menu_args Nav menu args supplied as container context.
1372          * @return string|false
1373          */
1374         public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1375                 unset( $partial );
1376
1377                 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1378                         // Error: missing_args_hmac.
1379                         return false;
1380                 }
1381
1382                 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1383                 unset( $nav_menu_args['args_hmac'] );
1384
1385                 ksort( $nav_menu_args );
1386                 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1387                         // Error: args_hmac_mismatch.
1388                         return false;
1389                 }
1390
1391                 ob_start();
1392                 wp_nav_menu( $nav_menu_args );
1393                 $content = ob_get_clean();
1394
1395                 return $content;
1396         }
1397 }