Newer
Older
<?php
// $Id$
/**
* @todo
* _ Configurable text for theme_lt_access_denied()
Chad Phillips
committed
*
* _ clean up variable names
* _ unify the password page to just one field
* _ test with Drupal's distributed authentication (drupal.module)
*
*/
/**
* _ password complexity testing option
* _ options for minimum/maximum username/password length
* _ setting to expire unverified accounts and purge them from system
*
Chad Phillips
committed
*/
/**
* @defgroup logintoboggan_core Core drupal hooks
*/
/**
* Implementation of hook_help().
*/
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:
<ol>
Chad Phillips
committed
<li>Allow users to login using either their username OR their e-mail address.</li>
<li>Allow users to define their own password during registration.</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>
Chad Phillips
committed
<li>Customize the registration form with two e-mail fields to ensure accuracy.</li>
<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>
</ol>
These features may be turned on or off in the Login Toboggan <a href="%url">settings</a>.</p>
Chad Phillips
committed
<p>Because this module completely reorients the Drupal login process you will probably want to edit the welcome e-mail on the user settings page. For instance if you have enabled the "Set password & Immediate Login" option, you probably should not send the user\'s password out in the welcome e-mail (also note when the "Set password & Immediate Login" 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>
Chad Phillips
committed
', array('%url' => url('admin/user/logintoboggan')));
$output .= drupal_get_form('logintoboggan_example_help');
$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 & Immediate Login" 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 (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.');
return $output;
break;
case 'admin/user/logintoboggan':
$output = t('<p>Customize your login and registration system. More help can be found <a href="!url">here</a>.</p>', array('!url' => url('admin/help/logintoboggan')));
return $output;
}
}
/**
* Helper function for example user email textfield.
*/
function logintoboggan_example_help() {
$example = t('
Chad Phillips
committed
!username,
Chad Phillips
committed
Thank you for registering at !site.
IMPORTANT:
For full site access, you will need to click on this link or copy and paste it in your browser:
Chad Phillips
committed
!login_url
This will verify your account and log you into the site. In the future you will be able to log in using the username and password that you created during registration.
Chad Phillips
committed
Your new !site membership also enables to you to login to other Drupal powered websites (e.g. http://www.drupal.org/) without registering. Just use the following Drupal ID along with the password you\'ve chosen:
Chad Phillips
committed
Drupal ID: !username@!uri_brief
Chad Phillips
committed
-- !site team');
$form['foo'] = array(
'#type' => 'textarea',
'#default_value' => $example,
'#rows' => 15,
);
}
/**
* Implementation of hook_form_alter()
*
* @ingroup logintoboggan_core
*/
function logintoboggan_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
Chad Phillips
committed
case 'block_admin_configure':
if (($form['module']['#value'] == 'user') && ($form['delta']['#value'] == 0)) {
$form['#submit'][] = 'logintoboggan_user_block_admin_configure_submit';
$form['block_settings']['title']['#description'] = t('Override the default title for the block. Use <em><none></em> to display no title, or leave blank to use the default block title.<br \><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><none></em>');
$form['block_settings']['toboggan_block_type'] = array('#type' => 'radios',
Chad Phillips
committed
'#title' => t('Block type'),
'#default_value' => variable_get('toboggan_block_type', 1),
'#options' => array(t('Standard'), t('Link'), t('Collapsible Form')),
);
Chad Phillips
committed
$form['block_settings']['toboggan_block_msg'] = array('#type' => 'textarea',
'#title' => t('Set a custom message to appear at the top of the login block'),
Chad Phillips
committed
'#default_value' => variable_get('toboggan_block_msg', ''),
);
Chad Phillips
committed
}
break;
// This will reset the the site 403 variable to the default if the module is disabled and the toboggan redirect on acccess
// denied is enabled.
case 'system_modules':
Chad Phillips
committed
if ($_POST && !$_POST['status']['logintoboggan'] && (db_result(db_query("SELECT status FROM {system} WHERE name = 'logintoboggan'")) == 1) && (variable_get('site_403', '') == 'toboggan/denied')) {
variable_set('site_403', '');
}
break;
Chad Phillips
committed
case 'logintoboggan_main_settings':
$form['#submit'][] = 'logintoboggan_flip_user_email_verification';
Chad Phillips
committed
break;
Chad Phillips
committed
case 'user_edit':
$form['#validate'][] = 'logintoboggan_user_edit_validate';
$account = user_load(array('uid' => arg(1)));
Chad Phillips
committed
$id = logintoboggan_validating_id();
$in_pre_auth_role = in_array($id, array_keys($account->roles));
Chad Phillips
committed
// Messages aren't necessary if pre-auth role is authenticated user.
if ($in_pre_auth_role && user_access('administer users') && $id != DRUPAL_AUTHENTICATED_RID) {
Chad Phillips
committed
if ((variable_get('user_register', 1) == 2)) {
$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.');
Chad Phillips
committed
}
break;
case 'user_login':
case 'user_login_block':
//Grab the message from settings if there is one to display at the top of the login block.
if ($login_msg = variable_get('toboggan_block_msg', '')) {
Chad Phillips
committed
$form['message'] = array('#value' => filter_xss_admin($login_msg),
'#weight' => -50,
);
}
$form['name']['#attributes'] = array('tabindex' => '1');
$form['pass']['#attributes'] = array('tabindex' => '2');
$form['submit']['#attributes'] = array('tabindex' => '3');
if (variable_get('login_with_mail', 0)) {
// LT's validation function must run first.
$form['#validate'] = array('logintoboggan_user_login_validate') + $form['#validate'];
$form['name']['#title'] = t('Username or e-mail address');
if (variable_get('drupal_authentication_service', FALSE) && count(user_auth_help_links()) > 0) {
$form['name']['#description'] = t('Enter your %s username, e-mail address, or an ID from one of our affiliates: !a.', array('%s' => variable_get('site_name', 'local'), '!a' => implode(', ', user_auth_help_links())));
}
if($GLOBALS['logintoboggan_denied'] == TRUE){
$form['#redirect'] = logintoboggan_destination();
Chad Phillips
committed
if (($form_id == 'user_login_block')) {
$block_type = variable_get('toboggan_block_type', 1);
if ($block_type == 1) {
$form = array('#value' => l(t('Login/Register'), 'user/login', array('query' => drupal_get_destination())));
}
elseif ($block_type == 2) {
$form = _logintoboggan_toggleboggan($form);
}
Chad Phillips
committed
}
break;
Chad Phillips
committed
case 'user_register':
// Admin created account aren't processed by the module.
if (user_access('administer users')) {
break;
}
$mail = variable_get('email_reg_confirm', 0);
Chad Phillips
committed
$pass = !variable_get('user_email_verification', TRUE);
// Replace core's registration function with LT's registration function.
$key = array_search('user_register_submit', $form['#submit']);
if ($key !== FALSE) {
unset($form['#submit'][$key]);
}
$form['#submit'][] = 'logintoboggan_user_register_submit';
if ($mail || $pass) {
$form['#validate'][] = 'logintoboggan_user_register_validate';
Chad Phillips
committed
Chad Phillips
committed
//Display a confirm e-mail address box if option is enabled.
if ($mail) {
Chad Phillips
committed
$form['conf_mail'] = array('#type' => 'textfield',
Chad Phillips
committed
'#title' => t('Confirm e-mail address'),
Chad Phillips
committed
'#weight' => -28,
Chad Phillips
committed
'#maxlength' => 64,
Chad Phillips
committed
'#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, then pass
if (isset($form['account'])) {
$form['account']['#weight'] = -50; // Make sure account form group is at the top of the display.
Chad Phillips
committed
$form['account']['user_registration_help']['#weight'] = -40;
$form['account']['name']['#weight'] = -30;
$form['account']['mail']['#weight'] = -29;
$form['account']['conf_mail'] = $form['conf_mail'];
unset($form['conf_mail']);
$form['account']['conf_mail']['#weight'] = -28;
}
else {
Chad Phillips
committed
$form['user_registration_help']['#weight'] = -40;
$form['name']['#weight'] = -30;
$form['mail']['#weight'] = -29;
}
Chad Phillips
committed
if ($pass) {
$min_pass = variable_get('toboggan_min_pass_length', 0);
$length = $min_pass ? t('between !min and', array('!min' => $min_pass)) : t('no more than');
$form['pass']['#description'] = t('Please choose a password for your account; it must be !length 30 characters and spaces are not allowed.', array('!length' => $length));
}
}
break;
}
}
/**
* Custom submit function for user registration form
*
* @ingroup logintoboggan_form
*/
function logintoboggan_user_register_submit($form, &$form_state) {
global $base_url, $language;
Chad Phillips
committed
$from = variable_get('site_mail', ini_get('sendmail_from'));
Chad Phillips
committed
$reg_pass_set = !variable_get('user_email_verification', TRUE);
Chad Phillips
committed
// 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;
Chad Phillips
committed
// If we are allowing user selected passwords then skip the auto-generate function
Chad Phillips
committed
// The new user's status should default to the site settings, unless reg_passwd_set == 1
Chad Phillips
committed
// (immediate login, we are going to assign a pre-auth role), and we want to allow
// admin approval accounts access to the site.
Chad Phillips
committed
if ($reg_pass_set) {
$pass = $form_state['values']['pass'];
Chad Phillips
committed
$status = 1;
}
else {
$pass = user_password();
Chad Phillips
committed
$status = variable_get('user_register', 1) == 1;
}
Chad Phillips
committed
// 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']); }
if (array_intersect(array_keys($form_state['values']), array('uid', 'roles', 'init', 'session', 'status'))) {
watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
Chad Phillips
committed
return 'user/register';
}
// 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)) {
$roles[$validating_id] = 1;
}
$account = user_save('', array_merge($form_state['values'], array('pass' => $pass, 'init' => $form_state['values']['mail'], 'roles' => $roles, 'status' => $status)));
$account->password = $pass;
watchdog('user', 'New user: %name %email.', array('%name' => $account->name, '%email' => "<$account->mail>"), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));
Chad Phillips
committed
$login_url = variable_get('user_register', 1) == 1 ? logintoboggan_eml_validate_url($account) : user_pass_reset_url($account);
$tokens = user_mail_tokens($account, $language);
// Customize special tokens.
$tokens['!uri_brief'] = substr($base_url, strlen(_logintoboggan_protocol() .'://'));
$tokens['!login_url'] = $login_url;
Chad Phillips
committed
//compose the appropriate user message--admin approvals don't require a validation email
Chad Phillips
committed
if($reg_pass_set && variable_get('user_register', 1) == 1) {
Chad Phillips
committed
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 = '';
}
Chad Phillips
committed
} else {
$message = t('Your password and further instructions have been sent to your e-mail address.');
}
Chad Phillips
committed
if (variable_get('user_register', 1) == 1) {
Chad Phillips
committed
Chad Phillips
committed
// Create new user account, no administrator approval required.
$subject = _user_mail_text('welcome_subject', $tokens);
$body = _user_mail_text('welcome_body', $tokens);
$mailkey = 'user-register-welcome';
Chad Phillips
committed
Chad Phillips
committed
} elseif (variable_get('user_register', 1) == 2) {
Chad Phillips
committed
Chad Phillips
committed
// Create new user account, administrator approval required.
$subject = _user_mail_text('approval_subject', $tokens);
$body = _user_mail_text('approval_body', $tokens);
$mailkey = 'user-register-approval-user';
Chad Phillips
committed
Chad Phillips
committed
$message = t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />') . $message;
Chad Phillips
committed
if ($reg_pass_set) {
$admin_tokens = array('!validating_url' => logintoboggan_eml_validate_url($account) .'/admin') + $tokens;
$admin_body = t("!username has applied for an account, and has automatically received the permissions of the LoginToboggan validating role. To give the user full site permissions, click the link below:\n\n!validating_url\n\nAlternatively, you may visit their user account listed below and remove them from the validating role.\n\n!uri", $admin_tokens);
Chad Phillips
committed
}
else {
$admin_body =t("!username has applied for an account.\n\n!uri", $tokens);
Chad Phillips
committed
}
drupal_mail('user-register-approval-admin', $from, $subject, $admin_body, $from);
Chad Phillips
committed
}
Chad Phillips
committed
Chad Phillips
committed
//mail the user.
drupal_mail($mailkey, $account->mail, $subject, $body, $from);
Chad Phillips
committed
drupal_set_message($message);
Chad Phillips
committed
Chad Phillips
committed
// where do we need to redirect after registration?
Chad Phillips
committed
$redirect = _logintoboggan_process_redirect(variable_get('toboggan_redirect_on_register', ''), $account);
Chad Phillips
committed
// Log the user in if they created the account and immediate login is enabled.
Chad Phillips
committed
if($reg_pass_set) {
$form_state['redirect'] = logintoboggan_process_login($account, $redirect);
}
else {
// Redirect to the appropriate page.
$form_state['redirect'] = $redirect;
Chad Phillips
committed
}
}
/**
* Custom validation for user login form
*
* @ingroup logintoboggan_form
*/
function logintoboggan_user_login_validate($form, &$form_state) {
if (isset($form_state['values']['name'])) {
if ($name = db_result(db_query("SELECT name FROM {users} WHERE LOWER(mail) = LOWER('%s')", $form_state['values']['name']))) {
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) {
if (variable_get('login_with_mail', 0)) {
Chad Phillips
committed
// check that it's not an e-mail
if (db_result(db_query("SELECT uid FROM {users} WHERE LOWER(mail) = LOWER('%s') AND uid <> 0", $form_state['values']['name']))) {
Chad Phillips
committed
form_set_error('name', t('This e-mail address has already been taken by another user.'));
}
}
Chad Phillips
committed
//Check to see whether our e-mail address matches the confirm address if enabled.
if (variable_get('email_reg_confirm', 0)) {
if ($form_state['values']['mail'] != $form_state['values']['conf_mail']) {
Chad Phillips
committed
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.
Chad Phillips
committed
if (!variable_get('user_email_verification', TRUE)) {
$pass_err = logintoboggan_validate_pass($form_state['values']['pass']);
Chad Phillips
committed
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) {
if (strlen($form_state['values']['pass'])) {
Chad Phillips
committed
// if we're changing the password, validate it
$pass_err = logintoboggan_validate_pass($form_state['values']['pass']);
if ($pass_err) {
Chad Phillips
committed
form_set_error('pass', $pass_err);
}
}
}
Chad Phillips
committed
/**
* Implementation of hook_init()
*
* @ingroup logintoboggan_core
*/
function logintoboggan_init() {
global $user;
Chad Phillips
committed
// 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');
Chad Phillips
committed
}
/**
* 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) {
Chad Phillips
committed
$id = logintoboggan_validating_id();
Chad Phillips
committed
$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]);
Chad Phillips
committed
}
}
}
/**
* Implementation of hook_menu()
*
* @ingroup logintoboggan_core
*/
function logintoboggan_menu() {
$items = array();
// Settings page.
$items['admin/user/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'] = array(
'title' => 'Validate e-mail address',
'page callback' => 'logintoboggan_validate_email',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
// 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'] = 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,
);
return $items;
}
/**
* Access check for user revalidation.
*/
function logintoboggan_revalidate_access($uid) {
global $user;
return $user->uid == $uid;
}
/**
* Implemenation of hook_theme().
*/
function logintoboggan_theme() {
return array(
'lt_access_denied' => array(
'arguments' => array(),
),
'lt_loggedinblock' => array(
'arguments' => array(),
),
);
}
/**
* @defgroup logintoboggan_block Functions for LoginToboggan blocks.
*/
function logintoboggan_user_block_admin_configure_submit($form, &$form_state) {
variable_set('toboggan_block_type', $form_state['values']['toboggan_block_type']);
variable_set('toboggan_block_msg', $form_state['values']['toboggan_block_msg']);
}
Chad Phillips
committed
/**
* Implementation of hook_block
*/
function logintoboggan_block($op = 'list', $delta = 0, $edit = array()) {
global $user;
switch ($op) {
case 'list' :
$blocks[0]['info'] = t('LoginToboggan logged in block');
$blocks[0]['cache'] = BLOCK_NO_CACHE;
return $blocks;
break;
case 'view' :
$block = array();
switch ($delta) {
case 0:
if ($user->uid) {
$block['content'] = theme('lt_loggedinblock');
}
return $block;
}
break;
}
}
/**
* Custom theme function for defining what gets displayed for logged in users.
*
*/
function theme_lt_loggedinblock(){
global $user;
Chad Phillips
committed
return check_plain($user->name) .' | ' . l(t('Log out'), 'logout');
}
/**
* User login block with JavaScript to expand
Chad Phillips
committed
*
* this should really be themed
*
Chad Phillips
committed
* @return array
* the reconstituted user login block
*/
Chad Phillips
committed
function _logintoboggan_toggleboggan ($form) {
Chad Phillips
committed
drupal_add_js(_logintoboggan_toggleboggan_js(), 'inline');
Chad Phillips
committed
$pre = '<div id="toboggan-container" class="toboggan-container">';
$pre .= '<div class="toboggan-login-link">';
$pre .= l(t('Login/Register'), 'user/login', array('onclick' => "toggleboggan();this.blur();return false;"));
Chad Phillips
committed
$pre .= '</div>';
//the block that will be toggled
$pre .= '<div id="toboggan-login" class="user-login-block">';
Chad Phillips
committed
$form['pre'] = array('#value' => $pre, '#weight' => -300);
$form['post'] = array('#value' => '</div></div>', '#weight' => 300);
Chad Phillips
committed
return $form;
}
function _logintoboggan_toggleboggan_js() {
return '
$(function() {
$("#toboggan-login").hide();
}
);
function toggleboggan() {
$("#toboggan-login").toggle();
function logintoboggan_main_settings() {
$version .= str_replace(array('$Re'.'vision:', '$Da'.'te:', '$'), array('', '', ''), '<p style="font-size:x-small">Login Toboggan version: <b>$Revision$</b>, $Date$</p>');
$_disabled = t('disabled');
$_enabled = t('enabled');
Chad Phillips
committed
$form['login'] = array('#type' => 'fieldset',
'#title' => t('Login'),
'#prefix' => $version,
);
Chad Phillips
committed
$form['login']['login_with_mail'] = array('#type' => 'radios',
Chad Phillips
committed
'#title' => t('Allow users to login using their e-mail address'),
Chad Phillips
committed
'#default_value' => variable_get('login_with_mail', 0),
'#options' => array($_disabled, $_enabled),
'#description' => t('Users will be able to enter EITHER their username OR their e-mail address to log in. NOTE: This will disallow users from registering using an e-mail address as their username.'),
);
Chad Phillips
committed
$form['registration'] = array('#type' => 'fieldset',
'#title' => t('Registration'),
);
Chad Phillips
committed
$form['registration']['email_reg_confirm'] = array('#type' => 'radios',
Chad Phillips
committed
'#title' => t('Use two e-mail fields on registration form'),
Chad Phillips
committed
'#default_value' => variable_get('email_reg_confirm', 0),
'#options' => array($_disabled, $_enabled),
Chad Phillips
committed
'#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.'),
);
Chad Phillips
committed
$form['registration']['user_email_verification'] = array('#type' => 'checkbox',
'#title' => t('Set password & Immediate login'),
'#default_value' => !variable_get('user_email_verification', TRUE) ? 1 : 0,
'#description' => t('This will allow users to choose their initial password when registering. If \'Set password & Immediate login\' is selected, users will be assigned to the role below and logged in immediately. 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 !settings--more help in writing the e-mail message can be found at !help.', array('!settings' => l('user e-mail welcome message', 'admin/user/settings'), '!help' => l('logintoboggan help', 'admin/help/logintoboggan'))),
);
Chad Phillips
committed
// Grab the roles that can be used for pre-auth. Remove the anon role, as it's not a valid choice.
Chad Phillips
committed
Chad Phillips
committed
$form ['registration']['toboggan_role'] = array('#type' => 'select',
'#title' => t('Non-authenticated role'),
Chad Phillips
committed
'#options' => $roles,
'#default_value' => variable_get('toboggan_role', 2),
'#description' => t('If "Set password & Immediate login" 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. Users will be removed from this role and assigned to the "authenticated user" role once they follow the link in their welcome e-mail. <a href="!url">Add new roles</a>.', array('!url' => url('admin/user/roles'))),
);
Chad Phillips
committed
$form['registration']['redirect'] = array(
'#type' => 'fieldset',
'#title' => t('Redirections'),
'#collapsible' => true,
'#collapsed' => false,
);
$form['registration']['redirect']['toboggan_redirect_on_register'] = array(
'#type' => 'textfield',
'#title' => t('Redirect path on Registration'),
'#default_value' => variable_get('toboggan_redirect_on_register', ''),
'#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><front></cite> page. You may also use <em>%uid</em> as a variable, and the user\'s user ID will be substituted in the path.'),
Chad Phillips
committed
);
$form['registration']['redirect']['toboggan_redirect_on_confirm'] = array(
'#type' => 'textfield',
'#title' => t('Redirect path on Confirmation'),
'#default_value' => variable_get('toboggan_redirect_on_confirm', ''),
Chad Phillips
committed
'#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><front></cite> page. You may also use <em>%uid</em> as a variable, and the user\'s user ID will be substituted in the path.'),
Chad Phillips
committed
);
Chad Phillips
committed
$form['other'] = array('#type' => 'fieldset',
'#title' => t('Other'),
'#tree' => FALSE,
);
$site403 = variable_get('site_403', '');
if ($site403 == 'toboggan/denied'){
$disabled = '';
}
else {
$disabled = $site403;
}
$options = array($disabled => $_disabled, 'toboggan/denied' => $_enabled);
$form['other']['site_403'] = array(
'#type' => 'radios',
'#title' => t('Present login form on access denied (403)'),
'#options' => $options,
'#default_value' => $site403,
'#description' => t('Anonymous users will be presented with a login form along with an access denied message.')
);
$form['other']['login_successful'] = array(
'#type' => 'radios',
'#title' => t('Display login successful message'),
'#options' => array($_disabled, $_enabled),
'#default_value' => variable_get('login_successful', 0),
'#description' => t('If enabled, users will receive a \'Login successful\' message upon login.')
);
Chad Phillips
committed
$min_pass_options = array(t('None'));
for ($i = 2; $i < 30; $i++) {
$min_pass_options[$i] = $i;
}
$form['other']['toboggan_min_pass_length'] = array(
'#type' => 'select',
'#title' => t('Minimum password length'),
'#options' => $min_pass_options,
'#default_value' => variable_get('toboggan_min_pass_length', 0),
'#description' => t('LoginToboggan automatically performs basic password validation for illegal characters. If you would additionally like to have a mimimum password length requirement, select the length here, or set to \'None\' for no password length validation.')
);
}
function logintoboggan_denied() {
global $user;
if ($user->uid == 0) {
Chad Phillips
committed
global $logintoboggan_denied;
$logintoboggan_denied = TRUE;
Chad Phillips
committed
// build the user menu item as the 403 page content, adjust the page title appropriately, and warn
// the user that they were denied access.
menu_set_active_item('user');
$return = menu_execute_active_handler();
drupal_set_title(t('Access Denied / User Login'));
drupal_set_message(t('Access denied. You may need to login below or register to access this page.'), 'error');
}
else {
drupal_set_title(t('Access Denied'));
$return = theme('lt_access_denied');
}
return $return;
}
// Themeable function so that the access denied message can be customized
function theme_lt_access_denied() {
return t('You are not authorized to access this page.');
}
// slight rewrite of drupal_get_destination()
// with custom 403, drupal_get_destination() would return toboggan/denied
// which would show 'Access Denied' after login... what good is that!?
function logintoboggan_destination() {
Chad Phillips
committed
// Drupal has reset $_GET[q], so we need a workaround. Start with home page,
// then try to determine the correct destination.
$destination = variable_get('site_frontpage', 'node');
Chad Phillips
committed
if ($internal_path = substr(request_uri(), strlen(base_path()))) {
$uriarray = explode('/', $internal_path);
if (!variable_get('clean_url', 0)) {
$uriarray[0] = str_replace('?q=', '', $uriarray[0]);
}
$destination = implode('/', $uriarray);
Chad Phillips
committed
Chad Phillips
committed
return $destination;
}
/**
* Modified version of user_validate_name
Chad Phillips
committed
* - validates user submitted passwords have a certain length and only contain letters, numbers or punctuation (graph character class in regex)
*/
function logintoboggan_validate_pass($pass) {
if (!strlen($pass)) return t('You must enter a password.');
if (ereg(' ', $pass)) return t('The password cannot contain spaces.');
Chad Phillips
committed
if (ereg("[^\x80-\xF7[:graph:]]", $pass)) return t('The password contains an illegal character.');
if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP
'\x{AD}'. // Soft-hyphen
'\x{2000}-\x{200F}'. // Various space characters
'\x{2028}-\x{202F}'. // Bidirectional text overrides
'\x{205F}-\x{206F}'. // Various text hinting characters
'\x{FEFF}'. // Byte order mark
'\x{FF01}-\x{FF60}'. // Full-width latin
'\x{FFF9}-\x{FFFD}]/u', // Replacement characters
$pass)) {
return t('The password contains an illegal character.');
}
if (strlen($pass) > 30) return t('The password is too long: it must be less than 30 characters.');
Chad Phillips
committed
$min_pass_length = variable_get('toboggan_min_pass_length', 0);
if ($min_pass_length && strlen($pass) < $min_pass_length) return t("The password is too short: it must be at least %min_length characters.", array('%min_length' => $min_pass_length));
}
/**
Chad Phillips
committed
* Modified version of $DRUPAL_AUTHENTICATED_RID
* - gets the role id for the "validating" user role.
*/
function logintoboggan_validating_id() {
Chad Phillips
committed
return variable_get('toboggan_role', 2);
}
/**
Chad Phillips
committed
* Menu callback; process validate the e-mail address as a one time URL,
* and redirects to the user page on success.
*/
Chad Phillips
committed
function logintoboggan_validate_email($uid, $timestamp, $hashed_pass, $action = 'login') {
$current = time();
// Some redundant checks for extra security
Chad Phillips
committed
if ($timestamp < $current && is_numeric($uid) && $account = user_load(array('uid' => $uid)) ) {
// No time out for first time login.
if ($account->uid && !empty($account) && $timestamp < $current &&
$hashed_pass == logintoboggan_eml_rehash($account->pass, $timestamp, $account->mail)) {
watchdog('user', 'E-mail validation URL used for %name with timestamp @timestamp.', array('%name' => $account->name, '@timestamp' => $timestamp));
// Update the user table noting user has logged in.
// And this also makes this hashed password a one-time-only login.
db_query("UPDATE {users} SET login = '%d' WHERE uid = %d", time(), $account->uid);
Chad Phillips
committed
Chad Phillips
committed
// 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;
Chad Phillips
committed
// Remove the pre-auth role from the user, unless they haven't been approved yet.
if ($account->status) {
Chad Phillips
committed
if ($pre_auth) {
db_query("DELETE FROM {users_roles} WHERE uid = %d AND rid = %d", $account->uid, logintoboggan_validating_id());
}
// Allow other modules to react to email validation by invoking the user update hook.
$edit = array();
$account->logintoboggan_email_validated = TRUE;
user_module_invoke('update', $edit, $account);
Chad Phillips
committed
}
Chad Phillips
committed
// Where do we redirect after confirming the account?
Chad Phillips
committed
$redirect = _logintoboggan_process_redirect(variable_get('toboggan_redirect_on_confirm', ''), $account);
Chad Phillips
committed
Chad Phillips
committed
switch ($action) {
Chad Phillips
committed
// Proceed with normal user login, as long as it's open registration and their
// account hasn't been blocked.
Chad Phillips
committed
case 'login':
Chad Phillips
committed
// Only show the validated message if there's a valid pre-auth role.
if ($pre_auth) {
drupal_set_message(t('You have successfully validated your e-mail address.'));
}
Chad Phillips
committed
if (!$account->status) {
drupal_set_message(t('Your account is currently blocked -- login cancelled.'), 'error');
drupal_goto('');
}
else {
drupal_goto(logintoboggan_process_login($account, $redirect));
Chad Phillips
committed
}
Chad Phillips
committed
break;
// Admin validation.
case 'admin':
// user has new permissions, so we clear their menu cache
cache_clear_all($account->uid .':', 'cache_menu', TRUE);
drupal_set_message(t('You have successfully validated %user.', array('%user' => $account->name)));
drupal_goto("user/$account->uid/edit");
break;
// Catch all.
default:
// user has new permissions, so we clear their menu cache
cache_clear_all($account->uid .':', 'cache_menu', TRUE);
drupal_set_message(t('You have successfully validated %user.', array('%user' => $account->name)));
drupal_goto('');
break;
}
Chad Phillips
committed
else {
drupal_set_message(t("Sorry, you can only use your validation link once for security reasons. Please !login with your username and password instead now.", array('!login' => l(t('login'),'user/login'))),'error');
Chad Phillips
committed
}
Chad Phillips
committed
// Deny access, no more clues.
// Everything will be in the watchdog's URL for the administrator to check.
drupal_access_denied();
}
/**
* Actually log the user on
*
* @param object $account
*/
Chad Phillips
committed
function logintoboggan_process_login($account, $redirect = ''){
global $user;
$user = $account;
watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
// Update the user table timestamp noting user has logged in.
db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $user->uid);
// user has new permissions, so we clear their menu cache
Chad Phillips
committed
cache_clear_all($user->uid .':', 'cache_menu', TRUE);
user_module_invoke('login', $edit, $user);
Chad Phillips
committed
// In the special case where a user is validating but they did not create their
// own password, redirect them to the user edit page, with a final destination
// of the confirmation page, if it exists.
if (variable_get('user_email_verification', TRUE)) {
watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $user->name, '%timestamp' => time()));
Chad Phillips
committed
drupal_set_message(t('You have just used your one-time login link. It is no longer necessary to use this link to login. Please change your password.'));
$destination = $redirect ? "destination=$redirect" : NULL;
drupal_goto('user/'. $user->uid .'/edit', $destination);
}
Chad Phillips
committed
if ($redirect != '') {
Chad Phillips
committed
return $redirect;
Chad Phillips
committed
}
Chad Phillips
committed
return 'user/'. $user->uid;
}
Chad Phillips
committed
function logintoboggan_eml_validate_url($account){
$timestamp = time();
return url("user/validate/$account->uid/$timestamp/". logintoboggan_eml_rehash($account->pass, $timestamp, $account->mail), array('absolute' => TRUE));
}
function logintoboggan_eml_rehash($password, $timestamp, $mail){
return md5($timestamp . $password . $mail);
Chad Phillips
committed
}
/**
* Implementation of hook_user().
*/
function logintoboggan_user($op, &$edit, &$user_edit, $category = NULL) {
global $user;
if ($op == 'form' && $category == 'account' && $user->uid == arg(1)) {
// User is editing their own account settings
Chad Phillips
committed
if (!variable_get('user_email_verification', TRUE) && array_key_exists(logintoboggan_validating_id(), $user_edit->roles) && variable_get('user_register', 1) == 1) {
Chad Phillips
committed
// User is still in pre-authorized role; display link to re-send e-mail.
$form['revalidate'] = array(
'#type' => 'fieldset',
'#title' => t('Account validation'),
'#weight' => -10,
);
$form['revalidate']['revalidate_link'] = array(
'#value' => l(t('re-send validation e-mail'), 'toboggan/revalidate/'. $user_edit->uid),
);
return $form;
}
} elseif ($op == 'login' && variable_get('login_successful', 0)) {
drupal_set_message(t('Login successful.'));
Chad Phillips
committed
}
Chad Phillips
committed
elseif ($op == 'load') {
// Just loaded the user into $user_edit.
// If the user has the pre-auth role, unset the authenticated role
_logintoboggan_user_roles_alter($user_edit);
}
Chad Phillips
committed
}
/**
* Re-sends validation e-mail to user specified by $uid.
*/
function logintoboggan_resend_validation($uid) {
global $base_url, $language;
Chad Phillips
committed
$account = user_load(array('uid' => $uid));
$account->password = t('If required, you may reset your password from: !url', array('!url' => url('user/password', array('absolute' => TRUE))));
Chad Phillips
committed
$tokens = user_mail_tokens($account, $language);
// Customize special tokens.
$tokens['!uri_brief'] = substr($base_url, strlen(_logintoboggan_protocol() .'://'));
$tokens['!login_url'] = logintoboggan_eml_validate_url($account);
Chad Phillips
committed
// Prepare and send e-mail.
$from = variable_get('site_mail', ini_get('sendmail_from'));
$subject = _user_mail_text('welcome_subject', $tokens);
$body = _user_mail_text('welcome_body', $tokens);
drupal_mail('logintoboggan-resend-validation', $account->mail, $subject, $body, $from);
Chad Phillips
committed
// Notify user that e-mail was sent and return to user edit form.
Chad Phillips
committed
drupal_set_message(t('A validation e-mail has been sent to your e-mail address. You will need to follow the instructions in that message in order to gain full access to the site.'));
Chad Phillips
committed
drupal_goto('user/'. $account->uid .'/edit');
}
function _logintoboggan_protocol() {
return (($_SERVER['HTTPS'] == 'on') ? 'https' : 'http');
Chad Phillips
committed
}
Chad Phillips
committed
function _logintoboggan_process_redirect($redirect, $account) {
$variables = array('%uid' => $account->uid);
$redirect = strtr($redirect, $variables);
Chad Phillips
committed
Chad Phillips
committed
return $redirect;
Chad Phillips
committed
}
Chad Phillips
committed
Chad Phillips
committed
/**
* Flips the value of the user_email_settings variable. This setting is less confusing when it works the opposite
* of it's current core behavior.
*/
function logintoboggan_flip_user_email_verification($form, &$form_state) {
$value = $form_state['values']['user_email_verification'] ? FALSE : TRUE;
Chad Phillips
committed
variable_set('user_email_verification', $value);