Index: email_registration.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/email_registration/email_registration.module,v
retrieving revision 1.5.2.13
diff -u -r1.5.2.13 email_registration.module
--- email_registration.module	25 Feb 2010 21:25:07 -0000	1.5.2.13
+++ email_registration.module	30 Nov 2010 21:03:04 -0000
@@ -14,39 +14,19 @@
 function email_registration_user($op, &$edit, &$account, $category = NULL) {
   switch ($op) {
     case 'insert':
-      // Other modules may implement hook_email_registration_name($edit, $account)
-      // to generate a username (return a string to be used as the username, NULL
-      // to have email_registration generate it)
-      $names = module_invoke_all('email_registration_name', $edit, $account);
-      // Remove any empty entries
-      $names = array_filter($names);
-
-      if (empty($names)) {
-        // Default implementation of name generation
-        $namenew = preg_replace('/@.*$/', '', $edit['mail']);
-        // Remove unwanted characters
-        $namenew = preg_replace('/[^a-zA-Z0-9.-]/', '', $namenew);
-
-        // if username generated from email record already exists, append underscore and number eg:(chris_123)
-        if (db_result(db_query("SELECT count(*) FROM {users} WHERE uid <> %d AND LOWER(name) = LOWER('%s')", $account->uid, $namenew)) > 0) {
-          // find the next number available to append to the name
-          $sql = "SELECT SUBSTRING_INDEX(name,'_',-1) FROM {users} WHERE name REGEXP '%s' ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC LIMIT 1";
-          $nameidx = db_result(db_query($sql, '^'. $namenew .'_[0-9]+$'));
-          $namenew .= '_'. ($nameidx + 1);
-        }
-      }
-      else {
-        // One would expect a single implementation of the hook, but if there
-        // are multiples out there use the last one
-        $namenew = array_pop($names);
+      // Don't create a new username if one is already set.
+      if (!empty($account->name) && strpos($account->name, 'email_registration_') !== 0) {
+        return;
       }
+    
+      $namenew = email_registration_generate_name($edit, $account);
 
-      // replace with generated username
+      // Replace with generated username
       if (db_query("UPDATE {users} SET name = '%s' WHERE uid = '%s'", $namenew, $account->uid)) {
         $edit['name'] = $namenew; // update in the user array for access by other modules
       }
 
-      // if email verification is off and a new user is the one creating account, log the new user in with correct name
+      // If email verification is off and a new user is the one creating account, log the new user in with correct name
       global $user;
       if (!variable_get('user_email_verification', 1) && $user->uid == 0) {
         $user = $account;
@@ -65,17 +45,17 @@
 function email_registration_form_alter(&$form, $form_state, $form_id) {
   switch ($form_id) {
     case 'user_register':
+      $name = 'email_registration_' . user_password();
       if (isset($form['account']) && is_array($form['account'])) {
-        $form['account']['name']['#type'] = 'hidden';
-        $form['account']['name']['#value'] = user_password();
+        $form['account']['name']['#type'] = 'value';
+        $form['account']['name']['#value'] = $name;
         $form['account']['mail']['#title'] = t('E-mail');
       }
       else {
-        $form['name']['#type'] = 'hidden';
-        $form['name']['#value'] = user_password();
+        $form['name']['#type'] = 'value';
+        $form['name']['#value'] = $name;
         $form['mail']['#title'] = t('E-mail');
       }
-      $form['#submit'][] = 'custom_email_registration_name_submit';
       break;
 
     case 'user_pass':
@@ -97,13 +77,12 @@
   }
 }
 
-
 /**
  * Custom submit handler to fix redirect for immediate logins
  * #648450
  *
  */
-function custom_email_registration_name_submit($form, &$form_state) {
+function email_registration_user_register_submit($form, &$form_state) {
   if (!isset($form_state['user'])) {
     return;
   }
@@ -138,4 +117,94 @@
       $form_state['values']['name'] = $name;
     }
   }
-}
\ No newline at end of file
+}
+
+
+/**
+ * Generate a username.
+ */
+function email_registration_generate_name($edit, $account) {
+
+  // Other modules may implement hook_email_registration_name($edit, $account)
+  // to generate a username (return a string to be used as the username, NULL
+  // to have email_registration generate it)
+  $names = module_invoke_all('email_registration_name', $edit, $account);
+
+  // Remove any empty entries
+  $names = array_filter($names);
+
+  if (empty($names)) {
+    // Default implementation of name generation
+    $namenew = _email_registration_generate_name($edit, $account);
+  }
+  else {
+    // One would expect a single implementation of the hook, but if there
+    // are multiples out there use the last one
+    $namenew = array_pop($names);
+  }
+
+  return $namenew;
+}
+
+/**
+ * Helper function: Generate a username by the default algorithm.
+ */
+function _email_registration_generate_name($edit, $account) {
+  $name = preg_replace('/@.*$/', '', $edit['mail']);
+  
+  // Strip illegal characters
+  $name = preg_replace('/[^\x{80}-\x{F7} a-zA-Z0-9@_.\'-]/', '', $name);
+  // Strip leading and trailing spaces
+  $name = preg_replace('/^ +/', '', $name);
+  $name = preg_replace('/ +$/', '', $name);
+  
+  // Convert any other series of spaces to a single underscore
+  $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;
+    $found = db_result(db_query_range("SELECT uid from {users} WHERE uid <> %d AND name = '%s'", $account->uid, $newname, 0, 1));
+    $i++;
+  } while ($found);
+
+  return $newname;
+}
+
+/**
+ * Implementation of hook_user_import_pre_save()
+ */
+function email_registration_user_import_after_save($settings, $account, $fields, $errors, $update_setting_per_module) {
+  static $generate_username = NULL;
+  
+  // The generate_username haven't been setted:  calculate it from the settings parameter
+  if (is_null($generate_username)) {
+    foreach($settings['field_match'] as $match) {
+      if ($match['username'] != 0) {
+        // This field is a username candidate, end our search!
+        $generate_username = FALSE;
+      }
+    }
+    // If the $generate_username is still NULL, no field have been setted as the username
+    if (is_null($generate_username)) {
+      $generate_username = TRUE;
+    }
+  }
+  // If we have to generate the new username, and the given account is valid
+  if ($generate_username === TRUE && !empty($account->uid)) {
+    $edit = (array)$account;
+    $newname = email_registration_generate_name($edit, $account);
+    $new_user_data = array('name' => $newname);
+    
+    // Let Drupal hooks be called for the updated username!
+    user_save($account, $new_user_data);
+  }
+ 
+}

