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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. * @param WP_Customize_Manager $manager Bootstrap Customizer instance.
  116. * @param string $id An specific ID of the setting. Can be a
  117. * theme mod or option name.
  118. * @param array $args Optional. Setting arguments.
  119. *
  120. * @throws Exception If $id is not valid for this setting type.
  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 = intval( $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 && $this->_previewed_blog_id === get_current_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'] );
  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 array $menus An array of menu objects.
  207. * @param array $args An array of arguments used to retrieve menu objects.
  208. * @return array
  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( array(
  232. 'term_id' => $this->term_id,
  233. 'term_taxonomy_id' => $this->term_id,
  234. 'slug' => sanitize_title( $setting_value['name'] ),
  235. 'count' => 0,
  236. 'term_group' => 0,
  237. 'taxonomy' => self::TAXONOMY,
  238. 'filter' => 'raw',
  239. ), $setting_value );
  240. array_splice( $menus, $index, ( -1 === $index ? 0 : 1 ), array( $menu_obj ) );
  241. }
  242. // Make sure the menu objects get re-sorted after an update/insert.
  243. if ( ! $is_delete && ! empty( $args['orderby'] ) ) {
  244. $menus = wp_list_sort( $menus, array(
  245. $args['orderby'] => 'ASC',
  246. ) );
  247. }
  248. // @todo add support for $args['hide_empty'] === true
  249. return $menus;
  250. }
  251. /**
  252. * Temporary non-closure passing of orderby value to function.
  253. *
  254. * @since 4.3.0
  255. * @var string
  256. *
  257. * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus()
  258. * @see WP_Customize_Nav_Menu_Setting::_sort_menus_by_orderby()
  259. */
  260. protected $_current_menus_sort_orderby;
  261. /**
  262. * Sort menu objects by the class-supplied orderby property.
  263. *
  264. * This is a workaround for a lack of closures.
  265. *
  266. * @since 4.3.0
  267. * @deprecated 4.7.0 Use wp_list_sort()
  268. *
  269. * @param object $menu1
  270. * @param object $menu2
  271. * @return int
  272. *
  273. * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus()
  274. */
  275. protected function _sort_menus_by_orderby( $menu1, $menu2 ) {
  276. _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' );
  277. $key = $this->_current_menus_sort_orderby;
  278. return strcmp( $menu1->$key, $menu2->$key );
  279. }
  280. /**
  281. * Filters the wp_get_nav_menu_object() result to supply the previewed menu object.
  282. *
  283. * Requesting a nav_menu object by anything but ID is not supported.
  284. *
  285. * @since 4.3.0
  286. *
  287. * @see wp_get_nav_menu_object()
  288. *
  289. * @param object|null $menu_obj Object returned by wp_get_nav_menu_object().
  290. * @param string $menu_id ID of the nav_menu term. Requests by slug or name will be ignored.
  291. * @return object|null
  292. */
  293. public function filter_wp_get_nav_menu_object( $menu_obj, $menu_id ) {
  294. $ok = (
  295. get_current_blog_id() === $this->_previewed_blog_id
  296. &&
  297. is_int( $menu_id )
  298. &&
  299. $menu_id === $this->term_id
  300. );
  301. if ( ! $ok ) {
  302. return $menu_obj;
  303. }
  304. $setting_value = $this->value();
  305. // Handle deleted menus.
  306. if ( false === $setting_value ) {
  307. return false;
  308. }
  309. // Handle sanitization failure by preventing short-circuiting.
  310. if ( null === $setting_value ) {
  311. return $menu_obj;
  312. }
  313. $menu_obj = (object) array_merge( array(
  314. 'term_id' => $this->term_id,
  315. 'term_taxonomy_id' => $this->term_id,
  316. 'slug' => sanitize_title( $setting_value['name'] ),
  317. 'count' => 0,
  318. 'term_group' => 0,
  319. 'taxonomy' => self::TAXONOMY,
  320. 'filter' => 'raw',
  321. ), $setting_value );
  322. return $menu_obj;
  323. }
  324. /**
  325. * Filters the nav_menu_options option to include this menu's auto_add preference.
  326. *
  327. * @since 4.3.0
  328. *
  329. * @param array $nav_menu_options Nav menu options including auto_add.
  330. * @return array (Kaybe) modified nav menu options.
  331. */
  332. public function filter_nav_menu_options( $nav_menu_options ) {
  333. if ( $this->_previewed_blog_id !== get_current_blog_id() ) {
  334. return $nav_menu_options;
  335. }
  336. $menu = $this->value();
  337. $nav_menu_options = $this->filter_nav_menu_options_value(
  338. $nav_menu_options,
  339. $this->term_id,
  340. false === $menu ? false : $menu['auto_add']
  341. );
  342. return $nav_menu_options;
  343. }
  344. /**
  345. * Sanitize an input.
  346. *
  347. * Note that parent::sanitize() erroneously does wp_unslash() on $value, but
  348. * we remove that in this override.
  349. *
  350. * @since 4.3.0
  351. *
  352. * @param array $value The value to sanitize.
  353. * @return array|false|null Null if an input isn't valid. False if it is marked for deletion.
  354. * Otherwise the sanitized value.
  355. */
  356. public function sanitize( $value ) {
  357. // Menu is marked for deletion.
  358. if ( false === $value ) {
  359. return $value;
  360. }
  361. // Invalid.
  362. if ( ! is_array( $value ) ) {
  363. return null;
  364. }
  365. $default = array(
  366. 'name' => '',
  367. 'description' => '',
  368. 'parent' => 0,
  369. 'auto_add' => false,
  370. );
  371. $value = array_merge( $default, $value );
  372. $value = wp_array_slice_assoc( $value, array_keys( $default ) );
  373. $value['name'] = trim( esc_html( $value['name'] ) ); // This sanitization code is used in wp-admin/nav-menus.php.
  374. $value['description'] = sanitize_text_field( $value['description'] );
  375. $value['parent'] = max( 0, intval( $value['parent'] ) );
  376. $value['auto_add'] = ! empty( $value['auto_add'] );
  377. if ( '' === $value['name'] ) {
  378. $value['name'] = _x( '(unnamed)', 'Missing menu name.' );
  379. }
  380. /** This filter is documented in wp-includes/class-wp-customize-setting.php */
  381. return apply_filters( "customize_sanitize_{$this->id}", $value, $this );
  382. }
  383. /**
  384. * Storage for data to be sent back to client in customize_save_response filter.
  385. *
  386. * See {@see 'customize_save_response'}.
  387. *
  388. * @since 4.3.0
  389. * @var array
  390. *
  391. * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response()
  392. */
  393. protected $_widget_nav_menu_updates = array();
  394. /**
  395. * Create/update the nav_menu term for this setting.
  396. *
  397. * Any created menus will have their assigned term IDs exported to the client
  398. * via the {@see 'customize_save_response'} filter. Likewise, any errors will be exported
  399. * to the client via the customize_save_response() filter.
  400. *
  401. * To delete a menu, the client can send false as the value.
  402. *
  403. * @since 4.3.0
  404. *
  405. * @see wp_update_nav_menu_object()
  406. *
  407. * @param array|false $value {
  408. * The value to update. Note that slug cannot be updated via wp_update_nav_menu_object().
  409. * If false, then the menu will be deleted entirely.
  410. *
  411. * @type string $name The name of the menu to save.
  412. * @type string $description The term description. Default empty string.
  413. * @type int $parent The id of the parent term. Default 0.
  414. * @type bool $auto_add Whether pages will auto_add to this menu. Default false.
  415. * }
  416. * @return null|void
  417. */
  418. protected function update( $value ) {
  419. if ( $this->is_updated ) {
  420. return;
  421. }
  422. $this->is_updated = true;
  423. $is_placeholder = ( $this->term_id < 0 );
  424. $is_delete = ( false === $value );
  425. add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) );
  426. $auto_add = null;
  427. if ( $is_delete ) {
  428. // If the current setting term is a placeholder, a delete request is a no-op.
  429. if ( $is_placeholder ) {
  430. $this->update_status = 'deleted';
  431. } else {
  432. $r = wp_delete_nav_menu( $this->term_id );
  433. if ( is_wp_error( $r ) ) {
  434. $this->update_status = 'error';
  435. $this->update_error = $r;
  436. } else {
  437. $this->update_status = 'deleted';
  438. $auto_add = false;
  439. }
  440. }
  441. } else {
  442. // Insert or update menu.
  443. $menu_data = wp_array_slice_assoc( $value, array( 'description', 'parent' ) );
  444. $menu_data['menu-name'] = $value['name'];
  445. $menu_id = $is_placeholder ? 0 : $this->term_id;
  446. $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) );
  447. $original_name = $menu_data['menu-name'];
  448. $name_conflict_suffix = 1;
  449. while ( is_wp_error( $r ) && 'menu_exists' === $r->get_error_code() ) {
  450. $name_conflict_suffix += 1;
  451. /* translators: 1: original menu name, 2: duplicate count */
  452. $menu_data['menu-name'] = sprintf( __( '%1$s (%2$d)' ), $original_name, $name_conflict_suffix );
  453. $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) );
  454. }
  455. if ( is_wp_error( $r ) ) {
  456. $this->update_status = 'error';
  457. $this->update_error = $r;
  458. } else {
  459. if ( $is_placeholder ) {
  460. $this->previous_term_id = $this->term_id;
  461. $this->term_id = $r;
  462. $this->update_status = 'inserted';
  463. } else {
  464. $this->update_status = 'updated';
  465. }
  466. $auto_add = $value['auto_add'];
  467. }
  468. }
  469. if ( null !== $auto_add ) {
  470. $nav_menu_options = $this->filter_nav_menu_options_value(
  471. (array) get_option( 'nav_menu_options', array() ),
  472. $this->term_id,
  473. $auto_add
  474. );
  475. update_option( 'nav_menu_options', $nav_menu_options );
  476. }
  477. if ( 'inserted' === $this->update_status ) {
  478. // Make sure that new menus assigned to nav menu locations use their new IDs.
  479. foreach ( $this->manager->settings() as $setting ) {
  480. if ( ! preg_match( '/^nav_menu_locations\[/', $setting->id ) ) {
  481. continue;
  482. }
  483. $post_value = $setting->post_value( null );
  484. if ( ! is_null( $post_value ) && $this->previous_term_id === intval( $post_value ) ) {
  485. $this->manager->set_post_value( $setting->id, $this->term_id );
  486. $setting->save();
  487. }
  488. }
  489. // Make sure that any nav_menu widgets referencing the placeholder nav menu get updated and sent back to client.
  490. foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
  491. $nav_menu_widget_setting = $this->manager->get_setting( $setting_id );
  492. if ( ! $nav_menu_widget_setting || ! preg_match( '/^widget_nav_menu\[/', $nav_menu_widget_setting->id ) ) {
  493. continue;
  494. }
  495. $widget_instance = $nav_menu_widget_setting->post_value(); // Note that this calls WP_Customize_Widgets::sanitize_widget_instance().
  496. if ( empty( $widget_instance['nav_menu'] ) || intval( $widget_instance['nav_menu'] ) !== $this->previous_term_id ) {
  497. continue;
  498. }
  499. $widget_instance['nav_menu'] = $this->term_id;
  500. $updated_widget_instance = $this->manager->widgets->sanitize_widget_js_instance( $widget_instance );
  501. $this->manager->set_post_value( $nav_menu_widget_setting->id, $updated_widget_instance );
  502. $nav_menu_widget_setting->save();
  503. $this->_widget_nav_menu_updates[ $nav_menu_widget_setting->id ] = $updated_widget_instance;
  504. }
  505. }
  506. }
  507. /**
  508. * Updates a nav_menu_options array.
  509. *
  510. * @since 4.3.0
  511. *
  512. * @see WP_Customize_Nav_Menu_Setting::filter_nav_menu_options()
  513. * @see WP_Customize_Nav_Menu_Setting::update()
  514. *
  515. * @param array $nav_menu_options Array as returned by get_option( 'nav_menu_options' ).
  516. * @param int $menu_id The term ID for the given menu.
  517. * @param bool $auto_add Whether to auto-add or not.
  518. * @return array (Maybe) modified nav_menu_otions array.
  519. */
  520. protected function filter_nav_menu_options_value( $nav_menu_options, $menu_id, $auto_add ) {
  521. $nav_menu_options = (array) $nav_menu_options;
  522. if ( ! isset( $nav_menu_options['auto_add'] ) ) {
  523. $nav_menu_options['auto_add'] = array();
  524. }
  525. $i = array_search( $menu_id, $nav_menu_options['auto_add'] );
  526. if ( $auto_add && false === $i ) {
  527. array_push( $nav_menu_options['auto_add'], $this->term_id );
  528. } elseif ( ! $auto_add && false !== $i ) {
  529. array_splice( $nav_menu_options['auto_add'], $i, 1 );
  530. }
  531. return $nav_menu_options;
  532. }
  533. /**
  534. * Export data for the JS client.
  535. *
  536. * @since 4.3.0
  537. *
  538. * @see WP_Customize_Nav_Menu_Setting::update()
  539. *
  540. * @param array $data Additional information passed back to the 'saved' event on `wp.customize`.
  541. * @return array Export data.
  542. */
  543. public function amend_customize_save_response( $data ) {
  544. if ( ! isset( $data['nav_menu_updates'] ) ) {
  545. $data['nav_menu_updates'] = array();
  546. }
  547. if ( ! isset( $data['widget_nav_menu_updates'] ) ) {
  548. $data['widget_nav_menu_updates'] = array();
  549. }
  550. $data['nav_menu_updates'][] = array(
  551. 'term_id' => $this->term_id,
  552. 'previous_term_id' => $this->previous_term_id,
  553. 'error' => $this->update_error ? $this->update_error->get_error_code() : null,
  554. 'status' => $this->update_status,
  555. 'saved_value' => 'deleted' === $this->update_status ? null : $this->value(),
  556. );
  557. $data['widget_nav_menu_updates'] = array_merge(
  558. $data['widget_nav_menu_updates'],
  559. $this->_widget_nav_menu_updates
  560. );
  561. $this->_widget_nav_menu_updates = array();
  562. return $data;
  563. }
  564. }