You are here

function simple_fb_connect_unique_user_name in Simple FB Connect 7.2

Same name and namespace in other branches
  1. 8 simple_fb_connect.module \simple_fb_connect_unique_user_name()
  2. 7 simple_fb_connect.module \simple_fb_connect_unique_user_name()

Generates a unique username for Drupal site based on FB username.

Return value

string|bool Unique username, if the generated username passes user_validate_name(). False otherwise.

See also

user_validate_name()

1 call to simple_fb_connect_unique_user_name()
simple_fb_connect_create_user in ./simple_fb_connect.module
Creates a new user account for a Facebook user.

File

./simple_fb_connect.module, line 916
Simple Facebook Login Module for Drupal Sites.

Code

function simple_fb_connect_unique_user_name($fb_name) {

  // Truncate to max length.
  $fb_name = drupal_substr($fb_name, 0, USERNAME_MAX_LENGTH);

  // Add a trailing number if needed to make username unique.
  $base = $fb_name;
  $i = 1;
  $candidate = $base;
  while (is_object(user_load_by_name($candidate))) {
    $i++;

    // Calculate max length for $base and truncate if needed.
    $max_length_base = USERNAME_MAX_LENGTH - strlen((string) $i) - 1;
    $base = drupal_substr($base, 0, $max_length_base);
    $candidate = $base . " " . $i;
  }

  // Trim leading and trailing whitespace.
  $candidate = trim($candidate);

  // Remove multiple spacebars if needed.
  $candidate = preg_replace('/ {2,}/', ' ', $candidate);

  // We now have a candidate that is unique and not too long.
  // Let's check that the username passes Drupal username validation.
  if ($error = user_validate_name($candidate)) {
    return FALSE;
  }

  // Validation passed, return the username.
  return $candidate;
}