You are here

function auto_username_generate_username in Automatic User Names 7

Work out what the new username could be, calling api hooks where applicable, and adding a number suffix if necccessary.

Parameters

type $edit:

type $account:

Return value

string

1 call to auto_username_generate_username()
auto_username_user_presave in ./auto_username.module
Implements hook_user_presave().

File

./auto_username.module, line 143
Allows a user's username to be assigned based on tokens.

Code

function auto_username_generate_username(&$edit, &$account) {
  $new_name = "";

  // Other modules may implement hook_auto_username_name($edit, $account) to generate a username (return a
  // string to be used as the username, NULL to have auto_username generate it).
  $names = module_invoke_all('auto_username_name', $edit, $account);

  // Remove any empty entries.
  $names = array_filter($names);
  if (empty($names)) {

    // Default implementation of name generation.
    $new_name = _auto_username_patternprocessor($account);
  }
  else {

    // One would expect a single implementation of the hook, but if there
    // are multiples out there use the last one.
    $new_name = array_pop($names);
  }

  // If no new name was found, then either the hook hasn't been implemented, or
  // the aun_pattern hasn't been set yet. Therefore leave the username as it is.
  if (empty($new_name)) {
    return $account->name;
  }

  // lets check if our name is used somewhere else, and append _1 if it is  eg:(chris_123). We do this regardless of
  // whether hook has run, as we can't assume the hook implementation will do this santity check.
  $i = 0;
  $static_name = $new_name;
  do {
    $new_name = empty($i) ? $static_name : $static_name . '_' . $i;
    $found = db_select('users', 'u')
      ->fields('u')
      ->condition('uid', $account->uid, '!=')
      ->condition('name', $new_name)
      ->execute()
      ->fetchAll();
    $i++;
  } while (!empty($found));
  return $new_name;
}