You are here

function auto_username_user in Automatic User Names 6

Same name and namespace in other branches
  1. 5 auto_username.module \auto_username_user()

Implementation of hook_user().

File

./auto_username.module, line 136

Code

function auto_username_user($op, &$edit, &$account, $category = NULL) {
  static $new_name;
  switch ($op) {
    case 'validate':
      $new_name = _auto_username_patternprocessor($account);

      // Borrowed from _user_edit_validate().
      if ($error = user_validate_name($new_name)) {
        form_set_error('name', $error);
      }

      // Add a serial to the name for uniqueness.
      $counter = 1;
      $base_name = $new_name;
      while (db_result(db_query("SELECT COUNT(uid) FROM {users} WHERE uid <> %d AND LOWER(name) = LOWER('%s')", $account->uid, $new_name)) > 0) {
        $new_name = $base_name . $counter++;
      }

      // Save to the session so that we can grab it in the form submit handler
      // later.  Yes, we could use a global instead, but then we'd be using
      // globals!
      $_SESSION['auto_username']['new_name'] = $new_name;
      break;
    case 'insert':

      // change $account so that other modules (eg. pathauto) will be able to use the new name
      $account->name = $new_name;
      $edit['name'] = $new_name;
      db_query("UPDATE {users} SET name='%s' WHERE uid=%d", array(
        $new_name,
        $account->uid,
      ));
      break;
    case 'after_update':

      // Only process on update if we're configured to do so.
      // We have to use after_update here instead of the 'update' op because
      // update happens before user module does its own saving.  Anything we do
      // to the users table in op update would be overwritten.
      if (variable_get('aun_update_on_edit', 1)) {
        db_query("UPDATE {users} SET name='%s' WHERE uid=%d", array(
          $new_name,
          $account->uid,
        ));
      }
      break;
  }
}