<?php

/**
 * @file
 * Registration process without a username
 *
 */

/**
 * Implements hook_user_insert().
 */
function email_registration_user_insert(&$edit, &$account, $category = NULL) {
  // 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 ((bool) db_query("SELECT 1 FROM {users} WHERE uid <> :uid AND LOWER(name) = LOWER(:namenew)", array(':uid' => $account->uid, ':namenew' => $namenew))->fetchField()) {
      $nameidx = db_query_range("SELECT SUBSTRING_INDEX(name,'_',-1) FROM {users} WHERE name REGEXP :search ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC", 0, 1, array(':search' => '^' . $namenew . '_[0-9]+$'))->fetchField();

      $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);
  }

  // replace with generated username
  db_update('users')
    ->fields(array('name' => $namenew))
    ->condition('uid', $account->uid)
    ->execute();

  $edit['name'] = $namenew;
  
  // 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;
    $user->name = $namenew;
  }
  $account->name = $namenew;
  return;
}

/**
 * Implements hook_form_alter().
 *
 */
function email_registration_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
      if (isset($form['account']) && is_array($form['account'])) {
        $form['account']['name']['#type'] = 'hidden';
        $form['account']['name']['#value'] = user_password();
        $form['account']['mail']['#title'] = t('E-mail');
      }
      else {
        $form['name']['#type'] = 'hidden';
        $form['name']['#value'] = user_password();
        $form['mail']['#title'] = t('E-mail');
      }
      $form['#submit'][] = 'custom_email_registration_name_submit';
      break;

    case 'user_pass':
      $form['name']['#title'] = t('E-mail');
      $form['name']['#description'] = t('Enter your e-mail address. You\'ll be sent a new password immediately.');
      break;

    case 'user_login':
      $form['name']['#title'] = t('E-mail');
      $form['name']['#description'] = t('Enter your e-mail address.');
      $form['pass']['#description'] = t('Enter the password that accompanies your e-mail.');
      $form['name']['#element_validate'][] = 'email_registration_user_login_validate';
      break;

    case 'user_login_block':
      $form['name']['#title'] = t('E-mail');
      $form['name']['#element_validate'][] = 'email_registration_user_login_validate';
      break;
  }
}


/**
 * Form element submit handler for user registration form
 * Fixes redirect for immediate logins
 *
 */
function custom_email_registration_name_submit($form, &$form_state) {
  if (!isset($form_state['user'])) {
    return;
  }

  $admin = user_access('administer users');
  $account = $form_state['user'];

  if (!variable_get('user_email_verification', TRUE) && $account->status && !$admin) {
    // No e-mail verification is required, create account, and login user immediately.
    if (user_authenticate($account->name, $form_state['values']['pass'])) {
      // Authenticated, add a message and go to the users account
      $form_state['redirect'] = 'user/' . $account->uid;
    }
  }
}

/**
 * Form element validation handler for user login form.
 * Allows users to authenticate by email, which is our preferred method.
 *
 */
function email_registration_user_login_validate($form, &$form_state) {
  if (isset($form_state['values']['name'])) {
    if ($name = db_query('SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:name)', array(':name' => $form_state['values']['name']))->fetchField()) {
      $form_state['values']['name'] = $name;
    }
  }
}