You are here

pathauto_menu_link.module in Pathauto Menu Link 7

Same filename and directory in other branches
  1. 8 pathauto_menu_link.module

Update paths when a menu item is moved.

File

pathauto_menu_link.module
View source
<?php

/**
 * @file
 * Update paths when a menu item is moved.
 */

/**
 * Implements hook_menu_link_update().
 */
function pathauto_menu_link_menu_link_update($link) {

  // Attempt to update the path for the menu link.
  _pathauto_menu_link_update($link);
}

/**
 * Update the path for a node menu link.
 *
 * @param object $link
 *   The link.
 */
function _pathauto_menu_link_update($link) {
  $exploded = explode('/', $link['link_path']);
  if ($exploded) {

    // Only affect nodes.
    if ($exploded[0] == 'node' && isset($exploded[1]) && is_numeric($exploded[1])) {

      // Get the node ID and load the node object.
      $nid = $exploded[1];
      if (!is_numeric($nid)) {
        return;
      }
      $node = node_load($nid, NULL, TRUE);
      if (is_bool($node)) {
        return;
      }

      // @todo: Check that the path has changed before updating the node.
      // Update the alias.
      pathauto_node_update_alias($node, 'update');

      // Update any child menu links.
      _pathauto_menu_link_update_children($link);
    }
  }
}

/**
 * Search for and update any child menu links.
 *
 * @param object $link
 *   The link.
 */
function _pathauto_menu_link_update_children($link) {
  if (_pathauto_menu_link_has_children($link)) {

    // Find the child menu items.
    $children = menu_build_tree($link['menu_name'], array(
      'expanded' => array(
        $link['mlid'],
      ),
      'min_depth' => $link['depth'] + 1,
    ));
    foreach ($children as $child) {
      $link = $child['link'];

      // Update this menu item, and loop through it's children if there are
      // any.
      _pathauto_menu_link_update($link);
    }
  }
}

/**
 * See if a link has any child links
 *
 * @param object $link
 *   The parent link
 */
function _pathauto_menu_link_has_children($link) {

  // If has_children is set we can assume TRUE.
  if ($link['has_children']) {
    return TRUE;
  }

  // Check if at least one child exists in the table.
  $query = db_select('menu_links');
  $query
    ->addField('menu_links', 'mlid');
  $query
    ->condition('menu_name', $link['menu_name']);
  $query
    ->condition('plid', $link['mlid']);
  $query
    ->range(0, 1);
  return (bool) $query
    ->execute()
    ->fetchField() ? 1 : 0;
}

Functions

Namesort descending Description
pathauto_menu_link_menu_link_update Implements hook_menu_link_update().
_pathauto_menu_link_has_children See if a link has any child links
_pathauto_menu_link_update Update the path for a node menu link.
_pathauto_menu_link_update_children Search for and update any child menu links.