2 // $Id: logintoboggan.module,v 1.133.2.9 2009/03/21 12:09:20 thehunmonkgroup Exp $
8 * This module enhances the configuration abilities of Drupal's default login system.
22 * @defgroup logintoboggan_core Core drupal hooks
26 * Implementation of hook_cron().
28 function logintoboggan_cron() {
29 // If set password is enabled, and a purge interval is set, check for
30 // unvalidated users to purge.
31 if (($purge_interval = variable_get('logintoboggan_purge_unvalidated_user_interval', 0)) && !variable_get('user_email_verification', TRUE)) {
32 $validating_id = logintoboggan_validating_id();
33 // As a safety check, make sure that we have a non-core role as the
34 // pre-auth role -- otherwise skip.
35 if ($validating_id > DRUPAL_AUTHENTICATED_RID) {
36 $purge_time = time() - $purge_interval;
37 $accounts = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid WHERE ur.rid = %d AND u.access < %d", $validating_id, $purge_time);
39 $purged_users = array();
40 // Delete the users from the system.
41 while ($account = db_fetch_object($accounts)) {
42 user_delete(array(), $account->uid);
43 $purged_users[] = check_plain($account->name);
46 // Log the purged users.
47 if (!empty($purged_users)) {
48 watchdog('logintoboggan', 'Purged the following unvalidated users: !purged_users', array('!purged_users' => theme('item_list', $purged_users)));
55 * Implementation of hook_help().
57 function logintoboggan_help($path, $arg) {
59 case 'admin/help#logintoboggan':
60 $output = t("<p>The Login Toboggan module improves the Drupal login system by offering the following features:
62 <li>Allow users to login using either their username OR their e-mail address.</li>
63 <li>Allow users to login immediately.</li>
64 <li>Provide a login form on Access Denied pages for non-logged-in (anonymous) users.</li>
65 <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>
66 <li>Customize the registration form with two e-mail fields to ensure accuracy.</li>
67 <li>Optionally redirect the user to a specific page when using the 'Immediate login' feature.</li>
68 <li>Optionally redirect the user to a specific page upon validation of their e-mail address.</li>
69 <li>Optionally display a user message indicating a successful login.</li>
71 These features may be turned on or off in the Login Toboggan <a href=\"!url\">settings</a>.</p>
72 <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>
73 ", array('!url' => url('admin/user/logintoboggan'), '!user_settings' => url('admin/user/settings')));
74 $output .= drupal_get_form('logintoboggan_example_help');
75 $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.");
78 case 'admin/user/logintoboggan':
79 $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')));
86 * Helper function for example user e-mail textfield.
88 function logintoboggan_example_help() {
92 Thank you for registering at !site.
95 For full site access, you will need to click on this link or copy and paste it in your browser:
99 This will verify your account and log you into the site. In the future you will be able to log in to !login_uri using the username and password that you created during registration:
102 $form['foo'] = array(
103 '#type' => 'textarea',
104 '#default_value' => $example,
112 * Implementation of hook_form_alter()
114 * @ingroup logintoboggan_core
116 function logintoboggan_form_alter(&$form, $form_state, $form_id) {
118 case 'block_admin_configure':
119 if (($form['module']['#value'] == 'user') && ($form['delta']['#value'] == 0)) {
120 $form['#submit'][] = 'logintoboggan_user_block_admin_configure_submit';
122 $form['block_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><none></em>.') .'</div>';
124 $form['block_settings']['logintoboggan_login_block_type'] = array('#type' => 'radios',
125 '#title' => t('Block type'),
126 '#default_value' => variable_get('logintoboggan_login_block_type', 0),
127 '#options' => array(t('Standard'), t('Link'), t('Collapsible form')),
128 '#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."),
131 $form['block_settings']['logintoboggan_login_block_message'] = array('#type' => 'textarea',
132 '#title' => t('Set a custom message to appear at the top of the login block'),
133 '#default_value' => variable_get('logintoboggan_login_block_message', ''),
138 // This will reset the the site 403 variable to the default if the module is
139 // disabled and the toboggan redirect on access denied is enabled.
140 case 'system_modules':
141 $form['#validate'][] = 'logintoboggan_site_403_validate';
143 case 'logintoboggan_main_settings':
144 $form['#submit'][] = 'logintoboggan_flip_user_email_verification';
147 case 'user_profile_form':
148 $form['#validate'][] = 'logintoboggan_user_edit_validate';
149 $account = user_load(array('uid' => arg(1)));
150 $id = logintoboggan_validating_id();
151 $in_pre_auth_role = in_array($id, array_keys($account->roles));
152 // Messages aren't necessary if pre-auth role is authenticated user.
153 if ($in_pre_auth_role && user_access('administer users') && $id != DRUPAL_AUTHENTICATED_RID) {
154 if ((variable_get('user_register', 1) == 2)) {
155 $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!');
157 $form['account']['roles']['#description'] = t("The user is assigned LoginToboggan's pre-authorized role, and is not currently receiving authenticated user permissions.");
162 case 'user_login_block':
163 // Grab the message from settings for display at the top of the login block.
164 if ($login_msg = variable_get('logintoboggan_login_block_message', '')) {
165 $form['message'] = array(
166 '#value' => filter_xss_admin($login_msg),
170 $form['name']['#attributes']['tabindex'] = '1';
171 $form['pass']['#attributes']['tabindex'] = '2';
172 $form['submit']['#attributes']['tabindex'] = '3';
173 if (variable_get('logintoboggan_login_with_email', 0)) {
174 // LT's validation function must run first.
175 $form['#validate'] = array('logintoboggan_user_login_validate') + $form['#validate'];
176 // Use theme functions to print the username field's textual labels.
177 $form['name']['#title'] = theme('lt_username_title', $form_id);
178 $form['name']['#description'] = theme('lt_username_description', $form_id);
179 // Use theme functions to print the password field's textual labels.
180 $form['pass']['#title'] = theme('lt_password_title', $form_id);
181 $form['pass']['#description'] = theme('lt_password_description', $form_id);
183 if(isset($GLOBALS['logintoboggan_denied']) && $GLOBALS['logintoboggan_denied'] == TRUE) {
184 logintoboggan_destination();
187 if (($form_id == 'user_login_block')) {
188 $block_type = variable_get('logintoboggan_login_block_type', 0);
189 if ($block_type == 1) {
190 $form = array('#value' => l(theme('lt_login_link'), 'user/login', array('query' => drupal_get_destination())));
192 elseif ($block_type == 2) {
193 $form = _logintoboggan_toggleboggan($form);
199 case 'user_register':
200 // Admin created account aren't processed by the module.
201 if (user_access('administer users')) {
204 $mail = variable_get('logintoboggan_confirm_email_at_registration', 0);
205 $pass = !variable_get('user_email_verification', TRUE);
207 // Replace core's registration function with LT's registration function.
208 // Put the LT submit handler first, so other submit handlers have a valid
209 // user to work with upon registration.
210 $key = array_search('user_register_submit', $form['#submit']);
211 if ($key !== FALSE) {
212 unset($form['#submit'][$key]);
214 $form['#submit'] = array('logintoboggan_user_register_submit') + $form['#submit'];
216 if ($mail || $pass) {
217 $form['#validate'][] = 'logintoboggan_user_register_validate';
219 //Display a confirm e-mail address box if option is enabled.
221 // Make sure user help is at the top of the form.
222 $form['user_registration_help']['#weight'] = -100;
224 $form['conf_mail'] = array('#type' => 'textfield',
225 '#title' => t('Confirm e-mail address'),
228 '#description' => t('Please re-type your e-mail address to confirm it is accurate.'),
232 // Weight things properly so that the order is name, mail, conf_mail, then pass
233 if (isset($form['account'])) {
234 $form['account']['#weight'] = -50; // Make sure account form group is at the top of the display.
235 $form['account']['name']['#weight'] = -30;
236 $form['account']['mail']['#weight'] = -29;
237 $form['account']['conf_mail'] = $form['conf_mail'];
238 unset($form['conf_mail']);
239 $form['account']['conf_mail']['#weight'] = -28;
242 $form['name']['#weight'] = -30;
243 $form['mail']['#weight'] = -29;
247 $min_pass = variable_get('logintoboggan_minimum_password_length', 0);
248 $length = $min_pass ? t('between !min and', array('!min' => $min_pass)) : t('no more than');
249 $form['pass']['#description'] = t('Please choose a password for your account; it must be !length 30 characters.', array('!length' => $length));
257 * Custom submit function for user registration form
259 * @ingroup logintoboggan_form
261 function logintoboggan_user_register_submit($form, &$form_state) {
263 $reg_pass_set = !variable_get('user_email_verification', TRUE);
265 // Test here for a valid pre-auth -- if the pre-auth is set to the auth user, we
266 // handle things a bit differently.
267 $pre_auth = logintoboggan_validating_id() != DRUPAL_AUTHENTICATED_RID;
269 // If we are allowing user selected passwords then skip the auto-generate function
270 // The new user's status should default to the site settings, unless reg_passwd_set == 1
271 // (immediate login, we are going to assign a pre-auth role), and we want to allow
272 // admin approval accounts access to the site.
274 $pass = $form_state['values']['pass'];
278 $pass = user_password();
279 $status = variable_get('user_register', 1) == 1;
282 // Must unset mail confirmation to prevent it from being saved in the user table's 'data' field.
283 if (isset($form_state['values']['conf_mail'])) { unset($form_state['values']['conf_mail']); }
285 if (array_intersect(array_keys($form_state['values']), array('uid', 'roles', 'init', 'session', 'status'))) {
286 watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
287 $form_state['redirect'] = 'user/register';
291 // The unset below is needed to prevent these form values from being saved as user data.
292 unset($form_state['values']['form_token'], $form_state['values']['submit'], $form_state['values']['op'], $form_state['values']['notify'], $form_state['values']['form_id'], $form_state['values']['form_build_id'], $form_state['values']['affiliates'], $form_state['values']['destination']);
294 // Set the roles for the new user -- add the pre-auth role if they can pick their own password,
295 // and the pre-auth role isn't anon or auth user.
296 $validating_id = logintoboggan_validating_id();
297 $roles = isset($form_state['values']['roles']) ? array_filter($form_state['values']['roles']) : array();
298 if ($reg_pass_set && ($validating_id > DRUPAL_AUTHENTICATED_RID)) {
299 $roles[$validating_id] = 1;
302 $account = user_save('', array_merge($form_state['values'], array('pass' => $pass, 'init' => $form_state['values']['mail'], 'roles' => $roles, 'status' => $status)));
303 // Add plain text password into user account to generate mail tokens.
304 $account->password = $pass;
305 $form_state['user'] = $account;
307 watchdog('user', 'New user: %name (%email).', array('%name' => $account->name, '%email' => $account->mail), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));
309 $login_url = variable_get('user_register', 1) == 1 ? logintoboggan_eml_validate_url($account) : NULL;
311 // Compose the appropriate user message--admin approvals don't require a validation email.
312 if($reg_pass_set && variable_get('user_register', 1) == 1) {
314 $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.');
320 $message = t('Your password and further instructions have been sent to your e-mail address.');
323 if (variable_get('user_register', 1) == 1) {
325 // Create new user account, no administrator approval required.
326 $mailkey = 'register_no_approval_required';
328 } elseif (variable_get('user_register', 1) == 2) {
330 // Create new user account, administrator approval required.
331 $mailkey = 'register_pending_approval';
333 $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.');
337 _logintoboggan_mail_notify($mailkey, $account, $login_url);
339 drupal_set_message($message);
341 // where do we need to redirect after registration?
342 $redirect = _logintoboggan_process_redirect(variable_get('logintoboggan_redirect_on_register', ''), $account);
344 // Log the user in if they created the account and immediate login is enabled.
345 if($reg_pass_set && variable_get('logintoboggan_immediate_login_on_register', TRUE)) {
346 $form_state['redirect'] = logintoboggan_process_login($account, $redirect);
349 // Redirect to the appropriate page.
350 $form_state['redirect'] = $redirect;
355 * Custom validation for user login form
357 * @ingroup logintoboggan_form
359 function logintoboggan_user_login_validate($form, &$form_state) {
360 if (isset($form_state['values']['name'])) {
361 if ($name = db_result(db_query("SELECT name FROM {users} WHERE LOWER(mail) = LOWER('%s')", $form_state['values']['name']))) {
362 form_set_value($form['name'], $name, $form_state);
368 * Custom validation function for user registration form
370 * @ingroup logintoboggan_form
372 function logintoboggan_user_register_validate($form, &$form_state) {
373 //Check to see whether our e-mail address matches the confirm address if enabled.
374 if (variable_get('logintoboggan_confirm_email_at_registration', 0)) {
375 if ($form_state['values']['mail'] != $form_state['values']['conf_mail']) {
376 form_set_error('conf_mail', t('Your e-mail address and confirmed e-mail address must match.'));
380 //Do some password validation if password selection is enabled.
381 if (!variable_get('user_email_verification', TRUE)) {
382 $pass_err = logintoboggan_validate_pass($form_state['values']['pass']);
384 form_set_error('pass', $pass_err);
390 * Custom validation function for user edit form
392 * @ingroup logintoboggan_form
394 function logintoboggan_user_edit_validate($form, &$form_state) {
395 if (strlen($form_state['values']['pass'])) {
396 // if we're changing the password, validate it
397 $pass_err = logintoboggan_validate_pass($form_state['values']['pass']);
399 form_set_error('pass', $pass_err);
405 * Implementation of hook_init()
407 * @ingroup logintoboggan_core
409 function logintoboggan_init() {
412 // Make sure any user with pre-auth role doesn't have authenticated user role
413 _logintoboggan_user_roles_alter($user);
416 drupal_add_css(drupal_get_path('module', 'logintoboggan') .'/logintoboggan.css');
420 * Alter user roles for loaded user account.
422 * If user is not an anonymous user, and the user has the pre-auth role, and the pre-auth role
423 * isn't also the auth role, then unset the auth role for this user--they haven't validated yet.
425 * This alteration is required because sess_read() and user_load() automatically set the
426 * authenticated user role for all non-anonymous users (see http://drupal.org/node/92361).
429 * User account to have roles adjusted.
431 function _logintoboggan_user_roles_alter(&$account) {
432 $id = logintoboggan_validating_id();
433 $in_pre_auth_role = in_array($id, array_keys($account->roles));
434 if ($account->uid && $in_pre_auth_role) {
435 if ($id != DRUPAL_AUTHENTICATED_RID) {
436 unset($account->roles[DRUPAL_AUTHENTICATED_RID]);
437 // Reset the permissions cache. Since the only
438 // goal here is to reset the cache, create a
439 // temporary account object for uid 1 -- this
440 // results in no hits on the database.
441 $temp_account = new stdClass();
442 $temp_account->uid = 1;
443 user_access('', $temp_account, TRUE);
449 * Implementation of hook_menu()
451 * @ingroup logintoboggan_core
453 function logintoboggan_menu() {
457 $items['admin/user/logintoboggan'] = array(
458 'title' => 'LoginToboggan',
459 'description' => 'Set up custom login options like instant login, login redirects, pre-authorized validation roles, etc.',
460 'page callback' => 'drupal_get_form',
461 'page arguments' => array('logintoboggan_main_settings'),
462 'access callback' => 'user_access',
463 'access arguments' => array('administer site configuration'),
466 // Callback for user validate routine.
467 $items['user/validate'] = array(
468 'title' => 'Validate e-mail address',
469 'page callback' => 'logintoboggan_validate_email',
470 'access callback' => TRUE,
471 'type' => MENU_CALLBACK,
474 // Callback for handling access denied redirection.
475 $items['toboggan/denied'] = array(
476 'access callback' => TRUE,
477 'page callback' => 'logintoboggan_denied',
478 'title' => 'Access denied',
479 'type' => MENU_CALLBACK,
482 //callback for re-sending validation e-mail
483 $items['toboggan/revalidate'] = array(
484 'title' => 'Re-send validation e-mail',
485 'page callback' => 'logintoboggan_resend_validation',
486 'page arguments' => array(2),
487 'access callback' => 'logintoboggan_revalidate_access',
488 'access arguments' => array(2),
489 'type' => MENU_CALLBACK,
496 * Access check for user revalidation.
498 function logintoboggan_revalidate_access($uid) {
501 return $user->uid == $uid || user_access('administer users');
505 * Implemenation of hook_theme().
507 * @ingroup logintoboggan_core
509 function logintoboggan_theme() {
511 'lt_username_title' => array(
512 'arguments' => array('form_id'),
514 'lt_username_description' => array(
515 'arguments' => array('form_id'),
517 'lt_password_title' => array(
518 'arguments' => array('form_id'),
520 'lt_password_description' => array(
521 'arguments' => array('form_id'),
523 'lt_access_denied' => array(
524 'arguments' => array(),
526 'lt_loggedinblock' => array(
527 'arguments' => array(),
529 'lt_login_link' => array(
530 'arguments' => array(),
536 * @defgroup logintoboggan_block Functions for LoginToboggan blocks.
539 function logintoboggan_user_block_admin_configure_submit($form, &$form_state) {
540 variable_set('logintoboggan_login_block_type', $form_state['values']['logintoboggan_login_block_type']);
541 variable_set('logintoboggan_login_block_message', $form_state['values']['logintoboggan_login_block_message']);
545 * Implementation of hook_block
547 * @ingroup logintoboggan_core
549 function logintoboggan_block($op = 'list', $delta = 0, $edit = array()) {
554 $blocks[0]['info'] = t('LoginToboggan logged in block');
555 $blocks[0]['cache'] = BLOCK_NO_CACHE;
563 $block['content'] = theme('lt_loggedinblock');
572 * User login block with JavaScript to expand
574 * this should really be themed
577 * the reconstituted user login block
580 function _logintoboggan_toggleboggan ($form) {
582 drupal_add_js(drupal_get_path('module', 'logintoboggan') .'/logintoboggan.js');
584 $pre = '<div id="toboggan-container" class="toboggan-container">';
586 'attributes' => array(
587 'id' => 'toboggan-login-link',
588 'class' => 'toboggan-login-link',
590 'query' => drupal_get_destination(),
592 $pre .= '<div id="toboggan-login-link-container" class="toboggan-login-link-container">';
593 $pre .= l(theme('lt_login_link'), 'user/login', $options);
596 //the block that will be toggled
597 $pre .= '<div id="toboggan-login" class="user-login-block">';
599 $form['pre'] = array('#value' => $pre, '#weight' => -300);
600 $form['post'] = array('#value' => '</div></div>', '#weight' => 300);
604 function logintoboggan_main_settings(&$form_state) {
605 $version = str_replace(array('$Re'.'vision:', '$Da'.'te:', '$'), array('', '', ''), '<p style="font-size:x-small">Login Toboggan version: <b>$Revision: 1.133.2.9 $</b>, $Date: 2009/03/21 12:09:20 $</p>');
607 $_disabled = t('disabled');
608 $_enabled = t('enabled');
610 $form['login'] = array(
611 '#type' => 'fieldset',
612 '#title' => t('Login'),
613 '#prefix' => $version,
616 $form['login']['logintoboggan_login_with_email'] = array(
618 '#title' => t('Allow users to login using their e-mail address'),
619 '#default_value' => variable_get('logintoboggan_login_with_email', 0),
620 '#options' => array($_disabled, $_enabled),
621 '#description' => t('Users will be able to enter EITHER their username OR their e-mail address to log in.'),
624 $form['registration'] = array(
625 '#type' => 'fieldset',
626 '#title' => t('Registration'),
629 $form['registration']['logintoboggan_confirm_email_at_registration'] = array(
631 '#title' => t('Use two e-mail fields on registration form'),
632 '#default_value' => variable_get('logintoboggan_confirm_email_at_registration', 0),
633 '#options' => array($_disabled, $_enabled),
634 '#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.'),
637 $form['registration']['user_email_verification'] = array(
638 '#type' => 'checkbox',
639 '#title' => t('Set password'),
640 '#default_value' => !variable_get('user_email_verification', TRUE) ? 1 : 0,
641 '#description' => t("This will allow users to choose their initial password when registering (note that this setting is merely 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 -- more help in writing the e-mail message can be found at <a href=\"!help\">LoginToboggan help</a>.", array('!settings' => url('admin/user/settings'), '!help' => url('admin/help/logintoboggan'))),
644 // Grab the roles that can be used for pre-auth. Remove the anon role, as it's not a valid choice.
645 $roles = user_roles(1);
647 $form ['registration']['logintoboggan_pre_auth_role'] = array(
649 '#title' => t('Non-authenticated role'),
650 '#options' => $roles,
651 '#default_value' => variable_get('logintoboggan_pre_auth_role', DRUPAL_AUTHENTICATED_RID),
652 '#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. 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'))),
655 $purge_options = array(
656 0 => t('Never delete'),
658 172800 => t('2 Days'),
659 259200 => t('3 Days'),
660 345600 => t('4 Days'),
661 432000 => t('5 Days'),
662 518400 => t('6 Days'),
663 604800 => t('1 Week'),
664 1209600 => t('2 Weeks'),
665 2592000 => t('1 Month'),
666 7776000 => t('3 Months'),
667 15379200 => t('6 Months'),
668 30758400 => t('1 Year'),
671 $form['registration']['logintoboggan_purge_unvalidated_user_interval'] = array(
673 '#title' => t('Delete unvalidated users after'),
674 '#options' => $purge_options,
675 '#default_value' => variable_get('logintoboggan_purge_unvalidated_user_interval', 0),
676 '#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 last login 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.")
679 $form['registration']['logintoboggan_immediate_login_on_register'] = array(
680 '#type' => 'checkbox',
681 '#title' => t('Immediate login'),
682 '#default_value' => variable_get('logintoboggan_immediate_login_on_register', TRUE),
683 '#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."),
686 $form['registration']['redirect'] = array(
687 '#type' => 'fieldset',
688 '#title' => t('Redirections'),
689 '#collapsible' => true,
690 '#collapsed' => false,
693 $form['registration']['redirect']['logintoboggan_redirect_on_register'] = array(
694 '#type' => 'textfield',
695 '#title' => t('Redirect path on Registration'),
696 '#default_value' => variable_get('logintoboggan_redirect_on_register', ''),
697 '#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.'),
700 $form['registration']['redirect']['logintoboggan_redirect_on_confirm'] = array(
701 '#type' => 'textfield',
702 '#title' => t('Redirect path on Confirmation'),
703 '#default_value' => variable_get('logintoboggan_redirect_on_confirm', ''),
704 '#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. 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.'),
707 $form['other'] = array('#type' => 'fieldset',
708 '#title' => t('Other'),
712 $site403 = variable_get('site_403', '');
713 if ($site403 == 'toboggan/denied'){
717 $disabled = $site403;
719 $options = array($disabled => $_disabled, 'toboggan/denied' => $_enabled);
721 $form['other']['site_403'] = array(
723 '#title' => t('Present login form on access denied (403)'),
724 '#options' => $options,
725 '#default_value' => $site403,
726 '#description' => t('Anonymous users will be presented with a login form along with an access denied message.')
728 $form['other']['logintoboggan_login_successful_message'] = array(
730 '#title' => t('Display login successful message'),
731 '#options' => array($_disabled, $_enabled),
732 '#default_value' => variable_get('logintoboggan_login_successful_message', 0),
733 '#description' => t('If enabled, users will receive a \'Login successful\' message upon login.')
735 $min_pass_options = array(t('None'));
736 for ($i = 2; $i < 30; $i++) {
737 $min_pass_options[$i] = $i;
739 $form['other']['logintoboggan_minimum_password_length'] = array(
741 '#title' => t('Minimum password length'),
742 '#options' => $min_pass_options,
743 '#default_value' => variable_get('logintoboggan_minimum_password_length', 0),
744 '#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.')
747 return system_settings_form($form);
750 function logintoboggan_denied() {
752 if ($user->uid == 0) {
754 global $logintoboggan_denied;
755 $logintoboggan_denied = TRUE;
757 // build the user menu item as the 403 page content, adjust the page title appropriately, and warn
758 // the user that they were denied access.
759 menu_set_active_item('user');
760 $return = menu_execute_active_handler();
761 drupal_set_title(t('Access Denied / User Login'));
762 drupal_set_message(t('Access denied. You may need to login below or register to access this page.'), 'error');
765 drupal_set_title(t('Access Denied'));
766 $return = theme('lt_access_denied');
771 // Slight rewrite of drupal_get_destination()
772 // with custom 403, drupal_get_destination() would return toboggan/denied
773 // which would show 'Access Denied' after login... what good is that!?
774 // Because drupal_access_denied() sets $_REQUEST['destination'], and that
775 // overrides any other setting in drupal_goto(), we manipulate that
776 // directly here instead of returning values to the form code.
777 function logintoboggan_destination() {
778 // Drupal has reset $_GET[q], so we need a workaround.
779 if ($internal_path = substr(request_uri(), strlen(base_path()))) {
780 // Clean URLs disabled, so break apart the query string and
781 // pull out the path.
782 if (!variable_get('clean_url', 0)) {
783 $internal_path = parse_url($internal_path);
784 $queryarray = explode('&', $internal_path['query']);
785 $path = str_replace('q=', '', $queryarray[0]);
786 unset($queryarray[0]);
787 $query = !empty($queryarray) ? '?'. implode('&', $queryarray) : '';
788 $internal_path = $path . $query;
790 // If the language path prefixing is enabled remove it from the path.
791 switch (variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE)) {
792 case LANGUAGE_NEGOTIATION_PATH_DEFAULT:
793 case LANGUAGE_NEGOTIATION_PATH:
794 $args = explode('/', $internal_path);
795 $prefix = array_shift($args);
797 // Search prefix within enabled languages.
798 $languages = language_list('enabled');
799 foreach ($languages[1] as $language) {
800 if (!empty($language->prefix) && $language->prefix == $prefix) {
801 // Found a match, rebuild the path without the language.
802 $internal_path = implode('/', $args);
807 $_REQUEST['destination'] = $internal_path;
809 // Fall back to homepage.
811 $_REQUEST['destination'] = variable_get('site_frontpage', 'node');
816 * Modified version of user_validate_name
817 * - validates user submitted passwords have a certain length and only contain letters, numbers or punctuation (graph character class in regex)
819 function logintoboggan_validate_pass($pass) {
820 if (!strlen($pass)) return t('You must enter a password.');
821 if (ereg("[^\x80-\xF7[:graph:] ]", $pass)) return t('The password contains an illegal character.');
822 if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP
823 '\x{AD}'. // Soft-hyphen
824 '\x{2000}-\x{200F}'. // Various space characters
825 '\x{2028}-\x{202F}'. // Bidirectional text overrides
826 '\x{205F}-\x{206F}'. // Various text hinting characters
827 '\x{FEFF}'. // Byte order mark
828 '\x{FF01}-\x{FF60}'. // Full-width latin
829 '\x{FFF9}-\x{FFFD}]/u', // Replacement characters
831 return t('The password contains an illegal character.');
833 if (strlen($pass) > 30) return t('The password is too long: it must be less than 30 characters.');
834 $min_pass_length = variable_get('logintoboggan_minimum_password_length', 0);
835 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));
840 * Modified version of $DRUPAL_AUTHENTICATED_RID
841 * - gets the role id for the "validating" user role.
843 function logintoboggan_validating_id() {
844 return variable_get('logintoboggan_pre_auth_role', DRUPAL_AUTHENTICATED_RID);
849 * Menu callback; process validate the e-mail address as a one time URL,
850 * and redirects to the user page on success.
852 function logintoboggan_validate_email($uid, $timestamp, $hashed_pass, $action = 'login') {
856 // Some redundant checks for extra security
857 if ($timestamp < $current && $uid && $account = user_load(array('uid' => $uid)) ) {
858 // No time out for first time login.
859 // This conditional checks that:
860 // - the user is still in the pre-auth role or didn't set
861 // their own password.
862 // - the hashed password is correct.
863 if (((variable_get('user_email_verification', TRUE) && empty($account->login)) || array_key_exists(logintoboggan_validating_id(), $account->roles)) && $hashed_pass == logintoboggan_eml_rehash($account->pass, $timestamp, $account->mail)) {
864 watchdog('user', 'E-mail validation URL used for %name with timestamp @timestamp.', array('%name' => $account->name, '@timestamp' => $timestamp));
865 // Update the user table noting user has logged in.
866 // And this also makes this hashed password a one-time-only login.
867 db_query("UPDATE {users} SET login = '%d' WHERE uid = %d", time(), $account->uid);
869 // Test here for a valid pre-auth -- if the pre-auth is set to the auth user, we
870 // handle things a bit differently.
871 $validating_id = logintoboggan_validating_id();
872 $pre_auth = $validating_id != DRUPAL_AUTHENTICATED_RID;
874 // Remove the pre-auth role from the user, unless they haven't been approved yet.
875 if ($account->status) {
877 db_query("DELETE FROM {users_roles} WHERE uid = %d AND rid = %d", $account->uid, $validating_id);
878 // Since we're passing $account around to the update hook, remove
879 // the pre-auth role from the roles array, and add in the auth user
881 $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
882 unset($account->roles[$validating_id]);
884 // Allow other modules to react to email validation by invoking the user update hook.
886 $account->logintoboggan_email_validated = TRUE;
887 user_module_invoke('update', $edit, $account);
890 // Where do we redirect after confirming the account?
891 $redirect = _logintoboggan_process_redirect(variable_get('logintoboggan_redirect_on_confirm', ''), $account);
894 // Proceed with normal user login, as long as it's open registration and their
895 // account hasn't been blocked.
897 // Only show the validated message if there's a valid pre-auth role.
899 drupal_set_message(t('You have successfully validated your e-mail address.'));
901 if (!$account->status) {
902 drupal_set_message(t('Your account is currently blocked -- login cancelled.'), 'error');
906 $redirect = logintoboggan_process_login($account, $redirect);
907 drupal_goto($redirect['path'], $redirect['query'], $redirect['fragment']);
912 // user has new permissions, so we clear their menu cache
913 cache_clear_all($account->uid .':', 'cache_menu', TRUE);
916 // Mail the user, letting them know their account now has auth user perms.
917 _user_mail_notify('status_activated', $account);
920 drupal_set_message(t('You have successfully validated %user.', array('%user' => $account->name)));
921 drupal_goto("user/$account->uid/edit");
925 // user has new permissions, so we clear their menu cache
926 cache_clear_all($account->uid .':', 'cache_menu', TRUE);
928 drupal_set_message(t('You have successfully validated %user.', array('%user' => $account->name)));
934 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');
938 // Deny access, no more clues.
939 // Everything will be in the watchdog's URL for the administrator to check.
940 drupal_access_denied();
944 * Actually log the user on
946 * @param object $account
949 function logintoboggan_process_login($account, $redirect = ''){
953 watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
955 // Update the user table timestamp noting user has logged in.
956 db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $user->uid);
958 // user has new permissions, so we clear their menu cache
959 cache_clear_all($user->uid .':', 'cache_menu', TRUE);
962 user_module_invoke('login', $edit, $user);
964 // In the special case where a user is validating but they did not create their
965 // own password, show a user message letting them know to change their password.
966 if (variable_get('user_email_verification', TRUE)) {
967 watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $user->name, '%timestamp' => time()));
968 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.'));
971 if ($redirect['path'] != '') {
976 'path' => 'user/'. $user->uid,
982 function logintoboggan_eml_validate_url($account){
984 return url("user/validate/$account->uid/$timestamp/". logintoboggan_eml_rehash($account->pass, $timestamp, $account->mail), array('absolute' => TRUE));
987 function logintoboggan_eml_rehash($password, $timestamp, $mail){
988 return md5($timestamp . $password . $mail);
992 * Implementation of hook_user().
994 function logintoboggan_user($op, &$edit, &$user_edit, $category = NULL) {
996 if ($op == 'form' && $category == 'account' && ($user->uid == $user_edit->uid || user_access('administer users'))) {
997 // User is editing their own account settings, or user admin
998 // is editing their account.
999 if (!variable_get('user_email_verification', TRUE) && array_key_exists(logintoboggan_validating_id(), $user_edit->roles) && variable_get('user_register', 1) == 1) {
1000 // User is still in pre-authorized role; display link to re-send e-mail.
1001 $form['revalidate'] = array(
1002 '#type' => 'fieldset',
1003 '#title' => t('Account validation'),
1006 $form['revalidate']['revalidate_link'] = array(
1007 '#value' => l(t('re-send validation e-mail'), 'toboggan/revalidate/'. $user_edit->uid),
1011 } elseif ($op == 'login' && variable_get('logintoboggan_login_successful_message', 0)) {
1012 drupal_set_message(t('Login successful.'));
1014 elseif ($op == 'load') {
1015 // Just loaded the user into $user_edit.
1016 // If the user has the pre-auth role, unset the authenticated role
1017 _logintoboggan_user_roles_alter($user_edit);
1019 elseif ($op == 'validate') {
1020 // If login with mail is enabled...
1021 if (variable_get('logintoboggan_login_with_email', 0)) {
1022 $uid = isset($user_edit->uid) ? $user_edit->uid : 0;
1023 // Check that no user is using this name for their email address.
1024 if (isset($edit['name']) && db_result(db_query("SELECT uid FROM {users} WHERE LOWER(mail) = LOWER('%s') AND uid <> %d", $edit['name'], $uid))) {
1025 form_set_error('name', t('This name has already been taken by another user.'));
1027 // Check that no user is using this email address for their name.
1028 if (isset($edit['mail']) && db_result(db_query("SELECT uid FROM {users} WHERE LOWER(name) = LOWER('%s') AND uid <> %d", $edit['mail'], $uid))) {
1029 form_set_error('mail', t('This e-mail has already been taken by another user.'));
1036 * Re-sends validation e-mail to user specified by $uid.
1038 function logintoboggan_resend_validation($uid) {
1041 $account = user_load(array('uid' => $uid));
1042 $account->password = t('If required, you may reset your password from: !url', array('!url' => url('user/password', array('absolute' => TRUE))));
1044 $params['account'] = $account;
1045 $params['login_url'] = logintoboggan_eml_validate_url($account);
1047 // Prepare and send e-mail.
1048 drupal_mail('logintoboggan', 'logintoboggan_resend_validation', $account->mail, $language, $params);
1050 // Notify admin or user that e-mail was sent and return to user edit form.
1051 if (user_access('administer users')) {
1052 drupal_set_message(t("A validation e-mail has been sent to the user's e-mail address."));
1055 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.'));
1058 drupal_goto('user/'. $account->uid .'/edit');
1061 function _logintoboggan_protocol() {
1062 return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http');
1065 function _logintoboggan_process_redirect($redirect, $account) {
1066 $variables = array('%uid' => $account->uid);
1067 $redirect = parse_url(urldecode(strtr($redirect, $variables)));
1069 // Explicitly create query and fragment elements if not present already.
1070 $redirect['query'] = isset($redirect['query']) ? $redirect['query'] : NULL;
1071 $redirect['fragment'] = isset($redirect['fragment']) ? $redirect['fragment'] : NULL;
1077 * Resets the the site 403 variable to the default if the module is disabled
1078 * and the toboggan redirect on access denied is enabled.
1080 function logintoboggan_site_403_validate($form, &$form_state) {
1081 // The check order is important:
1082 // 1. Is the module disabled? Skip if so.
1083 // 2. Has the module been selected to be disabled?
1084 // 3. Is the current site 403 toboggan/denied?
1085 // Only reset the site 403 variable if 2 and 3 are true.
1086 if (!isset($form_state['values']['disabled_modules']['logintoboggan']) && !$form_state['values']['status']['logintoboggan'] && (variable_get('site_403', '') == 'toboggan/denied')) {
1087 variable_set('site_403', '');
1092 * Flips the value of the user_email_settings variable. This setting is less confusing when it works the opposite
1093 * of it's current core behavior.
1095 function logintoboggan_flip_user_email_verification($form, &$form_state) {
1096 $value = $form_state['values']['user_email_verification'] ? FALSE : TRUE;
1097 variable_set('user_email_verification', $value);
1101 * Conditionally create and send a notification email when a certain
1102 * operation happens on the given user account. This is a knock-off of
1103 * _user_mail_notify() customized for LT.
1105 * @see user_mail_tokens()
1106 * @see drupal_mail()
1109 * The operation being performed on the account. Possible values:
1110 * 'register_admin_created': Welcome message for user created by the admin
1111 * 'register_no_approval_required': Welcome message when user self-registers
1112 * 'register_pending_approval': Welcome message, user pending admin approval
1113 * 'password_reset': Password recovery request
1114 * 'status_activated': Account activated
1115 * 'status_blocked': Account blocked
1116 * 'status_deleted': Account deleted
1119 * The user object of the account being notified. Must contain at
1120 * least the fields 'uid', 'name', and 'mail'.
1122 * The custom !login_url setting. User default is used if none is provided.
1124 * Optional language to use for the notification, overriding account language.
1126 * The return value from drupal_mail_send(), if ends up being called.
1128 function _logintoboggan_mail_notify($op, $account, $login_url = NULL, $language = NULL) {
1129 // By default, we always notify except for deleted and blocked.
1130 $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
1131 $notify = variable_get('user_mail_'. $op .'_notify', $default_notify);
1133 $params['account'] = $account;
1134 $params['login_url'] = $login_url;
1135 $language = $language ? $language : user_preferred_language($account);
1136 $mail = drupal_mail('logintoboggan', $op, $account->mail, $language, $params);
1137 if ($op == 'register_pending_approval') {
1138 // If a user registered requiring admin approval, notify the admin, too.
1139 // We use the site default language for this.
1140 $params['validating_url'] = logintoboggan_eml_validate_url($account) .'/admin';
1141 drupal_mail('logintoboggan', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
1144 return empty($mail) ? NULL : $mail['result'];
1148 * Implementation of hook_mail().
1150 function logintoboggan_mail($key, &$message, $params) {
1153 $language = $message['language'];
1154 $langcode = isset($language) ? $language->language : NULL;
1156 $variables = user_mail_tokens($params['account'], $language);
1157 // Customize special tokens.
1158 $variables['!uri_brief'] = substr($base_url, strlen(_logintoboggan_protocol() .'://'));
1159 if (isset($params['login_url'])) {
1160 $variables['!login_url'] = $params['login_url'];
1164 case 'register_pending_approval_admin':
1165 $variables['!validating_url'] = $params['validating_url'];
1166 $message['subject'] .= t("(!site) Account application for !username", $variables, $langcode);
1167 $reg_pass_set = !variable_get('user_email_verification', TRUE);
1168 if ($reg_pass_set) {
1169 $message['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!edit_uri", $variables, $langcode);
1172 $message['body'][] = t("!username has applied for an account.\n\n!edit_uri", $variables, $langcode);
1175 case 'logintoboggan_resend_validation':
1176 $message['subject'] .= strtr(variable_get('user_mail_register_no_approval_required_subject', _user_mail_text('register_no_approval_required_subject')), $variables);
1177 $message['body'][] = strtr(variable_get('user_mail_register_no_approval_required_body', _user_mail_text('register_no_approval_required_body')), $variables);
1180 $message['subject'] .= strtr(variable_get('user_mail_'. $key .'_subject', _user_mail_text($key .'_subject')), $variables);
1181 $message['body'][] = strtr(variable_get('user_mail_'. $key .'_body', _user_mail_text($key .'_body')), $variables);
1189 * You may override and change any of these custom HTML output functions
1190 * by copy/pasting them into your template.php file, at which point you can
1191 * customize anything, provided you are using the default phptemplate engine.
1193 * For more info on overriding theme functions, see http://drupal.org/node/55126
1197 * Theme the username title of the user login form
1198 * and the user login block.
1200 function theme_lt_username_title($form_id) {
1203 // Label text for the username field on the /user/login page.
1204 return t('Username or e-mail address');
1207 case 'user_login_block':
1208 // Label text for the username field when shown in a block.
1209 return t('Username or e-mail');
1215 * Theme the username description of the user login form
1216 * and the user login block.
1218 function theme_lt_username_description($form_id) {
1221 // The username field's description when shown on the /user/login page.
1222 return t('You may login with either your assigned username or your e-mail address.');
1224 case 'user_login_block':
1231 * Theme the password title of the user login form
1232 * and the user login block.
1234 function theme_lt_password_title($form_id) {
1235 // Label text for the password field.
1236 return t('Password');
1240 * Theme the password description of the user login form
1241 * and the user login block.
1243 function theme_lt_password_description($form_id) {
1246 // The password field's description on the /user/login page.
1247 return t('The password field is case sensitive.');
1250 case 'user_login_block':
1251 // If showing the login form in a block, don't print any descriptive text.
1258 * Theme the Access Denied message.
1260 function theme_lt_access_denied() {
1261 return t('You are not authorized to access this page.');
1265 * Theme the loggedinblock that shows for logged-in users.
1267 function theme_lt_loggedinblock(){
1269 return check_plain($user->name) .' | ' . l(t('Log out'), 'logout');
1273 * Custom theme function for the login/register link.
1275 function theme_lt_login_link() {
1276 // Only display register text if registration is allowed.
1277 if (variable_get('user_register', 1)) {
1278 return t('Login/Register');