<?php
// $Id: email_registration.module,v 1.3 2007/10/11 03:14:13 chrisherberte Exp $

/**
 * Implementation of hook_user().
 *
 */

function email_registration_user($op, &$edit, &$account, $category = NULL) {
  switch($op) {
    case 'insert':
	  $namenew = preg_replace('/@.*$/', '', $edit['mail']);
    // if username generated from email record already exists, append underscore and number eg:(chris_123)
	  if (db_num_rows(db_query("SELECT uid 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_[0-9]+$' ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC LIMIT 1";
      $nameidx = db_result(db_query($sql, $namenew));
      $namenew .= '_' . ($nameidx + 1);
    }
    // replace with generated username
    db_query("UPDATE {users} SET name = '%s' WHERE uid = '%s'", $namenew, $account->uid);
	  break;
  }
  return;
}

/**
 * Implementation of hook_form_alter().
 *
 */

function email_registration_form_alter($form_id, &$form) {
  switch ($form_id) {
    case 'user_register':
      email_registration_inject($form, 'name', array(
				'#type'  => 'hidden',
		    '#value' => user_password(),
			));
		  email_registration_inject($form, 'mail', array(
      	'#title' => t('E-mail'),
			));
      break;

    case 'user_pass':
		  email_registration_inject($form, 'name', array(
				'#title'       => t('E-mail'),
			   // this description may be untrue in some cases (like if email verification is off i think)
				'#description' => t('Enter your e-mail address. You\'ll be sent a new password immediately.'),
			));
      break;

    case 'user_login':
      email_registration_inject($form, 'name', array(
				'#title'       => t('E-mail'),
				'#description' => t('Enter your e-mail address.'),
			));

	    $form['#validate'] = array('email_registration_user_login_validate' => array()) + $form['#validate'];
      break;

    case 'user_login_block':
			email_registration_inject($form, 'name', array('#title' => t('E-mail')));
	    $form['#validate'] = array('email_registration_user_login_validate' => array()) + $form['#validate'];
      break;
  }
}

/**
 * Custom validation function for user login form.
 * Allows users to authenticate by email only, which is our preferred method.
 *
 */

function email_registration_user_login_validate($form_id, $form_values, $form) {
  if (isset($form_values['name'])) {
    if ($name = db_result(db_query("SELECT name FROM {users} WHERE LOWER(mail) = LOWER('%s')", $form_values['name']))) {
      form_set_value($form['name'], $name);
    }
  }
}

function email_registration_inject(&$form, $fieldname, $attrib = array()) {
	// make sure we have something to inject before we recursively search for this field
  if (! count($attrib)) return;

  // check for our field in the form, this may be the root form array, a fieldset
	if (isset($form[$fieldname])) {
		$form[$fieldname] = array_merge($form[$fieldname], $attrib);
		return true;
	}
  // so far we haven't found the field we are looking for, lets traverse the form and search in fieldsets as well
	else {
		foreach (array_keys($form) AS $field) {
		  if (strpos($field, '#') != 1 && isset($form[$field]['#type']) && $form[$field]['#type'] == 'fieldset') {
				if (email_registration_inject($form[$field], $fieldname, $attrib))
					return true;
			}
		}
	}
	return false;
}