You are here

function _hybridauth_make_username in HybridAuth Social Login 7.2

Same name and namespace in other branches
  1. 6.2 hybridauth.module \_hybridauth_make_username()

Helper function to generate user name.

Parameters

array $data: The data returned by HybridAuth or entered by the user.

bool $allow_empty: (optional) Allow this function to return empty username.

Return value

string The proposed user name to use for this user.

2 calls to _hybridauth_make_username()
hybridauth_additional_info_form in ./hybridauth.pages.inc
_hybridauth_window_process_auth in ./hybridauth.pages.inc
Handle the Drupal authentication.

File

./hybridauth.module, line 1032
Main file for the HybridAuth module.

Code

function _hybridauth_make_username($data, $allow_empty = FALSE) {

  // $data['username'] contains user entered username, we should use it if
  // available.
  if (empty($data['username'])) {
    $pattern = variable_get('hybridauth_username', '[user:hybridauth:firstName] [user:hybridauth:lastName]');
    $account = new stdClass();
    $account->data = array(
      'hybridauth' => $data,
    );
    $hybridauth_name = trim(token_replace($pattern, array(
      'user' => $account,
    ), array(
      'clear' => TRUE,
      'sanitize' => FALSE,
    )));
  }
  else {
    $hybridauth_name = trim($data['username']);
  }

  // Strip multiple spaces and illegal characters, see user_validate_name().
  $hybridauth_name = preg_replace('/[^\\x{80}-\\x{F7} a-z0-9@_.\'-]/i', '', $hybridauth_name);
  $hybridauth_name = preg_replace('/[\\x{80}-\\x{A0}' . '\\x{AD}' . '\\x{2000}-\\x{200F}' . '\\x{2028}-\\x{202F}' . '\\x{205F}-\\x{206F}' . '\\x{FEFF}' . '\\x{FF01}-\\x{FF60}' . '\\x{FFF9}-\\x{FFFD}' . '\\x{0}-\\x{1F}]/u', '', $hybridauth_name);
  $hybridauth_name = preg_replace('/[ ]{2,}/', ' ', $hybridauth_name);

  // Check for empty username and use default one if empty is not allowed.
  if (empty($hybridauth_name) && !$allow_empty) {
    $hybridauth_name = 'hybridauth_user';
  }
  $desired_name = $hybridauth_name;
  if (!empty($hybridauth_name)) {

    // Find the initial counter value.
    $query = db_select('users', 'u')
      ->condition('u.name', db_like($desired_name) . '%', 'LIKE');
    $query
      ->addExpression('COUNT(1)');
    $counter = $query
      ->execute()
      ->fetchField();
    if (!empty($counter)) {
      $hybridauth_name = $desired_name . ' ' . $counter;
    }

    // Check that the username is unique.
    while (user_load_by_name($hybridauth_name)) {
      $counter++;
      $hybridauth_name = $desired_name . ' ' . $counter;
    }
  }
  $name = $hybridauth_name;

  // Invoke hook_hybridauth_username_alter().
  drupal_alter('hybridauth_username', $name, $data);

  // Check that the altered username is unique.
  if (!empty($name) && !user_load_by_name($name)) {
    return $name;
  }
  return $hybridauth_name;
}