summaryrefslogtreecommitdiffstats
path: root/logintoboggan.module
blob: 99da9798bbc50e81cdc271c120d2d8c895b9e1b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
<?php
// $Id$

/**
 * @file
 *  Logintoboggan Module
 *
 * This module enhances the configuration abilities of Drupal's default login system.
 */

/**
 * @todo
 *
 * _ Configurable text for theme_lt_access_denied()
 * _ clean up variable names
 *
 */

/**
 * @wishlist
 *
 * _ password complexity testing option
 * _ setting to expire unverified accounts and purge them from system
 *
 */

/**
 * @defgroup logintoboggan_core Core drupal hooks
 */

/**
 * Implementation of hook_help()
 *
 * @param unknown_type $section
 * @return unknown
 */

function logintoboggan_help($section) {
  switch ($section) {
    case 'admin/help#logintoboggan':
      $output = t('<p>The Login Toboggan module improves the Drupal login system by offering the following features:
      <ol>
      <li>Allow users to login using either their username OR their e-mail address.</li>
      <li>Allow users to login immediately.</li>
      <li>Provide a login form on Access Denied pages for non-logged-in (anonymous) users.</li>
      <li>The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.</li>
      <li>Customize the registration form with two e-mail fields to ensure accuracy.</li>
      <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>
      <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 & 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>
      ', array('!url' => url('admin/user/logintoboggan'), '!user_settings' => url('admin/user/settings')));
      $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':
      if (module_exists('help')) {
        $help_text =  t("More help can be found at <a href=\"!help\">LoginToboggan help</a>.", array('!help' => url('admin/help/logintoboggan')));
      }
      else {
        $help_text = '';
      }
      $output = t("<p>Customize your login and registration system. $help_text</p>");

      return $output;
  }
}

/**
 * Helper function for example user e-mail textfield.
 */
function logintoboggan_example_help() {
  $example = t('
!username,

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:

!login_url

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:

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:

Drupal ID: !username@!uri_brief


--  !site team');
  $form['foo'] = array(
    '#type' => 'textarea',
    '#default_value' => $example,
    '#rows' => 15,
  );

  return $form;
}

/**
 * Implementation of hook_form_alter()
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_form_alter($form_id, &$form) {
  switch ($form_id) {
    case 'block_admin_configure':
      if (($form['module']['#value'] == 'user') && ($form['delta']['#value'] == 0)) {
        $form['#submit'] += array('logintoboggan_user_block_admin_configure_submit' => array($form));

        $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>&lt;none&gt;</em>.') .'</div>';

        $form['block_settings']['toboggan_block_type'] = array('#type' => 'radios',
          '#title' => t('Block type'),
          '#default_value' => variable_get('toboggan_block_type', 1),
          '#options' => array(t('Standard'), t('Link'), t('Collapsible form')),
          '#description' => t("'Standard' is a standard login block, 'Link' is a login link that returns the user to the original page after logging in, 'Collapsible form' is a javascript collaspible login form."),
        );

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

    case 'system_modules':
      $form['#validate']['logintoboggan_site_403_validate'] = array();
      break;

    case 'logintoboggan_main_settings':
      $form['#submit'] += array('logintoboggan_flip_user_email_verification' => array());
      break;
    case 'user_edit':
      $form['#validate'] += array('logintoboggan_user_edit_validate' => array());
      $user = user_load(array('uid' => arg(1)));
      $id = logintoboggan_validating_id();
      $in_pre_auth_role = in_array($id, array_keys($user->roles));
      // Messages aren't necessary if pre-auth role is authenticated user.
      if ($in_pre_auth_role && $id != DRUPAL_AUTHENTICATED_RID) {
        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.");
      }
      break;

    case 'user_login':
    case 'user_login_block':
      // Grab the message from settings for display at the top of the login block.
      if ($login_msg = variable_get('toboggan_block_msg', '')) {
        $form['message'] = array(
          '#value' => filter_xss_admin($login_msg),
          '#weight' => -50,
        );
      }
      $form['name']['#attributes']['tabindex']    = '1';
      $form['pass']['#attributes']['tabindex']    = '2';
      $form['submit']['#attributes']['tabindex']  = '3';
      if (variable_get('login_with_mail', 0)) {
        $form['#validate'] = array('logintoboggan_user_login_validate' => array()) + $form['#validate'];
        // Use theme functions to print the username field's textual labels.
        $form['name']['#title']       = theme('lt_username_title', $form_id);
        $form['name']['#description'] = theme('lt_username_description', $form_id);
        // Use theme functions to print the password field's textual labels.
        $form['pass']['#title']       = theme('lt_password_title', $form_id);
        $form['pass']['#description'] = theme('lt_password_description', $form_id);
      }
      if($GLOBALS['logintoboggan_denied'] == TRUE){
        logintoboggan_destination();
      }

      if (($form_id == 'user_login_block')) {
        $block_type = variable_get('toboggan_block_type', 1);
        if ($block_type == 1) {
          $form = array('#value' => l(theme('lt_login_link'), 'user/login', array(), drupal_get_destination()));
        }
        elseif ($block_type == 2) {
          $form  = _logintoboggan_toggleboggan($form);
        }
      }
      break;

    case 'user_register':
      // Admin created accounts are only validated by the module.
      if (user_access('administer users')) {
        $form['#validate'] += array('logintoboggan_user_register_validate' => array());
        break;
      }
      $mail = variable_get('email_reg_confirm', 0);
      $pass = !variable_get('user_email_verification', TRUE);

      // Replace core's registration function with LT's registration function.
      // Put the LT submit handler first, so other submit handlers have a valid
      // user to work with upon registration.
      unset($form['#submit']['user_register_submit']);
      $form['#submit'] = array('logintoboggan_user_register_submit' => array()) + $form['#submit'];

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

        //Display a confirm e-mail address box if option is enabled.
        if ($mail) {
          // Make sure user help is at the top of the form.
          $form['user_registration_help']['#weight'] = -100;

          $form['conf_mail'] = array('#type' => 'textfield',
            '#title' => t('Confirm e-mail address'),
            '#weight' => -28,
            '#maxlength' => 64,
            '#description' => t('Please re-type your e-mail address to confirm it is accurate.'),
            '#required' => TRUE,
            );

          // Weight things properly so that the order is name, mail, conf_mail, then pass
          if (isset($form['account'])) {
            $form['account']['#weight'] = -50;  // Make sure account form group is at the top of the display.
            $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 {
            $form['name']['#weight'] = -30;
            $form['mail']['#weight'] = -29;
          }
        }
        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.', array('!length' => $length));
        }
      }
      break;
    // Password resets count as validating an email address, so remove the user
    // from the pre-auth role if they are still in it.
    case 'user_pass_reset':
      // We only want to run this code when the user first hits the reset login
      // form.
      if (arg(5) != 'login' && ($uid = (int) arg(2))) {
        if ($account = user_load(array('uid' => $uid))) {
          $id = logintoboggan_validating_id();
          $in_pre_auth_role = in_array($id, array_keys($account->roles));
          if ($in_pre_auth_role) {
            _logintoboggan_process_validation($account);
            drupal_set_message(t('You have successfully validated your e-mail address.'));
          }
        }
      }
      break;
  }
}

/**
 * Custom submit function for user registration form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_register_submit($form_id, $form_values) {
  global $base_url;

  $mail = $form_values['mail'];
  $name = $form_values['name'];
  $from = variable_get('site_mail', ini_get('sendmail_from'));
  $reg_pass_set = !variable_get('user_email_verification', TRUE);

  // Test here for a valid pre-auth -- if the pre-auth is set to the auth user, we
  // handle things a bit differently.
  $pre_auth = logintoboggan_validating_id() != DRUPAL_AUTHENTICATED_RID;

  // If we are allowing user selected passwords then skip the auto-generate function
  // The new user's status should default to the site settings, unless reg_passwd_set == 1
  // (immediate login, we are going to assign a pre-auth role), and we want to allow
  // admin approval accounts access to the site.
  if ($reg_pass_set) {
    $pass = $form_values['pass'];
    $status = 1;
  }
  else {
    $pass = user_password();
    $status = variable_get('user_register', 1) == 1;
  }

  // Must unset mail confirmation to prevent it from being saved in the user table's 'data' field.
  if (isset($form_values['conf_mail'])) { unset($form_values['conf_mail']); }

  if (array_intersect(array_keys($form_values), array('uid', 'roles', 'init', 'session', 'status'))) {
    watchdog('security', t('Detected malicious attempt to alter protected user fields.'), WATCHDOG_WARNING);
    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_values['roles']) ? array_filter($form_values['roles']) : array();
  if ($reg_pass_set && ($validating_id > DRUPAL_AUTHENTICATED_RID)) {
    $roles[$validating_id] = 1;
  }

  $edit = array_merge($form_values, array('pass' => $pass, 'init' => $mail, 'roles' => $roles, 'status' => $status));
  $account = user_save('', $edit);

  watchdog('user', t('New user: %name %email.', array('%name' => $name, '%email' => "<$mail>")), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));

  $login_url = variable_get('user_register', 1) == 1 ? logintoboggan_eml_validate_url($account) : user_pass_reset_url($account);
  $variables = array('!username' => $name, '!site' => variable_get('site_name', 'drupal'), '!password' => $pass, '!uri' => $base_url, '!uri_brief' => substr($base_url, strlen(_logintoboggan_protocol() .'://')), '!mailto' => $mail, '!date' => format_date(time()), '!login_uri' => url('user', NULL, NULL, TRUE), '!edit_uri' => url('user/'. $account->uid .'/edit', NULL, NULL, TRUE), '!login_url' => $login_url);

  // Compose the appropriate user message--admin approvals don't require a validation e-mail.
  if($reg_pass_set && variable_get('user_register', 1) == 1) {
    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 = '';
    }
  } else {
    $message = t('Your password and further instructions have been sent to your e-mail address.');
  }

  if (variable_get('user_register', 1) == 1) {

    // Create new user account, no administrator approval required.
    $subject = _user_mail_text('welcome_subject', $variables);
    $body = _user_mail_text('welcome_body', $variables);
    $mailkey = 'user-register-welcome';

  } elseif (variable_get('user_register', 1) == 2) {

    // Create new user account, administrator approval required.
    $subject = _user_mail_text('approval_subject', $variables);
    $body = _user_mail_text('approval_body', $variables);
    $mailkey = 'user-register-approval-user';

    $message = t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />') . $message;
    $admin_variables = array('!u' => $account->name, '!validating_url' => logintoboggan_eml_validate_url($account) .'/admin', '!uri' => url("user/$account->uid/edit", NULL, NULL, TRUE));

    if ($reg_pass_set) {
      $admin_body = t("!u 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_variables);
    }
    else {
      $admin_body =t("!u has applied for an account.\n\n!uri", $admin_variables);
    }
    drupal_mail('user-register-approval-admin', $from, $subject, $admin_body, $from);

  }

  //mail the user.
  drupal_mail($mailkey, $mail, $subject, $body, $from);

  drupal_set_message($message);

  // where do we need to redirect after registration?
  $redirect = _logintoboggan_process_redirect(variable_get('toboggan_redirect_on_register', ''), $account);

  //log the user in if they created the account and immediate login is enabled.
  if($reg_pass_set) {
    return logintoboggan_process_login($account, $edit, $redirect);
  }

  //redirect to the appropriate page.
  return $redirect;
}

/**
 * Custom validation for user login form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_login_validate($form_id, $form_values, $form) {
  if (isset($form_values['name'])) {
    if ($name = db_result(db_query("SELECT name FROM {users} WHERE LOWER(mail) = LOWER('%s')", $form_values['name']))) {
      form_set_value($form['name'], $name);
    }
  }
}

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

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

/**
 * Custom validation function for user edit form
 *
 * @ingroup logintoboggan_form
 */
function logintoboggan_user_edit_validate($form_id, $form_values) {
  if (!empty($form_values['pass'])) {
    // if we're changing the password, validate it
    $pass_err = logintoboggan_validate_pass($form_values['pass']);
    if ($pass_err) {
      form_set_error('pass', $pass_err);
    }
  }
}

/**
 * Implementation of hook_init()
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_init() {

  global $user;

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

/**
 * 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) {
  $id = logintoboggan_validating_id();
  $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]);
    }
  }
}

/**
 * Implementation of hook_menu()
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_menu($may_cache) {
  global $user;
  $items = array();
  if ($may_cache) {

    //settings page
    $items[] = array(
      'path' => 'admin/user/logintoboggan',
      'title' => t('LoginToboggan'),
      'description' => t('Set up custom login options like instant login, login redirects, pre-authorized validation roles, etc.'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('logintoboggan_main_settings')
      );

    //callback for user validate routine
    $items[] = array('path' => 'user/validate',
      'title' => t('Validate e-mail address'),
      'callback' => 'logintoboggan_validate_email',
      'access' => TRUE,
      'type' => MENU_CALLBACK,
      );

    //callback for handling access denied redirection
    $items[] = array('path' => 'toboggan/denied',
      'access' => TRUE,
      'callback' => 'logintoboggan_denied',
      'title' => t('Access denied'),
      'type' => MENU_CALLBACK,
      );
  }
  else {

    // add custom css for the block
    drupal_add_css(drupal_get_path('module', 'logintoboggan') .'/logintoboggan.css');

    //callback for re-sending validation e-mail
    $items[] = array('path' => 'toboggan/revalidate',
      'title' => t('Re-send validation e-mail'),
      'callback' => 'logintoboggan_resend_validation',
      'callback arguments' => array(arg(2)),
      'access' => $user->uid == arg(2) || user_access('administer users'),
      'type' => MENU_CALLBACK,
      );
  }
  return $items;
}

/**
 * @defgroup logintoboggan_block Functions for LoginToboggan blocks.
 */

function logintoboggan_user_block_admin_configure_submit($form_id, $form_values) {
  variable_set('toboggan_block_type', $form_values['toboggan_block_type']);
  variable_set('toboggan_block_msg', $form_values['toboggan_block_msg']);
}

/**
 * Implementation of hook_block
 *
 * @ingroup logintoboggan_core
 */
function logintoboggan_block($op = 'list', $delta = 0, $edit = array()) {
  global $user;

  switch ($op) {
    case 'list' :
      $blocks[0]['info'] = t('LoginToboggan logged in block');
      return $blocks;
      break;
    case 'view' :
      $block = array();
      switch ($delta) {
        case 0:
          if ($user->uid) {
            $block['content'] =  theme('lt_loggedinblock');
          }
          return $block;
      }
      break;
  }
}

/**
 * User login block with JavaScript to expand
 *
 * this should really be themed
 *
 * @return array
 *   the reconstituted user login block
 */

function _logintoboggan_toggleboggan ($form) {

  drupal_add_js(_logintoboggan_toggleboggan_js(), 'inline');

  $pre = '<div id="toboggan-container" class="toboggan-container">';
  $pre .= '<div class="toboggan-login-link">';
  $pre .= l(theme('lt_login_link'), 'user/login', array('onclick' => "toggleboggan();this.blur();return false;"));
  $pre .= '</div>';

  //the block that will be toggled
  $pre .= '<div id="toboggan-login" class="user-login-block">';

  $form['pre'] = array('#value' => $pre, '#weight' => -300);
  $form['post'] = array('#value' => '</div></div>', '#weight' => 300);
  return $form;
}

function _logintoboggan_toggleboggan_js() {
  return '
  $(function() {
      if (Drupal.jsEnabled) {
        $("#toboggan-login").hide();
      }
    }
  );
  function toggleboggan() {
    if (Drupal.jsEnabled) {
      $("#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');

  $form['login'] = array('#type' => 'fieldset',
    '#title' => t('Login'),
    '#prefix' => $version,
    );

  $form['login']['login_with_mail'] = array('#type' => 'radios',
    '#title' => t('Allow users to login using their e-mail address'),
    '#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.'),
    );

  $form['registration'] = array('#type' => 'fieldset',
    '#title' => t('Registration'),
    );

  $form['registration']['email_reg_confirm'] = array('#type' => 'radios',
    '#title' => t('Use two e-mail fields on registration form'),
    '#default_value' => variable_get('email_reg_confirm', 0),
    '#options' => array($_disabled, $_enabled),
    '#description' => t('User will have to type the same e-mail address into both fields. This helps to confirm that they\'ve typed the correct address.'),
    );

  if (module_exists('help')) {
    $help_text =  t(" More help in writing the e-mail message can be found at !help.", array('!help' => l('LoginToboggan help', 'admin/help/logintoboggan')));
  }
  else {
    $help_text = '';
  }
  $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 (note that this setting is merely a mirror of the !email_verification setting, and is merely here for convenience).  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.', array('!email_verification' => l('Require e-mail verification when a visitor creates an account', 'admin/user/settings'), '!settings' => l('user e-mail welcome message', 'admin/user/settings'))) . $help_text,
    );

  // Grab the roles that can be used for pre-auth.  Remove the anon role, as it's not a valid choice.
  $roles = user_roles(1);

  $form ['registration']['toboggan_role'] = array('#type' => 'select',
    '#title' => t('Non-authenticated role'),
    '#options' => $roles,
    '#default_value' => variable_get('toboggan_role', DRUPAL_AUTHENTICATED_RID),
    '#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'))),
    );

  $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>&lt;front&gt;</cite> page. You may also use <em>%uid</em> as a variable, and the user\'s user ID will be substituted in the path.'),
  );

  $form['registration']['redirect']['toboggan_redirect_on_confirm'] = array(
    '#type' => 'textfield',
    '#title' => t('Redirect path on Confirmation'),
    '#default_value' => variable_get('toboggan_redirect_on_confirm', ''),
    '#description' => t('Normally, after a user confirms their new account, they will be taken to their user page. Leave this setting blank if you wish to keep the default behavior. If you wish the user to go to a page of your choosing, then enter the path for it here. For instance, you may redirect them to a static page such as <cite>node/35</cite>, or to the <cite>&lt;front&gt;</cite> page. You may also use <em>%uid</em> as a variable, and the user\'s user ID will be substituted in the path.'),
  );

  $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.')
  );
  $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.')
  );

  return system_settings_form($form);
}

