You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

662 lines
19 KiB

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