[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/customize/ -> class-wp-customize-nav-menu-setting.php (source)

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7