function logintoboggan_denied() {
  global $user;
  if ($user->uid == 0) {

    global $logintoboggan_denied;
    $logintoboggan_denied = TRUE;

    // 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;
}

// 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!?
// Because drupal_access_denied() sets $_REQUEST['destination'], and that
// overrides any other setting in drupal_goto(), we manipulate that
// directly here instead of returning values to the form code.
function logintoboggan_destination() {
  // Drupal has reset $_GET[q], so we need a workaround.
  if ($internal_path = substr(request_uri(), strlen(base_path()))) {
    // Clean URLs enabled, just pass destination through.
    if (variable_get('clean_url', 0)) {
      $_REQUEST['destination'] = $internal_path;
    }
    // Clean URLs disabled, so break apart the query string and
    // pull out the path.
    else {
      $internal_path = parse_url($internal_path);
      $queryarray = explode('&', $internal_path['query']);
      $path = str_replace('q=', '', $queryarray[0]);
      unset($queryarray[0]);
      $query = !empty($queryarray) ? '?'. implode('&', $queryarray) : '';
      $_REQUEST['destination'] = $path . $query;
    }
  }
  // Fall back to homepage.
  else {
    $_REQUEST['destination'] = variable_get('site_frontpage', 'node');
  }
}

/**
  * Modified version of user_validate_name
  * - 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("[^\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.');
  $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));
}


/**
  * Modified version of $DRUPAL_AUTHENTICATED_RID
  * - gets the role id for the "validating" user role.
  */
function logintoboggan_validating_id() {
  return variable_get('toboggan_role', DRUPAL_AUTHENTICATED_RID);
}


/**
 * Menu callback; process validate the e-mail address as a one time URL,
 * and redirects to the user page on success.
 */
function logintoboggan_validate_email($uid, $timestamp, $hashed_pass, $action = 'login') {

  $current = time();
  $uid = (int) $uid;
  // Some redundant checks for extra security
  if ($timestamp < $current && $uid && $account = user_load(array('uid' => $uid)) ) {
    // No time out for first time login.
    // This conditional checks that:
    // - the user is still in the pre-auth role or didn't set
    //   their own password.
    // - the hashed password is correct.
    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)) {
      watchdog('user', t('E-mail validation URL used for %name with timestamp @timestamp.', array('%name' => $account->name, '@timestamp' => $timestamp)));

      // Test here for a valid pre-auth -- if the pre-auth is set to the auth user, we
      // handle things a bit differently.
      $validating_id = logintoboggan_validating_id();
      $pre_auth = !variable_get('user_email_verification', TRUE) && $validating_id != DRUPAL_AUTHENTICATED_RID;

      _logintoboggan_process_validation($account);

      // Where do we redirect after confirming the account?
      $redirect = _logintoboggan_process_redirect(variable_get('toboggan_redirect_on_confirm', ''), $account);

      switch ($action) {
        // Proceed with normal user login, as long as it's open registration and their
        // account hasn't been blocked.
        case 'login':
          // 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.'));
          }
          if (!$account->status) {
            drupal_set_message(t('Your account is currently blocked -- login cancelled.'), 'error');
            drupal_goto('');
          }
          else {
            $edit = array();
            drupal_goto(logintoboggan_process_login($account, $edit, $redirect));
          }
          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;
      }
    }
    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');
    }
  }

  // Deny access, no more clues.
  // Everything will be in the watchdog's URL for the administrator to check.
  drupal_access_denied();
}

