You are here

function email_registration_unique_username in Email Registration 7

Same name and namespace in other branches
  1. 8 email_registration.module \email_registration_unique_username()
  2. 6 email_registration.module \email_registration_unique_username()

Given a starting point returns a legal, unique Drupal username.

This function is designed to work on the results of the /user/register or /admin/people/create forms which have already called user_validate_name, valid_email_address or a similar function. If your custom code is creating users, you should ensure that the email/name is already validated using something like that. Alternatively you can prepend the account user name to contain 'email_registration_' to allow for the email registration hooks to generate a unique username based on mail.

Parameters

string $name: A name from which to base the final user name. May contain illegal characters; these will be stripped.

int $uid: (optional) Uid to ignore when searching for unique user (e.g. if we update the username after the {users} row is inserted)

Return value

string A unique user name based on $name.

See also

user_validate_name()

1 call to email_registration_unique_username()
email_registration_user_insert in ./email_registration.module
Implements hook_user_insert().

File

./email_registration.module, line 72
Allows users to register with an e-mail address as their username.

Code

function email_registration_unique_username($name, $uid = NULL) {

  // Iterate until we find a unique name.
  $i = 0;
  do {
    $new_name = empty($i) ? $name : $name . '_' . $i;
    if ($uid) {
      $found = db_query_range("SELECT uid from {users} WHERE uid <> :uid AND name = :name", 0, 1, array(
        ':uid' => $uid,
        ':name' => $new_name,
      ))
        ->fetchAssoc();
    }
    else {
      $found = db_query_range("SELECT uid from {users} WHERE name = :name", 0, 1, array(
        ':name' => $new_name,
      ))
        ->fetchAssoc();
    }
    $i++;
  } while (!empty($found));
  return $new_name;
}