You are here

function uif_unique_username in User Import Framework 7

Same name and namespace in other branches
  1. 6 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.

2 calls to uif_unique_username()
uif_create_user in ./uif.admin.inc
Create a new user.
uif_update_user in ./uif.admin.inc
Update an existing user.

File

./uif.admin.inc, line 599
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;
    $args = array(
      ':uid' => $uid,
      ':name' => $newname,
    );
    $found = db_query_range('SELECT uid from {users} WHERE uid <> :uid AND name = :name', 0, 1, $args)
      ->fetchField();
    $i++;
  } while ($found);
  return $newname;
}