function _logintoboggan_process_validation($account) {
  // Test here for a valid pre-auth -- if the pre-auth is set to the auth user, we
  // handle things a bit differently.
  $validating_id = logintoboggan_validating_id();
  $pre_auth = !variable_get('user_email_verification', TRUE) && $validating_id != DRUPAL_AUTHENTICATED_RID;

  // Remove the pre-auth role from the user, unless they haven't been approved yet.
  if ($account->status) {
    if ($pre_auth) {
      db_query("DELETE FROM {users_roles} WHERE uid = %d AND rid = %d", $account->uid, $validating_id);
      // Since we're passing $account around to the update hook, remove
      // the pre-auth role from the roles array, and add in the auth user
      // role.
      $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      unset($account->roles[$validating_id]);
    }
  }
  // Allow other modules to react to email validation by invoking the user update hook.
  // This should only be triggered if LT's custom validation is active.
  if (!variable_get('user_email_verification', TRUE)) {
    $edit = array();
    $account->logintoboggan_email_validated = TRUE;
    user_module_invoke('update', $edit, $account);
  }
}

/**
 * Actually log the user on
 *
 * @param object $account
 *   The user object.
 * @param array $edit
 *   An array of form values if a form has been submitted.
 * @param string $redirect
 *   A string describing a redirect location, in the form
 *   that drupal_goto() will understand. Defaults to:
 *     'user/'. $user->uid
 */

