Skip to content
logintoboggan.module 58.3 KiB
Newer Older
/**
 * @file
 *  Logintoboggan Module
 *
 * This module enhances the configuration abilities of Drupal's default login system.
 */

Chad Phillips's avatar
Chad Phillips committed
 * @wishlist
Chad Phillips's avatar
Chad Phillips committed
 *
/**
 * @defgroup logintoboggan_core Core drupal hooks
 */

/**
function logintoboggan_cron() {
  // If set password is enabled, and a purge interval is set, check for
  // unvalidated users to purge.
  if (($purge_interval = variable_get('logintoboggan_purge_unvalidated_user_interval', 0)) && !variable_get('user_email_verification', TRUE)) {
    $validating_id = logintoboggan_validating_id();
    // As a safety check, make sure that we have a non-core role as the
    // pre-auth role -- otherwise skip.
    if (!in_array($validating_id, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
      $purge_time = REQUEST_TIME - $purge_interval;
      $accounts = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid WHERE ur.rid = :rid AND u.created < :created", array(
        ':rid' => $validating_id,
        ':created' => $purge_time,
      ));
      foreach ($accounts as $account) {
        $purged_users[] = check_plain($account->name);
      }

      // Delete the users from the system.
      user_delete_multiple($uids);

      // Log the purged users.
      if (!empty($purged_users)) {
        batch_process(drupal_get_destination());
        watchdog('logintoboggan', 'Purged the following unvalidated users: !purged_users', array('!purged_users' => theme('item_list', array('items' => $purged_users))));
function logintoboggan_help($path, $arg) {
  switch ($path) {
    case 'admin/help#logintoboggan':
      $output = t("<p>The Login Toboggan module improves the Drupal login system by offering the following features:
      <li>Allow users to login using either their username OR their e-mail address.</li>
      <li>Allow users to login immediately.</li>
      <li>Provide a login form on Access Denied pages for non-logged-in (anonymous) users.</li>
      <li>The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking 'log in'. The other brings the user to a separate page, but returns the user to their original page upon login.</li>
      <li>Customize the registration form with two e-mail fields to ensure accuracy.</li>
Chad Phillips's avatar
Chad Phillips committed
      <li>Optionally redirect the user to a specific page when using the 'Immediate login' feature.</li>
      <li>Optionally redirect the user to a specific page upon validation of their e-mail address.</li>
      <li>Optionally display a user message indicating a successful login.</li>
      <li>Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).</li>
      These features may be turned on or off in the Login Toboggan <a href=\"!url\">settings</a>.</p>
      <p>Because this module completely reorients the Drupal login process you will probably want to edit the welcome e-mail on the <a href=\"!user_settings\">user settings</a> page. For instance if you have enabled the 'Set password' option, you probably should not send the user's password out in the welcome e-mail (also note when the 'Set password' option is enabled, the !login_url becomes a verification url that the user MUST visit in order to enable authenticated status). The following is an example welcome e-mail:</p>
      ", array('!url' => url('admin/config/system/logintoboggan'), '!user_settings' => url('admin/config/people/accounts')));
Chad Phillips's avatar
Chad Phillips committed
      $example_help_form = drupal_get_form('logintoboggan_example_help');
      $output .= drupal_render($example_help_form);
      $output .= t("<p>Note that if you have set the 'Visitors can create accounts but administrator approval is required' option for account approval, and are also using the 'Set password' feature of LoginToboggan, the user will immediately receive the permissions of the pre-authorized user role -- you may wish to create a pre-authorized role with the exact same permissions as the anonymous user if you wish the newly created user to only have anonymous permissions.</p><p>In order for a site administrator to unblock a user who is awaiting administrator approval, they must either click on the validation link they receive in their notification e-mail, or manually remove the user from the site's pre-authorized role -- afterwards the user will then receive 'authenticated user' permissions. In either case, the user will receive an account activated e-mail if it's enabled on the user settings page -- it's recommended that you edit the default text of the activation e-mail to match LoginToboggan's workflow as described. </p><p>If you are using the 'Visitors can create accounts and no administrator approval is required' option, removal of the pre-authorized role will happen automatically when the user validates their account via e-mail.</p><p>Also be aware that LoginToboggan only affects registrations initiated by users--any user account created by an administrator will not use any LoginToboggan functionality.");
Chad Phillips's avatar
Chad Phillips committed
      return $output;
      break;
    case 'admin/config/system/logintoboggan':
      if (module_exists('help')) {
        $help_text =  t("More help can be found at <a href=\"!help\">LoginToboggan help</a>.", array('!help' => url('admin/help/logintoboggan')));
      }
      else {
        $help_text = '';
      }
      $output = t("<p>Customize your login and registration system. $help_text</p>");
Chad Phillips's avatar
Chad Phillips committed

      return $output;
  }
}

/**
 * Helper function for example user e-mail textfield.
Chad Phillips's avatar
Chad Phillips committed
 */
