You are here

function rb_user_action_provide_username in Rules Bonus Pack 6

Action for 'rb_user_action_provide_username'.

File

./rb_user.module, line 210
Functions for extending user management with Rules.

Code

function rb_user_action_provide_username($settings) {
  $potential_name = $settings['potential_name'];

  // Go through the checks that user_validate_name has, and clean the string.
  $potential_name = trim($potential_name);
  if (!strlen($potential_name)) {
    return t('dummy name');
  }
  while (strpos($potential_name, '  ') !== FALSE) {
    $potential_name = str_replace('  ', ' ', $potential_name);
  }

  // '/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i'
  // Check for, and replace, some regexp patterns.
  $pattern = implode('', array(
    '/[\\x{80}-\\x{A0}',
    // Non-printable ISO-8859-1 + NBSP
    '\\x{AD}',
    // Soft-hyphen
    '\\x{2000}-\\x{200F}',
    // Various space characters
    '\\x{2028}-\\x{202F}',
    // Bidirectional text overrides
    '\\x{205F}-\\x{206F}',
    // Various text hinting characters
    '\\x{FEFF}',
    // Byte order mark
    '\\x{FF01}-\\x{FF60}',
    // Full-width latin
    '\\x{FFF9}-\\x{FFFD}',
    // Replacement characters
    '\\x{0}-\\x{1F}]/u',
  ));

  // Let's iterate, just to make sure that we remove ALL occurances.
  while (preg_match($pattern, $potential_name)) {
    $potential_name = preg_replace($pattern, '', $potential_name);
  }

  // We compare against max length - 3, to make room for two-digit running
  // numbers for creating uniqueness. This limit is set pretty arbitrary, but
  // will work for all sane use cases.
  if (drupal_strlen($potential_name) > USERNAME_MAX_LENGTH - 3) {
    $potential_name = substr($potential_name, 0, USERNAME_MAX_LENGTH - 3);
  }

  // Check if the user name STILL contains any troubles.
  if (user_validate_name($potential_name) != NULL) {
    $potential_name = 'dummy name';
  }

  // Add a number to the name until it is unique in the user table.
  $unique_name = $potential_name;
  $index = 0;
  while (user_load(array(
    'name' => $unique_name,
  )) !== FALSE) {

    // Name exists in the user table; add a number to eventually make it unique.
    $index++;
    $unique_name = "{$potential_name} {$index}";
  }
  return array(
    'username' => $unique_name,
  );
}