function logintoboggan_process_login($account, $edit, $redirect = ''){
  global $user;
  $user = $account;

  watchdog('user', t('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 = '%s'", time(), $user->uid);

  // user has new permissions, so we clear their menu cache
  cache_clear_all($user->uid .':', 'cache_menu', TRUE);

  user_module_invoke('login', $edit, $user);

  // 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', t('User %name used one-time login link at time %timestamp.', array('%name' => $user->name, '%timestamp' => time())));
    drupal_set_message(t('You have just used your one-time login link. It is no longer possible to use this link to login. Please change your password.'));

    $destination = $redirect ? "destination=$redirect" : NULL;
    drupal_goto('user/'. $user->uid .'/edit', $destination);
  }

  if ($redirect != '') {
    return $redirect;
  }

  return 'user/'. $user->uid;
}

function logintoboggan_eml_validate_url($account){
  $timestamp = time();
  return url("user/validate/$account->uid/$timestamp/".logintoboggan_eml_rehash($account->pass, $timestamp, $account->mail), NULL, NULL, TRUE);
}

function logintoboggan_eml_rehash($password, $timestamp, $mail) {
  return user_pass_rehash($password, $timestamp, $mail);
}

/**
 * Implementation of hook_user().
 */
function logintoboggan_user($op, &$edit, &$user_edit, $category = NULL) {
  global $user;
  if ($op == 'form' && $category == 'account') {
    // User is editing their own account settings, or user admin
    // is editing their account.
    if ($user->uid == $user_edit->uid || user_access('administer users')) {
      // Display link to re-send validation e-mail.
      // Re-validate link appears if:
      //   1. Users can create their own password.
      //   2. User is still in the validating role.
      //   3. Users can create accounts without admin approval.
      //   4. The validating role is not the authorized user role.
      $validating_id = logintoboggan_validating_id();
      if (!variable_get('user_email_verification', TRUE) && array_key_exists($validating_id, $user_edit->roles) && (variable_get('user_register', 1) == 1) && ($validating_id > DRUPAL_AUTHENTICATED_RID)) {
        $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.'));
  }
  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);
  }
  elseif ($op == 'validate') {
    // If login with mail is enabled...
    if (variable_get('login_with_mail', 0)) {
      $uid = isset($user_edit->uid) ? $user_edit->uid : 0;
      // Check that no user is using this name for their email address.
      if (isset($edit['name']) && db_result(db_query("SELECT uid FROM {users} WHERE LOWER(mail) = LOWER('%s') AND uid <> %d", $edit['name'], $uid))) {
        form_set_error('name', t('This name has already been taken by another user.'));
      }
      // Check that no user is using this email address for their name.
      if (isset($edit['mail']) && db_result(db_query("SELECT uid FROM {users} WHERE LOWER(name) = LOWER('%s') AND uid <> %d", $edit['mail'], $uid))) {
        form_set_error('mail', t('This e-mail has already been taken by another user.'));
      }
    }
  }
}

/**
 * Re-sends validation e-mail to user specified by $uid.
 */
function logintoboggan_resend_validation($uid) {
  global $base_url;

  $account = user_load(array('uid' => $uid));

  // Variables to replace in e-mail
  $pass = t('If required, you may reset your password from: !url', array('!url' => url('user/password', NULL, NULL, TRUE)));
  $variables = array('!username' => $account->name, '!site' => variable_get('site_name', 'drupal'), '!password' => $pass, '!uri' => $base_url, '!uri_brief' => substr($base_url, strlen(_logintoboggan_protocol() .'://')), '!mailto' => $account->mail, '!date' => format_date(time()), '!login_uri' => url('user', NULL, NULL, TRUE), '!edit_uri' => url('user/'. $account->uid .'/edit', NULL, NULL, TRUE), '!login_url' => logintoboggan_eml_validate_url($account));

  // Prepare and send e-mail.
  $from = variable_get('site_mail', ini_get('sendmail_from'));
  $subject = _user_mail_text('welcome_subject', $variables);
  $body = _user_mail_text('welcome_body', $variables);
  drupal_mail('logintoboggan-resend-validation', $account->mail, $subject, $body, $from);

  // Notify admin or user that e-mail was sent and return to user edit form.
  if (user_access('administer users')) {
    drupal_set_message(t("A validation e-mail has been sent to the user's e-mail address."));
  }
  else {
    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.'));
  }

  drupal_goto('user/'. $account->uid .'/edit');
}

function _logintoboggan_protocol() {
  return (($_SERVER['HTTPS'] == 'on') ? 'https' : 'http');
}

function _logintoboggan_process_redirect($redirect, $account) {
  $variables = array('%uid' => $account->uid);
  $redirect = strtr($redirect, $variables);

  return $redirect;
}

/**
 * Resets the the site 403 variable to the default if the module is disabled
 * and the toboggan redirect on access denied is enabled.
 */
function logintoboggan_site_403_validate($form_id, $form_values) {
  // The check order is important:
  //   1. Is the module disabled?  Skip if so.
  //   2. Has the module been selected to be disabled?
  //   3. Is the current site 403 toboggan/denied?
  // Only reset the site 403 variable if 2 and 3 are true.
  if (!isset($form_values['disabled_modules']['logintoboggan']) && !$form_values['status']['logintoboggan'] && (variable_get('site_403', '') == 'toboggan/denied')) {
    variable_set('site_403', '');
  }
}

/**
 * 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.
 *
 * @param $form_id ID of the submitted form.
 * @param $form_values Submitted form values.
 */
function logintoboggan_flip_user_email_verification($form_id, $form_values) {
  $value = $form_values['user_email_verification'] ? FALSE : TRUE;
  variable_set('user_email_verification', $value);
}

/**
 *
 * THEME FUNCTIONS!
 *
 * You may override and change any of these custom HTML output functions
 * by copy/pasting them into your template.php file, at which point you can
 * customize anything, provided you are using the default phptemplate engine.
 *
 * For more info on overriding theme functions, see http://drupal.org/node/55126
 */

/**
 * Theme the username title of the user login form
 * and the user login block.
 */
function theme_lt_username_title($form_id) {
  switch ($form_id) {
    case 'user_login':
      // Label text for the username field on the /user/login page.
      return t('Username or e-mail address');
      break;

    case 'user_login_block':
      // Label text for the username field when shown in a block.
      return t('Username or e-mail');
      break;
  }
}

/**
 * Theme the username description of the user login form
 * and the user login block.
 */
function theme_lt_username_description($form_id) {
  switch ($form_id) {
    case 'user_login':
      if (variable_get('drupal_authentication_service', FALSE) && count(user_auth_help_links()) > 0) {
        // If drupal_authentication_service is enabled, this is
        // the username field's description when shown on the /user/login page.
        return 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())));
      }
      else {
        // The username field's description when shown on the /user/login page.
        return t('You may login with either your assigned username or your e-mail address.');
      }
      break;
    case 'user_login_block':
      return t('');
      break;
  }
}

/**
 * Theme the password title of the user login form
 * and the user login block.
 */
function theme_lt_password_title($form_id) {
  // Label text for the password field.
  return t('Password');
}

/**
 * Theme the password description of the user login form
 * and the user login block.
 */
function theme_lt_password_description($form_id) {
  switch ($form_id) {
    case 'user_login':
      // The password field's description on the /user/login page.
      return t('The password field is case sensitive.');
      break;

    case 'user_login_block':
      // If showing the login form in a block, don't print any descriptive text.
      return t('');
      break;
  }
}

/**
 * Theme the Access Denied message.
 */
function theme_lt_access_denied() {
  return t('You are not authorized to access this page.');
}

/**
 * Theme the loggedinblock that shows for logged-in users.
 */
function theme_lt_loggedinblock(){
  global $user;
  return check_plain($user->name) .' | ' . l(t('Log out'), 'logout');
}

/**
 * Custom theme function for the login/register link.
 */
function theme_lt_login_link() {
  // Only display register text if registration is allowed.
  if (variable_get('user_register', 1)) {
    return t('Login/Register');
  }
  else {
    return t('Login');
  }
}