function logintoboggan_example_help() {
  $example = t('

IMPORTANT:
For full site access, you will need to click on this link or copy and paste it in your browser:

This will verify your account and log you into the site. In the future you will be able to log in to [site:login-url] using the username and password that you created during registration.
');
Chad Phillips's avatar
Chad Phillips committed
  $form['foo'] = array(
    '#type' => 'textarea',
    '#default_value' => $example,
    '#rows' => 15,
  );
Chad Phillips's avatar
Chad Phillips committed
  return $form;
 * Implement hook_form_block_admin_configure_alter().
function logintoboggan_form_block_admin_configure_alter(&$form, &$form_state) {
  if (($form['module']['#value'] == 'user') && ($form['delta']['#value'] == 'login')) {
    $form['#submit'][] = 'logintoboggan_user_block_admin_configure_submit';

    $form['settings']['title']['#description'] .= '<div id="logintoboggan-block-title-description">'. t('<strong>Note:</strong> Logintoboggan module is installed. If you are using one of the custom login block types below, it is recommended that you set this to <em>&lt;none&gt;</em>.') .'</div>';
    $form['settings']['logintoboggan_login_block_type'] = array(
      '#type' => 'radios',
      '#title' => t('Block type'),
      '#default_value' => variable_get('logintoboggan_login_block_type', 0),
      '#options' => array(t('Standard'), t('Link'), t('Collapsible form')),
      '#description' => t("'Standard' is a standard login block, 'Link' is a login link that returns the user to the original page after logging in, 'Collapsible form' is a javascript collaspible login form."),
    );

    $form['settings']['logintoboggan_login_block_message'] = array(
      '#type' => 'textarea',
      '#title' => t('Set a custom message to appear at the top of the login block'),
      '#default_value' => variable_get('logintoboggan_login_block_message', ''),
    );
  }
}

/**
 * Implement hook_form_logintoboggan_main_settings_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_logintoboggan_main_settings_alter(&$form, &$form_state) {
  // Ensure a valid submit array.
  $form['#submit'] = is_array($form['#submit']) ? $form['#submit'] : array();
  // Make this submit handler run first.
  array_unshift($form['#submit'], 'logintoboggan_main_settings_submit');
/**
 * Implement hook_form_user_profile_form_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_user_profile_form_alter(&$form, &$form_state) {
  if ($form['#user_category'] == 'account') {
    $account = $form['#user'];
    $form['#validate'][] = 'logintoboggan_user_edit_validate';

    // User is editing their own account settings, or user admin
    // is editing their account.
    if ($GLOBALS['user']->uid == $account->uid || user_access('administer users')) {
      // Display link to re-send validation e-mail.
      // Re-validate link appears if:
      //   1. Users can create their own password.
      //   2. User is still in the validating role.
      //   3. Users can create accounts without admin approval.
      //   4. The validating role is not the authorized user role.
      $validating_id = logintoboggan_validating_id();
      if (!variable_get('user_email_verification', TRUE) && array_key_exists($validating_id, $account->roles) && (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS) && ($validating_id > DRUPAL_AUTHENTICATED_RID)) {
        $form['revalidate'] = array(
          '#type' => 'fieldset',
          '#title' => t('Account validation'),
          '#weight' => -10,
        );
        $form['revalidate']['revalidate_link'] = array(
          '#markup' => l(t('re-send validation e-mail'), 'toboggan/revalidate/'. $account->uid),
    $id = logintoboggan_validating_id();
    $pre_auth = !variable_get('user_email_verification', TRUE) && $id != DRUPAL_AUTHENTICATED_RID;
    $in_pre_auth_role = in_array($id, array_keys($account->roles));
    // Messages are only necessary for user admins, and aren't necessary if
    // there's no valid pre-auth role.
    if (user_access('administer users') && isset($form['account']['roles']) && $pre_auth) {
      // User is still in the pre-auth role, so let the admin know.
      if ($in_pre_auth_role) {
        // To reduce UI confusion, remove the disabled checkbox for the
        // authenticated user role.
        unset($form['account']['roles'][DRUPAL_AUTHENTICATED_RID]);

        // This form element is necessary as a placeholder for the user's
        // pre-auth setting on form load.  It's used to compare against the
        // submitted form values to see if the pre-auth role has been unchecked.
        $form['logintoboggan_pre_auth_check'] = array(
          '#type' => 'hidden',
          '#value' => '1',
        );
        if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) {
          $form['account']['status']['#description'] = t('If this user was created using the "Immediate Login" feature of LoginToboggan, and they are also awaiting adminstrator approval on their account, you must remove them from the site\'s pre-authorized role in the "Roles" section below, or they will not receive authenticated user permissions!');
        }
        $form['account']['roles']['#description'] = t("The user is assigned LoginToboggan's pre-authorized role, and is not currently receiving authenticated user permissions.");
      }
      // User is no longer in the pre-auth role, so remove the option to add
      // them back.
      else {
        unset($form['account']['roles']['#options'][$id]);
      }
    }
  }
}

/**
 * Implement hook_form_user_register_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_user_register_form_alter(&$form, &$form_state) {
  // Admin created accounts are only validated by the module.
  if (user_access('administer users')) {
    $form['#validate'][] = 'logintoboggan_user_register_validate';
  }
  $mail = variable_get('logintoboggan_confirm_email_at_registration', 0);
  $pass = !variable_get('user_email_verification', TRUE);

  // Ensure a valid submit array.
  $form['#submit'] = is_array($form['#submit']) ? $form['#submit'] : array();

  // Replace core's registration function with LT's registration function.
  // Put the LT submit handler first, so other submit handlers have a valid
  // user to work with upon registration.
  $key = array_search('user_register_submit', $form['#submit']);
  if ($key !== FALSE) {
    unset($form['#submit'][$key]);
  }
  array_unshift($form['#submit'],'logintoboggan_user_register_submit');

  if ($mail || $pass) {
    $form['#validate'][] = 'logintoboggan_user_register_validate';

    //Display a confirm e-mail address box if option is enabled.
    if ($mail) {

      $form['account']['conf_mail'] = array(
        '#type' => 'textfield',
        '#title' => t('Confirm e-mail address'),
        '#weight' => -28,
        '#maxlength' => 64,
        '#description' => t('Please re-type your e-mail address to confirm it is accurate.'),
        '#required' => TRUE,
      // Weight things properly so that the order is name, mail, conf_mail.
      $form['account']['name']['#weight'] = -30;
      $form['account']['mail']['#weight'] = -29;
    }
    if ($pass) {
      $min_pass = variable_get('logintoboggan_minimum_password_length', 0);
      $length = $min_pass ? t('between !min and', array('!min' => $min_pass)) : t('no more than');
      $pass_description = t('Please choose a password for your account; it must be !length 30 characters.', array('!length' => $length));
      if (isset($form['account'])) {
        $form['account']['pass']['#description'] = $pass_description;
      }
      else {
        $form['pass']['#description'] = $pass_description;
      }
/**
 * Implement hook_form_user_admin_account_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_user_admin_account_alter(&$form, &$form_state) {
  // Unset the ability to add the pre-auth role in the user admin interface.
  $id = logintoboggan_validating_id();
  // Test here for a valid pre-auth -- we only remove this role if one exists.
  $pre_auth = !variable_get('user_email_verification', TRUE) && $id != DRUPAL_AUTHENTICATED_RID;
  $add = t('Add a role to the selected users');
  if ($pre_auth && isset($form['options']['operation']['#options'][$add]["add_role-$id"])) {
    unset($form['options']['operation']['#options'][$add]["add_role-$id"]);
  }
}
/**
 * Implement hook_form_user_pass_reset_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_user_pass_reset_alter(&$form, &$form_state) {
  // Password resets count as validating an email address, so remove the user
  // from the pre-auth role if they are still in it.  We only want to run this
  // code when the user first hits the reset login form.
  if (arg(5) != 'login' && ($uid = (int) arg(2))) {
    if ($account = user_load($uid)) {
      $in_pre_auth_role = in_array($id, array_keys($account->roles));
      if ($in_pre_auth_role) {
        _logintoboggan_process_validation($account);
        drupal_set_message(t('You have successfully validated your e-mail address.'));
/**
 * Implement hook_form_user_admin_permissions_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_user_admin_permissions_alter(&$form, &$form_state) {
  // If the pre-auth role isn't the auth user, then add it as a setting.
  $id = logintoboggan_validating_id();
  if ($id != DRUPAL_AUTHENTICATED_RID) {
    drupal_add_js(array(
      'LoginToboggan' => array(
        'preAuthID' => $id,
      ),
    ), 'setting');
  }
}

/**
 * Implement hook_form_alter().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      // Grab the message from settings for display at the top of the login block.
      if ($login_msg = variable_get('logintoboggan_login_block_message', '')) {
        $form['message'] = array(
          '#markup' => filter_xss_admin($login_msg),
      if (variable_get('logintoboggan_login_with_email', 0)) {
        // Ensure a valid validate array.
        $form['#validate'] = is_array($form['#validate']) ? $form['#validate'] : array();
        // LT's validation function must run first.
        array_unshift($form['#validate'],'logintoboggan_user_login_validate');
        // Use theme functions to print the username field's textual labels.
        $form['name']['#title']       = theme('lt_username_title', array('form_id' => $form_id));
        $form['name']['#description'] = theme('lt_username_description', array('form_id' => $form_id));
        // Use theme functions to print the password field's textual labels.
        $form['pass']['#title']       = theme('lt_password_title', array('form_id' => $form_id));
        $form['pass']['#description'] = theme('lt_password_description', array('form_id' => $form_id));
      if (($form_id == 'user_login_block')) {
        $block_type = variable_get('logintoboggan_login_block_type', 0);
          // What would really be nice here is to start with a clean form, but
          // we can't really do that, because drupal_prepare_form() has already
          // been run, and we can't run it again in the _alter() hook, or we'll
          // get into and endless loop.  Since we don't know exactly what's in
          // the form, strip out all regular form elements and the handlers.
          foreach (element_children($form) as $element) {
            unset($form[$element]);
          }
          unset($form['#validate'], $form['#submit']);
          $form['logintoboggan_login_link'] = array(
            '#markup' => l(theme('lt_login_link'), 'user/login', array('query' => drupal_get_destination())),
          );
        }
        elseif ($block_type == 2) {
          $form  = _logintoboggan_toggleboggan($form);
        }
/**
 * Implement hook_js_alter().
 */
function logintoboggan_js_alter(&$javascript) {
  // Look for the user permissions js.
  if (isset($javascript['modules/user/user.permissions.js'])) {
    $id = logintoboggan_validating_id();
    // If the pre-auth user isn't the auth user, then swap out core's user
    // permissions js with LT's custom implementation.  This is necessary to
    // prevent the pre-auth role's checkboxes from being automatically disabled
    // when the auth user's checkboxes are checked.
    if ($id != DRUPAL_AUTHENTICATED_RID) {
      $javascript['modules/user/user.permissions.js']['data'] = drupal_get_path('module', 'logintoboggan') . '/logintoboggan.permissions.js';
    }
  }
}

/**
 * Implement hook_page_alter().
 */
function logintoboggan_page_alter(&$page) {
  // Remove blocks on access denied pages.
  if (isset($page['#logintoboggan_denied'])) {
    drupal_set_message(t('Access denied.  You may need to login below or register to access this page.'), 'error');
    unset($page['sidebar_first'], $page['sidebar_second']);
  }
}




/**
 * Implement hook_token_info().
 */
function logintoboggan_token_info() {
  $types['logintoboggan-validation'] = array(
    'name' => t('User validation'),
    'description' => t('Tokens related to validating user accounts.'),
    'needs-data' => 'user',
  );

  $user['url'] = array(
    'name' => t('Validating URL'),
    'description' => t("A special URL the user can use to validate their account."),
  );

  return array(
    'types' => array('logintoboggan' => $types),
    'tokens' => array('logintoboggan' => $user),
  );
}

/**
 * Implement hook_tokens().
 */
function logintoboggan_tokens($type, $tokens, array $data = array(), array $options = array()) {

  $url_options = array('absolute' => TRUE);
  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
    $language_code = $options['language']->language;
  }
  else {
    $language_code = NULL;
  }
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'logintoboggan-validation' && !empty($data['user'])) {
    $account = $data['user'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Validating URL.
        case 'url':
          $replacements[$original] = variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS ? logintoboggan_eml_validate_url($account, $url_options) : NULL;
/**
 * Custom submit function for user registration form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_register_submit($form, &$form_state) {
  $reg_pass_set = !variable_get('user_email_verification', TRUE);
  // Test here for a valid pre-auth -- if the pre-auth is set to the auth user, we
  // handle things a bit differently.
  $pre_auth = logintoboggan_validating_id() != DRUPAL_AUTHENTICATED_RID;

  // If we are allowing user selected passwords then skip the auto-generate function
  // The new user's status should default to the site settings, unless reg_passwd_set == 1
  // (immediate login, we are going to assign a pre-auth role), and we want to allow
  // admin approval accounts access to the site.
    $pass = $form_state['values']['pass'];
    $status = variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS;
  // The unset below is needed to prevent these form values from being saved as
  // user data.
  form_state_values_clean($form_state);

  // Must unset mail confirmation to prevent it from being saved in the user table's 'data' field.
  if (isset($form_state['values']['conf_mail'])) {
    unset($form_state['values']['conf_mail']);
  }
  // Set the roles for the new user -- add the pre-auth role if they can pick their own password,
  // and the pre-auth role isn't anon or auth user.
  $validating_id = logintoboggan_validating_id();
  $roles = isset($form_state['values']['roles']) ? array_filter($form_state['values']['roles']) : array();
  if ($reg_pass_set && ($validating_id > DRUPAL_AUTHENTICATED_RID)) {
  $form_state['values']['pass'] = $pass;
  $form_state['values']['init'] = $form_state['values']['mail'];
  $form_state['values']['roles'] = $roles;
  $form_state['values']['status'] = $status;

  $account = $form['#user'];
  $account = user_save($account, $form_state['values']);
  // Terminate if an error occurred during user_save().
  if (!$account) {
    drupal_set_message(t("Error saving user account."), 'error');
    $form_state['redirect'] = '';
    return;
  }
  watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));

  // Add plain text password into user account to generate mail tokens.
  $account->password = $pass;
  // Compose the appropriate user message--admin approvals don't require a validation email.
  if($reg_pass_set && variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS) {
    if ($pre_auth) {
      $message = t('A validation e-mail has been sent to your e-mail address. In order to gain full access to the site, you will need to follow the instructions in that message.');
    }
    else {
      $message = t('Further instructions have been sent to your e-mail address.');
  } else {
    $message = t('Your password and further instructions have been sent to your e-mail address.');
  }

  if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS) {
    // Create new user account, no administrator approval required.
    $mailkey = 'register_no_approval_required';
  } elseif (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) {
    // Create new user account, administrator approval required.
    $mailkey = 'register_pending_approval';
    $message = t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />Once it has been approved, you will receive an e-mail containing further instructions.');
  _user_mail_notify($mailkey, $account);
  // where do we need to redirect after registration?
  $redirect = _logintoboggan_process_redirect(variable_get('logintoboggan_redirect_on_register', ''), $account);
  // Log the user in if they created the account and immediate login is enabled.
  if($reg_pass_set && variable_get('logintoboggan_immediate_login_on_register', TRUE)) {
    $form_state['redirect'] = logintoboggan_process_login($account, $form_state['values'], $redirect);
  }
  else {
    // Redirect to the appropriate page.
    $form_state['redirect'] = $redirect;
}

/**
 * Custom validation for user login form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_login_validate($form, &$form_state) {
  if (isset($form_state['values']['name']) && $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_set_value($form['name'], $name, $form_state);
    }
  }
}

/**
 * Custom validation function for user registration form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_register_validate($form, &$form_state) {
  //Check to see whether our e-mail address matches the confirm address if enabled.
  if (variable_get('logintoboggan_confirm_email_at_registration', 0) && isset($form_state['values']['conf_mail'])) {
    if ($form_state['values']['mail'] != $form_state['values']['conf_mail']) {
      form_set_error('conf_mail', t('Your e-mail address and confirmed e-mail address must match.'));
    }
  }

  //Do some password validation if password selection is enabled.
  if (!variable_get('user_email_verification', TRUE)) {
    $pass_err = logintoboggan_validate_pass($form_state['values']['pass']);
    if ($pass_err) {
      form_set_error('pass', $pass_err);
    }
  }
}

/**
 * Custom validation function for user edit form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_edit_validate($form, &$form_state) {

  $account = $form['#user'];
  $edit = $form_state['values'];

  // If login with mail is enabled...
  if (variable_get('logintoboggan_login_with_email', 0)) {
    $uid = isset($account->uid) ? $account->uid : 0;
    // Check that no user is using this name for their email address.
    if (isset($edit['name']) && db_query("SELECT uid FROM {users} WHERE LOWER(mail) = LOWER(:mail) AND uid <> :uid", array(
      ':mail' => $edit['name'],
      ':uid' => $uid,
    ))->fetchField()) {
      form_set_error('name', t('This name has already been taken by another user.'));
    }
    // Check that no user is using this email address for their name.
    if (isset($edit['mail']) && db_query("SELECT uid FROM {users} WHERE LOWER(name) = LOWER(:name) AND uid <> :uid", array(
      ':name' => $edit['mail'],
      ':uid' => $uid,
    ))->fetchField()) {
      form_set_error('mail', t('This e-mail has already been taken by another user.'));
    }
  }

  if (!empty($edit['pass'])) {
    // if we're changing the password, validate it
    $pass_err = logintoboggan_validate_pass($edit['pass']);
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_init() {
  global $user;

  // Make sure any user with pre-auth role doesn't have authenticated user role
  _logintoboggan_user_roles_alter($user);

  // Add custom css.
  drupal_add_css(drupal_get_path('module', 'logintoboggan') .'/logintoboggan.css');
}

/**
 * Alter user roles for loaded user account.
 *
 * If user is not an anonymous user, and the user has the pre-auth role, and the pre-auth role
 * isn't also the auth role, then unset the auth role for this user--they haven't validated yet.
 *
 * This alteration is required because sess_read() and user_load() automatically set the
 * authenticated user role for all non-anonymous users (see http://drupal.org/node/92361).
 *
 * @param &$account
 *    User account to have roles adjusted.
 */
function _logintoboggan_user_roles_alter($account) {
  $in_pre_auth_role = in_array($id, array_keys($account->roles));
  if ($account->uid && $in_pre_auth_role) {
    if ($id != DRUPAL_AUTHENTICATED_RID) {
      unset($account->roles[DRUPAL_AUTHENTICATED_RID]);
      // Reset the permissions cache.
      drupal_static_reset('user_access');
function logintoboggan_menu() {
  $items['admin/config/system/logintoboggan'] = array(
    'title' => 'LoginToboggan',
    'description' => 'Set up custom login options like instant login, login redirects, pre-authorized validation roles, etc.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('logintoboggan_main_settings'),
    'access callback' => 'user_access',
    'access arguments' => array('administer site configuration'),
  );
  // Callback for user validate routine.
  $items['user/validate/%user/%/%'] = array(
    'title' => 'Validate e-mail address',
    'page callback' => 'logintoboggan_validate_email',
    'page arguments' => array(2, 3, 4),
    'access callback' => 'logintoboggan_validate_email_access',
    'access arguments' => array(2, 3),
  // Callback for handling access denied redirection.
  $items['toboggan/denied'] = array(
    'access callback' => TRUE,
    'page callback' => 'logintoboggan_denied',
    'title' => 'Access denied',
    'type' => MENU_CALLBACK,
  );

  //callback for re-sending validation e-mail
  $items['toboggan/revalidate/%user'] = array(
    'title' => 'Re-send validation e-mail',
    'page callback' => 'logintoboggan_resend_validation',
    'page arguments' => array(2),
    'access callback' => 'logintoboggan_revalidate_access',
    'access arguments' => array(2),
    'type' => MENU_CALLBACK,
  );
/**
 * Access check for user revalidation.
 */
function logintoboggan_revalidate_access($account) {
  return $GLOBALS['user']->uid && ($GLOBALS['user']->uid == $account->uid || user_access('administer users'));
}

/**
 * Implemenation of hook_theme().
Chad Phillips's avatar
Chad Phillips committed
 *
 * @ingroup logintoboggan_core
function logintoboggan_theme($existing, $type, $theme, $path) {
      'variables' => array('form_id' => NULL),
      'variables' => array('form_id' => NULL),
      'variables' => array('form_id' => NULL),
      'variables' => array('form_id' => NULL),
    'lt_access_denied' => array(
      'variables' => array(),
    ),
    'lt_loggedinblock' => array(
      'variables' => array('account' => NULL),
      'variables' => array(),
    'lt_login_successful_message' => array(
      'variables' => array('account' => NULL),
/**
 * @defgroup logintoboggan_block Functions for LoginToboggan blocks.
 */

function logintoboggan_user_block_admin_configure_submit($form, &$form_state) {
  variable_set('logintoboggan_login_block_type', $form_state['values']['logintoboggan_login_block_type']);
  variable_set('logintoboggan_login_block_message', $form_state['values']['logintoboggan_login_block_message']);
 * Implement hook_block_view().
 *
 * @ingroup logintoboggan_core
function logintoboggan_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'logintoboggan_logged_in':
      if ($user->uid) {
        $block['content'] =  array(
          '#theme' => 'lt_loggedinblock',
          '#account' => $user,
        );
  return $block;
}

/**
 * Implement hook_block_info().
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_block_info() {
  $blocks = array();
  $blocks['logintoboggan_logged_in'] = array(
    'info' => t('LoginToboggan logged in block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * User login block with JavaScript to expand
 * @return array
 *   the reconstituted user login block
function _logintoboggan_toggleboggan ($form) {
  drupal_add_js(drupal_get_path('module', 'logintoboggan') .'/logintoboggan.js');
  $pre = '<div id="toboggan-container" class="toboggan-container">';
  $options = array(
    'attributes' => array(
      'id' => 'toboggan-login-link',
      'class' => array('toboggan-login-link'),
    ),
    'query' => drupal_get_destination(),
  );
  $pre .= '<div id="toboggan-login-link-container" class="toboggan-login-link-container">';
  $pre .= l(theme('lt_login_link'), 'user/login', $options);
  $pre .= '<div id="toboggan-login" class="user-login-block">';
  $form['pre'] = array('#markup' => $pre, '#weight' => -300);
  $form['post'] = array('#markup' => '</div></div>', '#weight' => 300);
function logintoboggan_main_settings() {
  $_disabled = t('Disabled');
  $_enabled = t('Enabled');
  $form['login'] = array(
    '#type' => 'fieldset',
    '#title' => t('Log in'),
  $form['login']['logintoboggan_login_with_email'] = array(
Chad Phillips's avatar
Chad Phillips committed
    '#type' => 'radios',
    '#title' => t('Allow users to login using their e-mail address'),
    '#default_value' => variable_get('logintoboggan_login_with_email', 0),
Chad Phillips's avatar
Chad Phillips committed
    '#options' => array($_disabled, $_enabled),
    '#description' => t('Users will be able to enter EITHER their username OR their e-mail address to log in.'),
  $form['registration'] = array(
    '#type' => 'fieldset',
  $form['registration']['logintoboggan_confirm_email_at_registration'] = array(
Chad Phillips's avatar
Chad Phillips committed
    '#type' => 'radios',
    '#title' => t('Use two e-mail fields on registration form'),
    '#default_value' => variable_get('logintoboggan_confirm_email_at_registration', 0),
Chad Phillips's avatar
Chad Phillips committed
    '#options' => array($_disabled, $_enabled),
    '#description' => t('User will have to type the same e-mail address into both fields. This helps to confirm that they\'ve typed the correct address.'),
  if (module_exists('help')) {
    $help_text =  t(" More help in writing the e-mail message can be found at <a href=\"!help\">LoginToboggan help</a>.", array('!help' => url('admin/help/logintoboggan')));
  }
  else {
    $help_text = '';
  }
  $form['registration']['logintoboggan_user_email_verification'] = array(
Chad Phillips's avatar
Chad Phillips committed
    '#title' => t('Set password'),
    '#default_value' => !variable_get('user_email_verification', TRUE) ? 1 : 0,
    '#description' => t("This will allow users to choose their initial password when registering (note that this setting is a mirror of the <a href=\"!settings\">Require e-mail verification when a visitor creates an account</a> setting, and is merely here for convenience).  If selected, users will be assigned to the role below. They will not be assigned to the 'authenticated user' role until they confirm their e-mail address by following the link in their registration e-mail. It is HIGHLY recommended that you set up a 'pre-authorized' role with limited permissions for this purpose. <br />NOTE: If you enable this feature, you should edit the <a href=\"!settings\">Welcome (no approval required)</a> text.", array('!settings' => url('admin/config/people/accounts'))) . $help_text,
  // Grab the roles that can be used for pre-auth.  Remove the anon role, as it's not a valid choice.
  $roles = user_roles(TRUE);
  $form ['registration']['logintoboggan_pre_auth_role'] = array(
    '#default_value' => variable_get('logintoboggan_pre_auth_role', DRUPAL_AUTHENTICATED_RID),
    '#description' => t('If "Set password" is selected, users will be able to login before their e-mail address has been authenticated. Therefore, you must choose a role for new non-authenticated users -- you may wish to <a href="!url">add a new role</a> for this purpose. Users will be removed from this role and assigned to the "authenticated user" role once they follow the link in their welcome e-mail. <strong>WARNING: changing this setting after initial site setup can cause undesirable results, including unintended deletion of users -- change with extreme caution!</strong>', array('!url' => url('admin/people/permissions/roles'))),
  );

  $purge_options = array(
    0 => t('Never delete'),
    86400 => t('1 Day'),
    172800 => t('2 Days'),
    259200 => t('3 Days'),
    345600 => t('4 Days'),
    432000 => t('5 Days'),
    518400 => t('6 Days'),
    604800 => t('1 Week'),
    1209600 => t('2 Weeks'),
    2592000 => t('1 Month'),
    7776000 => t('3 Months'),
    15379200 => t('6 Months'),
    30758400 => t('1 Year'),
  );

  $form['registration']['logintoboggan_purge_unvalidated_user_interval'] = array(
    '#type' => 'select',
    '#title' => t('Delete unvalidated users after'),
    '#options' => $purge_options,
    '#default_value' => variable_get('logintoboggan_purge_unvalidated_user_interval', 0),
    '#description' => t("If enabled, users that are still in the 'Non-authenticated role' set above will be deleted automatically from the system, if the set time interval since their initial account creation has passed. This can be used to automatically purge spambot registrations. Note: this requires cron, and also requires that the 'Set password' option above is enabled. <strong>WARNING: changing this setting after initial site setup can cause undesirable results, including unintended deletion of users -- change with extreme caution! (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature)</strong>")
  $form['registration']['logintoboggan_immediate_login_on_register'] = array(
Chad Phillips's avatar
Chad Phillips committed
    '#title' => t('Immediate login'),
    '#default_value' => variable_get('logintoboggan_immediate_login_on_register', TRUE),
Chad Phillips's avatar
Chad Phillips committed
    '#description' => t("If set, the user will be logged in immediately after registering. Note this only applies if the 'Set password' option above is enabled."),
  $form['registration']['redirect'] = array(
    '#type' => 'fieldset',
    '#title' => t('Redirections'),
    '#collapsible' => true,
    '#collapsed' => false,
  );

  $form['registration']['redirect']['logintoboggan_redirect_on_register'] = array(
    '#title' => t('Redirect path on registration'),
    '#default_value' => variable_get('logintoboggan_redirect_on_register', ''),
Chad Phillips's avatar
Chad Phillips committed
    '#description' => t('Normally, after a user registers a new account, they will be taken to the front page, or to their user page if you specify <cite>Immediate login</cite> above. Leave this setting blank if you wish to keep the default behavior. If you wish the user to go to a page of your choosing, then enter the path for it here. For instance, you may redirect them to a static page such as <cite>node/35</cite>, or to the <cite>&lt;front&gt;</cite> page. You may also use <em>%uid</em> as a variable, and the user\'s user ID will be substituted in the path.'),
  $form['registration']['redirect']['logintoboggan_redirect_on_confirm'] = array(
    '#title' => t('Redirect path on confirmation'),
    '#default_value' => variable_get('logintoboggan_redirect_on_confirm', ''),
    '#description' => t('Normally, after a user confirms their new account, they will be taken to their user page. Leave this setting blank if you wish to keep the default behavior. If you wish the user to go to a page of your choosing, then enter the path for it here. For instance, you may redirect them to a static page such as <cite>node/35</cite>, or to the <cite>&lt;front&gt;</cite> page. You may also use <em>%uid</em> as a variable, and the user\'s user ID will be substituted in the path. In the case where users are not creating their own passwords, it is suggested to use <cite>user/%uid/edit</cite> here, so the user may set their password immediately after validating their account.'),
  $form['registration']['redirect']['logintoboggan_override_destination_parameter'] = array(
    '#type' => 'checkbox',
    '#title' => t('Override destination parameter'),
    '#default_value' => variable_get('logintoboggan_override_destination_parameter', 1),
    '#description' => t("Normally, when a Drupal redirect is performed, priority is given to the 'destination' parameter from the originating URL. With this setting enabled, LoginToboggan will attempt to override this behavior with any values set above."),
  );
  $form['other'] = array('#type' => 'fieldset',
    '#title' => t('Other'),
    '#tree' => FALSE,

  $site403 = variable_get('site_403', '');
  if ($site403 == '') {
    $disabled = $default = '0';
  }
  elseif ($site403 == 'toboggan/denied') {
    $disabled = '0';
    $default = 'toboggan/denied';