You are here

function uif_unique_username in User Import Framework 6

Same name and namespace in other branches
  1. 7 uif.admin.inc \uif_unique_username()

Given a starting point for a Drupal username (e.g. the name portion of an email address) return a legal, unique Drupal username.

Parameters

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

$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

A unique user name based on $name.

1 call to uif_unique_username()
uif_create_user in ./uif.admin.inc
Create a new user.

File

./uif.admin.inc, line 495
Simple, extensible user import from a CSV file.

Code

function uif_unique_username($name, $uid = 0) {

  // Strip illegal characters
  $name = preg_replace('/[^\\x{80}-\\x{F7} a-zA-Z0-9@_.\'-]/', '', $name);

  // Strip leading and trailing whitespace
  $name = trim($name);

  // Convert any other series of spaces to a single space
  $name = preg_replace('/ +/', ' ', $name);

  // If there's nothing left use a default
  $name = '' === $name ? t('user') : $name;

  // Truncate to reasonable size
  $name = drupal_strlen($name) > USERNAME_MAX_LENGTH - 10 ? drupal_substr($name, 0, USERNAME_MAX_LENGTH - 11) : $name;

  // Iterate until we find a unique name
  $i = 0;
  do {
    $newname = empty($i) ? $name : $name . '_' . $i;
    $found = db_result(db_query_range("SELECT uid from {users} WHERE uid <> %d AND name = '%s'", $uid, $newname, 0, 1));
    $i++;
  } while ($found);
  return $newname;
}