class-wp-customize-nav-menu-setting.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. <?php
  2. /**
  3. * Customize API: WP_Customize_Nav_Menu_Setting class
  4. *
  5. * @package WordPress
  6. * @subpackage Customize
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Customize Setting to represent a nav_menu.
  11. *
  12. * Subclass of WP_Customize_Setting to represent a nav_menu taxonomy term, and
  13. * the IDs for the nav_menu_items associated with the nav menu.
  14. *
  15. * @since 4.3.0
  16. *
  17. * @see wp_get_nav_menu_object()
  18. * @see WP_Customize_Setting
  19. */
  20. class WP_Customize_Nav_Menu_Setting extends WP_Customize_Setting {
  21. const ID_PATTERN = '/^nav_menu\[(?P<id>-?\d+)\]$/';
  22. const TAXONOMY = 'nav_menu';
  23. const TYPE = 'nav_menu';
  24. /**
  25. * Setting type.
  26. *
  27. * @since 4.3.0
  28. * @var string
  29. */
  30. public $type = self::TYPE;
  31. /**
  32. * Default setting value.
  33. *
  34. * @since 4.3.0
  35. * @var array
  36. *
  37. * @see wp_get_nav_menu_object()
  38. */
  39. public $default = array(
  40. 'name' => '',
  41. 'description' => '',
  42. 'parent' => 0,
  43. 'auto_add' => false,
  44. );
  45. /**
  46. * Default transport.
  47. *
  48. * @since 4.3.0
  49. * @var string
  50. */
  51. public $transport = 'postMessage';
  52. /**
  53. * The term ID represented by this setting instance.
  54. *
  55. * A negative value represents a placeholder ID for a new menu not yet saved.
  56. *
  57. * @since 4.3.0
  58. * @var int
  59. */
  60. public $term_id;
  61. /**
  62. * Previous (placeholder) term ID used before creating a new menu.
  63. *
  64. * This value will be exported to JS via the {@see 'customize_save_response'} filter
  65. * so that JavaScript can update the settings to refer to the newly-assigned
  66. * term ID. This value is always negative to indicate it does not refer to
  67. * a real term.
  68. *
  69. * @since 4.3.0
  70. * @var int
  71. *
  72. * @see WP_Customize_Nav_Menu_Setting::update()
  73. * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
  74. */
  75. public $previous_term_id;
  76. /**
  77. * Whether or not update() was called.
  78. *
  79. * @since 4.3.0
  80. * @var bool
  81. */
  82. protected $is_updated = false;
  83. /**
  84. * Status for calling the update method, used in customize_save_response filter.
  85. *
  86. * See {@see 'customize_save_response'}.
  87. *
  88. * When status is inserted, the placeholder term ID is stored in `$previous_term_id`.
  89. * When status is error, the error is stored in `$update_error`.
  90. *
  91. * @since 4.3.0
  92. * @var string updated|inserted|deleted|error
  93. *
  94. * @see WP_Customize_Nav_Menu_Setting::update()
  95. * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
  96. */
  97. public $update_status;
  98. /**
  99. * Any error object returned by wp_update_nav_menu_object() when setting is updated.
  100. *
  101. * @since 4.3.0
  102. * @var WP_Error
  103. *
  104. * @see WP_Customize_Nav_Menu_Setting::update()
  105. * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
  106. */
  107. public $update_error;
  108. /**
  109. * Constructor.
  110. *
  111. * Any supplied $args override class property defaults.
  112. *
  113. * @since 4.3.0
  114. *
  115. * @throws Exception If $id is not valid for this setting type.
  116. *
  117. * @param WP_Customize_Manager $manager Customizer bootstrap instance.
  118. * @param string $id A specific ID of the setting.
  119. * Can be a theme mod or option name.
  120. * @param array $args Optional. Setting arguments.
  121. */
  122. public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
  123. if ( empty( $manager->nav_menus ) ) {
  124. throw new Exception( 'Expected WP_Customize_Manager::$nav_menus to be set.' );
  125. }
  126. if ( ! preg_match( self::ID_PATTERN, $id, $matches ) ) {
  127. throw new Exception( "Illegal widget setting ID: $id" );
  128. }
  129. $this->term_id = (int) $matches['id'];
  130. parent::__construct( $manager, $id, $args );
  131. }
  132. /**
  133. * Get the instance data for a given widget setting.
  134. *
  135. * @since 4.3.0
  136. *
  137. * @see wp_get_nav_menu_object()
  138. *
  139. * @return array Instance data.
  140. */
  141. public function value() {
  142. if ( $this->is_previewed && get_current_blog_id() === $this->_previewed_blog_id ) {
  143. $undefined = new stdClass(); // Symbol.
  144. $post_value = $this->post_value( $undefined );
  145. if ( $undefined === $post_value ) {
  146. $value = $this->_original_value;
  147. } else {
  148. $value = $post_value;
  149. }
  150. } else {
  151. $value = false;
  152. // Note that a term_id of less than one indicates a nav_menu not yet inserted.
  153. if ( $this->term_id > 0 ) {
  154. $term = wp_get_nav_menu_object( $this->term_id );
  155. if ( $term ) {
  156. $value = wp_array_slice_assoc( (array) $term, array_keys( $this->default ) );
  157. $nav_menu_options = (array) get_option( 'nav_menu_options', array() );
  158. $value['auto_add'] = false;
  159. if ( isset( $nav_menu_options['auto_add'] ) && is_array( $nav_menu_options['auto_add'] ) ) {
  160. $value['auto_add'] = in_array( $term->term_id, $nav_menu_options['auto_add'], true );
  161. }
  162. }
  163. }
  164. if ( ! is_array( $value ) ) {
  165. $value = $this->default;
  166. }
  167. }
  168. return $value;
  169. }
  170. /**
  171. * Handle previewing the setting.
  172. *
  173. * @since 4.3.0
  174. * @since 4.4.0 Added boolean return value
  175. *
  176. * @see WP_Customize_Manager::post_value()
  177. *
  178. * @return bool False if method short-circuited due to no-op.
  179. */
  180. public function preview() {
  181. if ( $this->is_previewed ) {
  182. return false;
  183. }
  184. $undefined = new stdClass();
  185. $is_placeholder = ( $this->term_id < 0 );
  186. $is_dirty = ( $undefined !== $this->post_value( $undefined ) );
  187. if ( ! $is_placeholder && ! $is_dirty ) {
  188. return false;
  189. }
  190. $this->is_previewed = true;
  191. $this->_original_value = $this->value();
  192. $this->_previewed_blog_id = get_current_blog_id();
  193. add_filter( 'wp_get_nav_menus', array( $this, 'filter_wp_get_nav_menus' ), 10, 2 );
  194. add_filter( 'wp_get_nav_menu_object', array( $this, 'filter_wp_get_nav_menu_object' ), 10, 2 );
  195. add_filter( 'default_option_nav_menu_options', array( $this, 'filter_nav_menu_options' ) );
  196. add_filter( 'option_nav_menu_options', array( $this, 'filter_nav_menu_options' ) );
  197. return true;
  198. }
  199. /**
  200. * Filters the wp_get_nav_menus() result to ensure the inserted menu object is included, and the deleted one is removed.
  201. *
  202. * @since 4.3.0
  203. *
  204. * @see wp_get_nav_menus()
  205. *
  206. * @param WP_Term[] $menus An array of menu objects.
  207. * @param array $args An array of arguments used to retrieve menu objects.
  208. * @return WP_Term[] Array of menu objects.
  209. */
  210. public function filter_wp_get_nav_menus( $menus, $args ) {
  211. if ( get_current_blog_id() !== $this->_previewed_blog_id ) {
  212. return $menus;
  213. }
  214. $setting_value = $this->value();
  215. $is_delete = ( false === $setting_value );
  216. $index = -1;
  217. // Find the existing menu item's position in the list.
  218. foreach ( $menus as $i => $menu ) {
  219. if ( (int) $this->term_id === (int) $menu->term_id || (int) $this->previous_term_id === (int) $menu->term_id ) {
  220. $index = $i;
  221. break;
  222. }
  223. }
  224. if ( $is_delete ) {
  225. // Handle deleted menu by removing it from the list.
  226. if ( -1 !== $index ) {
  227. array_splice( $menus, $index, 1 );
  228. }
  229. } else {
  230. // Handle menus being updated or inserted.
  231. $menu_obj = (object) array_merge(
  232. array(
  233. 'term_id' => $this->term_id,
  234. 'term_taxonomy_id' => $this->term_id,
  235. 'slug' => sanitize_title( $setting_value['name'] ),
  236. 'count' => 0,
  237. 'term_group' => 0,
  238. 'taxonomy' => self::TAXONOMY,
  239. 'filter' => 'raw',
  240. ),
  241. $setting_value
  242. );
  243. array_splice( $menus, $index, ( -1 === $index ? 0 : 1 ), array( $menu_obj ) );
  244. }
  245. // Make sure the menu objects get re-sorted after an update/insert.
  246. if ( ! $is_delete && ! empty( $args['orderby'] ) ) {
  247. $menus = wp_list_sort(
  248. $menus,
  249. array(
  250. $args['orderby'] => 'ASC',
  251. )
  252. );
  253. }
  254. // @todo Add support for $args['hide_empty'] === true.
  255. return $menus;
  256. }
  257. /**
  258. * Temporary non-closure passing of orderby value to function.
  259. *
  260. * @since 4.3.0
  261. * @var string
  262. *
  263. * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus()
  264. * @see WP_Customize_Nav_Menu_Setting::_sort_menus_by_orderby()
  265. */
  266. protected $_current_menus_sort_orderby;
  267. /**
  268. * Sort menu objects by the class-supplied orderby property.
  269. *
  270. * This is a workaround for a lack of closures.
  271. *
  272. * @since 4.3.0
  273. * @deprecated 4.7.0 Use wp_list_sort()
  274. *
  275. * @param object $menu1
  276. * @param object $menu2
  277. * @return int
  278. *
  279. * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus()
  280. */
  281. protected function _sort_menus_by_orderby( $menu1, $menu2 ) {
  282. _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' );
  283. $key = $this->_current_menus_sort_orderby;
  284. return strcmp( $menu1->$key, $menu2->$key );
  285. }
  286. /**
  287. * Filters the wp_get_nav_menu_object() result to supply the previewed menu object.
  288. *
  289. * Requesting a nav_menu object by anything but ID is not supported.
  290. *
  291. * @since 4.3.0
  292. *
  293. * @see wp_get_nav_menu_object()
  294. *
  295. * @param object|null $menu_obj Object returned by wp_get_nav_menu_object().
  296. * @param string $menu_id ID of the nav_menu term. Requests by slug or name will be ignored.
  297. * @return object|null
  298. */
  299. public function filter_wp_get_nav_menu_object( $menu_obj, $menu_id ) {
  300. $ok = (
  301. get_current_blog_id() === $this->_previewed_blog_id
  302. &&
  303. is_int( $menu_id )
  304. &&
  305. $menu_id === $this->term_id
  306. );
  307. if ( ! $ok ) {
  308. return $menu_obj;
  309. }
  310. $setting_value = $this->value();
  311. // Handle deleted menus.
  312. if ( false === $setting_value ) {
  313. return false;
  314. }
  315. // Handle sanitization failure by preventing short-circuiting.
  316. if ( null === $setting_value ) {
  317. return $menu_obj;
  318. }
  319. $menu_obj = (object) array_merge(
  320. array(
  321. 'term_id' => $this->term_id,
  322. 'term_taxonomy_id' => $this->term_id,
  323. 'slug' => sanitize_title( $setting_value['name'] ),
  324. 'count' => 0,
  325. 'term_group' => 0,
  326. 'taxonomy' => self::TAXONOMY,
  327. 'filter' => 'raw',
  328. ),
  329. $setting_value
  330. );
  331. return $menu_obj;
  332. }
  333. /**
  334. * Filters the nav_menu_options option to include this menu's auto_add preference.
  335. *
  336. * @since 4.3.0
  337. *
  338. * @param array $nav_menu_options Nav menu options including auto_add.
  339. * @return array (Maybe) modified nav menu options.
  340. */
  341. public function filter_nav_menu_options( $nav_menu_options ) {
  342. if ( get_current_blog_id() !== $this->_previewed_blog_id ) {
  343. return $nav_menu_options;
  344. }
  345. $menu = $this->value();
  346. $nav_menu_options = $this->filter_nav_menu_options_value(
  347. $nav_menu_options,
  348. $this->term_id,
  349. false === $menu ? false : $menu['auto_add']
  350. );
  351. return $nav_menu_options;
  352. }
  353. /**
  354. * Sanitize an input.
  355. *
  356. * Note that parent::sanitize() erroneously does wp_unslash() on $value, but
  357. * we remove that in this override.
  358. *
  359. * @since 4.3.0
  360. *
  361. * @param array $value The menu value to sanitize.
  362. * @return array|false|null Null if an input isn't valid. False if it is marked for deletion.
  363. * Otherwise the sanitized value.
  364. */
  365. public function sanitize( $value ) {
  366. // Menu is marked for deletion.
  367. if ( false === $value ) {
  368. return $value;
  369. }
  370. // Invalid.
  371. if ( ! is_array( $value ) ) {
  372. return null;
  373. }
  374. $default = array(
  375. 'name' => '',
  376. 'description' => '',
  377. 'parent' => 0,
  378. 'auto_add' => false,
  379. );
  380. $value = array_merge( $default, $value );
  381. $value = wp_array_slice_assoc( $value, array_keys( $default ) );
  382. $value['name'] = trim( esc_html( $value['name'] ) ); // This sanitization code is used in wp-admin/nav-menus.php.
  383. $value['description'] = sanitize_text_field( $value['description'] );
  384. $value['parent'] = max( 0, (int) $value['parent'] );
  385. $value['auto_add'] = ! empty( $value['auto_add'] );
  386. if ( '' === $value['name'] ) {
  387. $value['name'] = _x( '(unnamed)', 'Missing menu name.' );
  388. }
  389. /** This filter is documented in wp-includes/class-wp-customize-setting.php */
  390. return apply_filters( "customize_sanitize_{$this->id}", $value, $this );
  391. }
  392. /**
  393. * Storage for data to be sent back to client in customize_save_response filter.
  394. *
  395. * See {@see 'customize_save_response'}.
  396. *
  397. * @since 4.3.0
  398. * @var array
  399. *
  400. * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
  401. */
  402. protected $_widget_nav_menu_updates = array();
  403. /**
  404. * Create/update the nav_menu term for this setting.
  405. *
  406. * Any created menus will have their assigned term IDs exported to the client
  407. * via the {@see 'customize_save_response'} filter. Likewise, any errors will be exported
  408. * to the client via the customize_save_response() filter.
  409. *
  410. * To delete a menu, the client can send false as the value.
  411. *
  412. * @since 4.3.0
  413. *
  414. * @see wp_update_nav_menu_object()
  415. *
  416. * @param array|false $value {
  417. * The value to update. Note that slug cannot be updated via wp_update_nav_menu_object().
  418. * If false, then the menu will be deleted entirely.
  419. *
  420. * @type string $name The name of the menu to save.
  421. * @type string $description The term description. Default empty string.
  422. * @type int $parent The id of the parent term. Default 0.
  423. * @type bool $auto_add Whether pages will auto_add to this menu. Default false.
  424. * }
  425. * @return null|void
  426. */
  427. protected function update( $value ) {
  428. if ( $this->is_updated ) {
  429. return;
  430. }
  431. $this->is_updated = true;
  432. $is_placeholder = ( $this->term_id < 0 );
  433. $is_delete = ( false === $value );
  434. add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) );
  435. $auto_add = null;
  436. if ( $is_delete ) {
  437. // If the current setting term is a placeholder, a delete request is a no-op.
  438. if ( $is_placeholder ) {
  439. $this->update_status = 'deleted';
  440. } else {
  441. $r = wp_delete_nav_menu( $this->term_id );
  442. if ( is_wp_error( $r ) ) {
  443. $this->update_status = 'error';
  444. $this->update_error = $r;
  445. } else {
  446. $this->update_status = 'deleted';
  447. $auto_add = false;
  448. }
  449. }
  450. } else {
  451. // Insert or update menu.
  452. $menu_data = wp_array_slice_assoc( $value, array( 'description', 'parent' ) );
  453. $menu_data['menu-name'] = $value['name'];
  454. $menu_id = $is_placeholder ? 0 : $this->term_id;
  455. $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) );
  456. $original_name = $menu_data['menu-name'];
  457. $name_conflict_suffix = 1;
  458. while ( is_wp_error( $r ) && 'menu_exists' === $r->get_error_code() ) {
  459. $name_conflict_suffix += 1;
  460. /* translators: 1: Original menu name, 2: Duplicate count. */
  461. $menu_data['menu-name'] = sprintf( __( '%1$s (%2$d)' ), $original_name, $name_conflict_suffix );
  462. $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) );
  463. }
  464. if ( is_wp_error( $r ) ) {
  465. $this->update_status = 'error';
  466. $this->update_error = $r;
  467. } else {
  468. if ( $is_placeholder ) {
  469. $this->previous_term_id = $this->term_id;
  470. $this->term_id = $r;
  471. $this->update_status = 'inserted';
  472. } else {
  473. $this->update_status = 'updated';
  474. }
  475. $auto_add = $value['auto_add'];
  476. }
  477. }
  478. if ( null !== $auto_add ) {
  479. $nav_menu_options = $this->filter_nav_menu_options_value(
  480. (array) get_option( 'nav_menu_options', array() ),
  481. $this->term_id,
  482. $auto_add
  483. );
  484. update_option( 'nav_menu_options', $nav_menu_options );
  485. }
  486. if ( 'inserted' === $this->update_status ) {
  487. // Make sure that new menus assigned to nav menu locations use their new IDs.
  488. foreach ( $this->manager->settings() as $setting ) {
  489. if ( ! preg_match( '/^nav_menu_locations\[/', $setting->id ) ) {
  490. continue;
  491. }
  492. $post_value = $setting->post_value( null );
  493. if ( ! is_null( $post_value ) && (int) $post_value === $this->previous_term_id ) {
  494. $this->manager->set_post_value( $setting->id, $this->term_id );
  495. $setting->save();
  496. }
  497. }
  498. // Make sure that any nav_menu widgets referencing the placeholder nav menu get updated and sent back to client.
  499. foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
  500. $nav_menu_widget_setting = $this->manager->get_setting( $setting_id );
  501. if ( ! $nav_menu_widget_setting || ! preg_match( '/^widget_nav_menu\[/', $nav_menu_widget_setting->id ) ) {
  502. continue;
  503. }
  504. $widget_instance = $nav_menu_widget_setting->post_value(); // Note that this calls WP_Customize_Widgets::sanitize_widget_instance().
  505. if ( empty( $widget_instance['nav_menu'] ) || (int) $widget_instance['nav_menu'] !== $this->previous_term_id ) {
  506. continue;
  507. }
  508. $widget_instance['nav_menu'] = $this->term_id;
  509. $updated_widget_instance = $this->manager->widgets->sanitize_widget_js_instance( $widget_instance );
  510. $this->manager->set_post_value( $nav_menu_widget_setting->id, $updated_widget_instance );
  511. $nav_menu_widget_setting->save();
  512. $this->_widget_nav_menu_updates[ $nav_menu_widget_setting->id ] = $updated_widget_instance;
  513. }
  514. }
  515. }
  516. /**
  517. * Updates a nav_menu_options array.
  518. *
  519. * @since 4.3.0
  520. *
  521. * @see WP_Customize_Nav_Menu_Setting::filter_nav_menu_options()
  522. * @see WP_Customize_Nav_Menu_Setting::update()
  523. *
  524. * @param array $nav_menu_options Array as returned by get_option( 'nav_menu_options' ).
  525. * @param int $menu_id The term ID for the given menu.
  526. * @param bool $auto_add Whether to auto-add or not.
  527. * @return array (Maybe) modified nav_menu_options array.
  528. */
  529. protected function filter_nav_menu_options_value( $nav_menu_options, $menu_id, $auto_add ) {
  530. $nav_menu_options = (array) $nav_menu_options;
  531. if ( ! isset( $nav_menu_options['auto_add'] ) ) {
  532. $nav_menu_options['auto_add'] = array();
  533. }
  534. $i = array_search( $menu_id, $nav_menu_options['auto_add'], true );
  535. if ( $auto_add && false === $i ) {
  536. array_push( $nav_menu_options['auto_add'], $this->term_id );
  537. } elseif ( ! $auto_add && false !== $i ) {
  538. array_splice( $nav_menu_options['auto_add'], $i, 1 );
  539. }
  540. return $nav_menu_options;
  541. }
  542. /**
  543. * Export data for the JS client.
  544. *
  545. * @since 4.3.0
  546. *
  547. * @see WP_Customize_Nav_Menu_Setting::update()
  548. *
  549. * @param array $data Additional information passed back to the 'saved' event on `wp.customize`.
  550. * @return array Export data.
  551. */
  552. public function amend_customize_save_response( $data ) {
  553. if ( ! isset( $data['nav_menu_updates'] ) ) {
  554. $data['nav_menu_updates'] = array();
  555. }
  556. if ( ! isset( $data['widget_nav_menu_updates'] ) ) {
  557. $data['widget_nav_menu_updates'] = array();
  558. }
  559. $data['nav_menu_updates'][] = array(
  560. 'term_id' => $this->term_id,
  561. 'previous_term_id' => $this->previous_term_id,
  562. 'error' => $this->update_error ? $this->update_error->get_error_code() : null,
  563. 'status' => $this->update_status,
  564. 'saved_value' => 'deleted' === $this->update_status ? null : $this->value(),
  565. );
  566. $data['widget_nav_menu_updates'] = array_merge(
  567. $data['widget_nav_menu_updates'],
  568. $this->_widget_nav_menu_updates
  569. );
  570. $this->_widget_nav_menu_updates = array();
  571. return $data;
  572. }
  573. }