File: Auth.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (1302 lines) | stat: -rw-r--r-- 43,088 bytes parent folder | download | duplicates (2)
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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
<?php
/**
 * The parameter name for the logout reason.
 */
define('AUTH_REASON_PARAM', 'logout_reason');

/**
 * The parameter name for the logout message used with type
 * AUTH_REASON_MESSAGE.
 */
define('AUTH_REASON_MSG_PARAM', 'logout_msg');

/**
 * The 'badlogin' reason.
 *
 * The following 'reasons' for the logout screen are recognized:
 * <pre>
 *   'badlogin'   --  Bad username and/or password
 *   'browser'    --  A browser change was detected
 *   'failed'     --  Login failed
 *   'logout'     --  Logout due to user request
 *   'message'    --  Logout with custom message in AUTH_REASON_MSG_PARAM
 *   'session'    --  Logout due to session expiration
 *   'sessionip'  --  Logout due to change of IP address during session
 * </pre>
 */
define('AUTH_REASON_BADLOGIN', 'badlogin');

/**
 * The 'browser' reason.
 */
define('AUTH_REASON_BROWSER', 'browser');

/**
 * The 'failed' reason.
 */
define('AUTH_REASON_FAILED', 'failed');

/**
 * The 'expired' reason.
 */
define('AUTH_REASON_EXPIRED', 'expired');

/**
 * The 'logout' reason.
 */
define('AUTH_REASON_LOGOUT', 'logout');

/**
 * The 'message' reason.
 */
define('AUTH_REASON_MESSAGE', 'message');

/**
 * The 'session' reason.
 */
define('AUTH_REASON_SESSION', 'session');

/**
 * The 'sessionip' reason.
 */
define('AUTH_REASON_SESSIONIP', 'sessionip');

/**
 * The Auth:: class provides a common abstracted interface into the various
 * backends for the Horde authentication system.
 *
 * $Horde: framework/Auth/Auth.php,v 1.142.10.23 2006/08/14 02:48:48 chuck Exp $
 *
 * Copyright 1999-2006 Chuck Hagenbuch <chuck@horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @since   Horde 1.3
 * @package Horde_Auth
 */
class Auth {

    /**
     * An array of capabilities, so that the driver can report which
     * operations it supports and which it doesn't.
     *
     * @var array
     */
    var $capabilities = array('add'           => false,
                              'update'        => false,
                              'resetpassword' => false,
                              'remove'        => false,
                              'list'          => false,
                              'groups'        => false,
                              'transparent'   => false);

    /**
     * Hash containing parameters.
     *
     * @var array
     */
    var $_params = array();

    /**
     * The credentials currently being authenticated.
     *
     * @access protected
     *
     * @var array
     */
    var $_authCredentials = array();

    /**
     * Returns the name of the concrete Auth implementation.
     *
     * @return string  The Auth implementation name.
     */
    function getDriver()
    {
        return str_replace('auth_', '', strtolower(get_class($this)));
    }

    /**
     * Finds out if a set of login credentials are valid, and if requested,
     * mark the user as logged in in the current session.
     *
     * @param string $userId      The userId to check.
     * @param array $credentials  The credentials to check.
     * @param boolean $login      Whether to log the user in. If false, we'll
     *                            only test the credentials and won't modify
     *                            the current session. Defaults to true.
     * @param string $realm       The authentication realm to check.
     *
     * @return boolean  Whether or not the credentials are valid.
     */
    function authenticate($userId, $credentials, $login = true, $realm = null)
    {
        global $conf;

        $auth = false;
        $userId = trim($userId);

        if (!empty($conf['hooks']['preauthenticate'])) {
            include_once HORDE_BASE . '/config/hooks.php';
            if (function_exists('_horde_hook_preauthenticate')) {
                if (!call_user_func('_horde_hook_preauthenticate', $userId, $credentials, $realm)) {
                    if ($this->_getAuthError() != AUTH_REASON_MESSAGE) {
                        $this->_setAuthError(AUTH_REASON_FAILED);
                    }
                    return false;
                }
            }
        }

        /* Store the credentials being checked so that subclasses can modify
         * them if necessary (like transparent auth does). */
        $this->_authCredentials = array(
            'userId' => $userId,
            'credentials' => $credentials,
            'realm' => $realm,
            'changeRequested' => false
        );

        if ($authenticated = $this->_authenticate($userId, $credentials)) {
            if (is_a($authenticated, 'PEAR_Error')) {
                return false;
            }
            if (!empty($conf['hooks']['postauthenticate'])) {
                include_once HORDE_BASE . '/config/hooks.php';
                if (function_exists('_horde_hook_postauthenticate')) {
                    if (!call_user_func('_horde_hook_postauthenticate', $userId, $credentials, $realm)) {
                        if ($this->_getAuthError() != AUTH_REASON_MESSAGE) {
                            $this->_setAuthError(AUTH_REASON_FAILED);
                        }
                        return false;
                    }
                }
            }

            if ($login) {
                $this->setAuth($this->_authCredentials['userId'],
                               $this->_authCredentials['credentials'],
                               $this->_authCredentials['realm'],
                               $this->_authCredentials['changeRequested']);
                $auth = true;
            } else {
                if (!$this->_checkSessionIP()) {
                    $this->_setAuthError(AUTH_REASON_SESSIONIP);
                    return false;
                } elseif (!$this->_checkBrowserString()) {
                    $this->_setAuthError(AUTH_REASON_BROWSER);
                    return false;
                }
                $auth = true;
            }
        }

        return $auth;
    }

    /**
     * Formats a password using the current encryption.
     *
     * @param string $plaintext      The plaintext password to encrypt.
     * @param string $salt           The salt to use to encrypt the password.
     *                               If not present, a new salt will be
     *                               generated.
     * @param string $encryption     The kind of pasword encryption to use.
     *                               Defaults to md5-hex.
     * @param boolean $show_encrypt  Some password systems prepend the kind of
     *                               encryption to the crypted password ({SHA},
     *                               etc). Defaults to false.
     *
     * @return string  The encrypted password.
     */
    function getCryptedPassword($plaintext, $salt = '',
                                $encryption = 'md5-hex', $show_encrypt = false)
    {
        /* Get the salt to use. */
        $salt = Auth::getSalt($encryption, $salt, $plaintext);

        /* Encrypt the password. */
        switch ($encryption) {
        case 'plain':
            return $plaintext;

        case 'msad':
            return String::convertCharset('"' . $plaintext . '"', 'ISO-8859-1', 'UTF-16LE');

        case 'sha':
            $encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
            return ($show_encrypt) ? '{SHA}' . $encrypted : $encrypted;

        case 'crypt':
        case 'crypt-des':
        case 'crypt-md5':
        case 'crypt-blowfish':
            return ($show_encrypt ? '{crypt}' : '') . crypt($plaintext, $salt);

        case 'md5-base64':
            $encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
            return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;

        case 'ssha':
            $encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt) . $salt);
            return ($show_encrypt) ? '{SSHA}' . $encrypted : $encrypted;

        case 'smd5':
            $encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt) . $salt);
            return ($show_encrypt) ? '{SMD5}' . $encrypted : $encrypted;

        case 'aprmd5':
            $length = strlen($plaintext);
            $context = $plaintext . '$apr1$' . $salt;
            $binary = Auth::_bin(md5($plaintext . $salt . $plaintext));

            for ($i = $length; $i > 0; $i -= 16) {
                $context .= substr($binary, 0, ($i > 16 ? 16 : $i));
            }
            for ($i = $length; $i > 0; $i >>= 1) {
                $context .= ($i & 1) ? chr(0) : $plaintext{0};
            }

            $binary = Auth::_bin(md5($context));

            for ($i = 0; $i < 1000; $i++) {
                $new = ($i & 1) ? $plaintext : substr($binary, 0,16);
                if ($i % 3) {
                    $new .= $salt;
                }
                if ($i % 7) {
                    $new .= $plaintext;
                }
                $new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
                $binary = Auth::_bin(md5($new));
            }

            $p = array();
            for ($i = 0; $i < 5; $i++) {
                $k = $i + 6;
                $j = $i + 12;
                if ($j == 16) {
                    $j = 5;
                }
                $p[] = Auth::_toAPRMD5((ord($binary[$i]) << 16) |
                                       (ord($binary[$k]) << 8) |
                                       (ord($binary[$j])),
                                       5);
            }

            return '$apr1$' . $salt . '$' . implode('', $p) . Auth::_toAPRMD5(ord($binary[11]), 3);

        case 'md5-hex':
        default:
            return ($show_encrypt) ? '{MD5}' . md5($plaintext) : md5($plaintext);
        }
    }

    /**
     * Returns a salt for the appropriate kind of password encryption.
     * Optionally takes a seed and a plaintext password, to extract the seed
     * of an existing password, or for encryption types that use the plaintext
     * in the generation of the salt.
     *
     * @param string $encryption  The kind of pasword encryption to use.
     *                            Defaults to md5-hex.
     * @param string $seed        The seed to get the salt from (probably a
     *                            previously generated password). Defaults to
     *                            generating a new seed.
     * @param string $plaintext   The plaintext password that we're generating
     *                            a salt for. Defaults to none.
     *
     * @return string  The generated or extracted salt.
     */
    function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
    {
        // Encrypt the password.
        switch ($encryption) {
        case 'crypt':
        case 'crypt-des':
            if ($seed) {
                return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
            } else {
                return substr(md5(mt_rand()), 0, 2);
            }

        case 'crypt-md5':
            if ($seed) {
                return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
            } else {
                return '$1$' . substr(md5(mt_rand()), 0, 8) . '$';
            }

        case 'crypt-blowfish':
            if ($seed) {
                return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
            } else {
                return '$2$' . substr(md5(mt_rand()), 0, 12) . '$';
            }

        case 'ssha':
            if ($seed) {
                return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
            } else {
                return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
            }

        case 'smd5':
            if ($seed) {
                return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
            } else {
                return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
            }

        case 'aprmd5':
            /* 64 characters that are valid for APRMD5 passwords. */
            $APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

            if ($seed) {
                return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
            } else {
                $salt = '';
                for ($i = 0; $i < 8; $i++) {
                    $salt .= $APRMD5{rand(0, 63)};
                }
                return $salt;
            }

        default:
            return '';
        }
    }

    /**
     * Generates a random, hopefully pronounceable, password. This can be used
     * when resetting automatically a user's password.
     *
     * @return string A random password
     */
    function genRandomPassword()
    {
        $vowels    = 'aeiouy';
        $constants = 'bcdfghjklmnpqrstvwxz';
        $numbers   = '0123456789';

        /* Alternate constant and vowel random chars with two random numbers
         * at the end. This should produce a fairly pronounceable password. */
        $chars[0] = substr($constants, mt_rand(0, strlen($constants) - 1), 1);
        $chars[1] = substr($vowels, mt_rand(0, strlen($vowels) - 1), 1);
        $chars[2] = substr($constants, mt_rand(0, strlen($constants) - 1), 1);
        $chars[3] = substr($vowels, mt_rand(0, strlen($vowels) - 1), 1);
        $chars[4] = substr($constants, mt_rand(0, strlen($constants) - 1), 1);
        $chars[5] = substr($numbers, mt_rand(0, strlen($numbers) - 1), 1);
        $chars[6] = substr($numbers, mt_rand(0, strlen($numbers) - 1), 1);

        return implode('', $chars);
    }

    /**
     * Adds a set of authentication credentials.
     *
     * @abstract
     *
     * @param string $userId      The userId to add.
     * @param array $credentials  The credentials to use.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function addUser($userId, $credentials)
    {
        return PEAR::raiseError('unsupported');
    }

    /**
     * Updates a set of authentication credentials.
     *
     * @abstract
     *
     * @param string $oldID        The old userId.
     * @param string $newID        The new userId.
     * @param array $credentials   The new credentials
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function updateUser($oldID, $newID, $credentials)
    {
        return PEAR::raiseError('unsupported');
    }

    /**
     * Deletes a set of authentication credentials.
     *
     * @abstract
     *
     * @param string $userId  The userId to delete.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function removeUser($userId)
    {
        return PEAR::raiseError('unsupported');
    }

    /**
     * Calls all applications' removeUser API methods.
     *
     * @param string $userId  The userId to delete.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function removeUserData($userId)
    {
        global $registry;

        foreach ($registry->listApps(array('notoolbar', 'hidden', 'active', 'admin')) as $app) {
            if ($registry->hasMethod('removeUserData', $app)) {
                if (is_a($result = $registry->callByPackage($app, 'removeUserData', array($userId)), 'PEAR_Error')) {
                    return $result;
                }
            }
        }

        return false;
    }

    /**
     * Lists all users in the system.
     *
     * @abstract
     *
     * @return mixed  The array of userIds, or a PEAR_Error object on failure.
     */
    function listUsers()
    {
        return PEAR::raiseError('unsupported');
    }

    /**
     * Checks if $userId exists in the system.
     *
     * @abstract
     *
     * @param string $userId User ID for which to check
     *
     * @return boolean  Whether or not $userId already exists.
     */
    function exists($userId)
    {
        return in_array($userId, $this->listUsers());
    }

    /**
     * Automatic authentication: Finds out if the client matches an allowed IP
     * block.
     *
     * @abstract
     *
     * @return boolean  Whether or not the client is allowed.
     */
    function transparent()
    {
        return false;
    }

    /**
     * Checks if there is a session with valid auth information. for the
     * specified user. If there isn't, but the configured Auth driver supports
     * transparent authentication, then we try that.
     *
     * @param string $realm  The authentication realm to check.
     *
     * @return boolean  Whether or not the user is authenticated.
     */
    function isAuthenticated($realm = null)
    {
        if (isset($_SESSION['__auth'])) {
            if (!empty($_SESSION['__auth']['authenticated']) &&
                !empty($_SESSION['__auth']['userId']) &&
                ($_SESSION['__auth']['realm'] == $realm)) {
                if (!Auth::_checkSessionIP()) {
                    Auth::_setAuthError(AUTH_REASON_SESSIONIP);
                    return false;
                } elseif (!Auth::_checkBrowserString()) {
                    Auth::_setAuthError(AUTH_REASON_BROWSER);
                    return false;
                } else {
                    return true;
                }
            }
        }

        // Try transparent authentication now.
        $auth = &Auth::singleton($GLOBALS['conf']['auth']['driver']);
        if ($auth->hasCapability('transparent') &&
            $auth->transparent()) {
            return Auth::isAuthenticated($realm);
        }

        return false;
    }

    /**
     * Returns the currently logged in user, if there is one.
     *
     * @return mixed  The userId of the current user, or false if no user is
     *                logged in.
     */
    function getAuth()
    {
        if (isset($_SESSION['__auth'])) {
            if (!empty($_SESSION['__auth']['authenticated']) &&
                !empty($_SESSION['__auth']['userId'])) {
                return $_SESSION['__auth']['userId'];
            }
        }

        return false;
    }

    /**
     * Return whether the authentication backend requested a password change.
     *
     * @return boolean Whether the backend requested a password change.
     */
    function isPasswordChangeRequested()
    {
        if (isset($_SESSION['__auth']) &&
            !empty($_SESSION['__auth']['authenticated']) &&
            !empty($_SESSION['__auth']['changeRequested'])) {
            return true;
        }

        return false;
    }

    /**
     * Returns the curently logged-in user without any domain information
     * (e.g., bob@example.com would be returned as 'bob').
     *
     * @return mixed  The user ID of the current user, or false if no user
     *                is logged in.
     */
    function getBareAuth()
    {
        $user = Auth::getAuth();
        if ($user) {
            $pos = strpos($user, '@');
            if ($pos !== false) {
                $user = substr($user, 0, $pos);
            }
        }

        return $user;
    }

    /**
     * Returns the domain of currently logged-in user (e.g., bob@example.com
     * would be returned as 'example.com').
     *
     * @since Horde 3.0.6
     *
     * @return mixed  The domain suffix of the current user, or false.
     */
    function getAuthDomain()
    {
        if ($user = Auth::getAuth()) {
            $pos = strpos($user, '@');
            if ($pos !== false) {
                return substr($user, $pos + 1);
            }
        }

        return false;
    }

    /**
     * Returns the requested credential for the currently logged in user, if
     * present.
     *
     * @param string $credential  The credential to retrieve.
     *
     * @return mixed  The requested credential, or false if no user is
     *                logged in.
     */
    function getCredential($credential)
    {
        if (!empty($_SESSION['__auth']) &&
            !empty($_SESSION['__auth']['authenticated'])) {
            require_once 'Horde/Secret.php';
            $credentials = @unserialize(Secret::read(Secret::getKey('auth'), $_SESSION['__auth']['credentials']));
        } else {
            return false;
        }

        if (is_array($credentials) &&
            isset($credentials[$credential])) {
            return $credentials[$credential];
        } else {
            return false;
        }
    }

    /**
     * Sets the requested credential for the currently logged in user.
     *
     * @param string $credential  The credential to set.
     * @param string $value       The value to set the credential to.
     */
    function setCredential($credential, $value)
    {
        if (!empty($_SESSION['__auth']) &&
            !empty($_SESSION['__auth']['authenticated'])) {
            require_once 'Horde/Secret.php';
            $credentials = @unserialize(Secret::read(Secret::getKey('auth'), $_SESSION['__auth']['credentials']));
            if (is_array($credentials)) {
                $credentials[$credential] = $value;
            } else {
                $credentials = array($credential => $value);
            }
            $_SESSION['__auth']['credentials'] = Secret::write(Secret::getKey('auth'), serialize($credentials));
        }
    }

    /**
     * Sets a variable in the session saying that authorization has succeeded,
     * note which userId was authorized, and note when the login took place.
     *
     * If a user name hook was defined in the configuration, it gets applied
     * to the userId at this point.
     *
     * @param string $userId            The userId who has been authorized.
     * @param array $credentials        The credentials of the user.
     * @param string $realm             The authentication realm to use.
     * @param boolean $changeRequested  Whether to request that the user change
     *                                  their password.
     */
    function setAuth($userId, $credentials, $realm = null, $changeRequested = false)
    {
        $userId = trim($userId);
        $userId = Auth::addHook($userId);

        /* If we're already set with this userId, don't continue. */
        if (isset($_SESSION['__auth']['userId']) &&
            $_SESSION['__auth']['userId'] == $userId) {
            return;
        }

        /* Clear any existing info. */
        $this->clearAuth($realm);

        require_once 'Horde/Secret.php';
        $credentials = Secret::write(Secret::getKey('auth'), serialize($credentials));

        if (!empty($realm)) {
            $userId .= '@' . $realm;
        }

        $_SESSION['__auth'] = array(
            'authenticated' => true,
            'userId' => $userId,
            'credentials' => $credentials,
            'realm' => $realm,
            'timestamp' => time(),
            'remote_addr' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null,
            'browser' => $GLOBALS['browser']->getAgentString(),
            'changeRequested' => $changeRequested
        );

        /* Reload preferences for the new user. */
        $GLOBALS['registry']->loadPrefs();
        NLS::setLang($GLOBALS['prefs']->getValue('language'));

        /* Fetch the user's last login time. */
        $old_login = @unserialize($GLOBALS['prefs']->getValue('last_login'));

        /* Display it, if we have a notification object and the
         * show_last_login preference is active. */
        if (isset($GLOBALS['notification']) && $GLOBALS['prefs']->getValue('show_last_login')) {
            if (empty($old_login['time'])) {
                $GLOBALS['notification']->push(_("Last login: Never"), 'horde.message');
            } else {
                if (empty($old_login['host'])) {
                    $GLOBALS['notification']->push(sprintf(_("Last login: %s"), strftime('%c', $old_login['time'])), 'horde.message');
                } else {
                    $GLOBALS['notification']->push(sprintf(_("Last login: %s from %s"), strftime('%c', $old_login['time']), $old_login['host']), 'horde.message');
                }
            }
        }

        // Set the user's last_login information.
        $host = empty($_SERVER['HTTP_X_FORWARDED_FOR'])
            ? $_SERVER['REMOTE_ADDR']
            : $_SERVER['HTTP_X_FORWARDED_FOR'];
        $last_login = array('time' => time(),
                            'host' => @gethostbyaddr($host));
        $GLOBALS['prefs']->setValue('last_login', serialize($last_login));

        if ($changeRequested) {
            $GLOBALS['notification']->push(_("Your password has expired."),
                                           'horde.message');
            if ($this->hasCapability('update')) {
                /* A bit of a kludge.  URL is set from the login screen, but
                 * we aren't completely certain we got here from the login
                 * screen.  So any screen which calls setAuth() which has a
                 * url will end up going there.  Should be OK. */
                $url_param = Util::getFormData('url');

                if ($url_param) {
                    $url = Horde::url(Util::removeParameter($url_param,
                                                            session_name()),
                                      true);
                    $return_to = $GLOBALS['registry']->get('webroot', 'horde') .
                                 '/index.php';
                    $return_to = Util::addParameter($return_to, 'url', $url);
                } else {
                    $return_to = Horde::url($GLOBALS['registry']->get('webroot', 'horde')
                                 . '/index.php');
                }

                $url = Horde::applicationUrl('services/changepassword.php');
                $url = Util::addParameter($url,
                                          array('return_to' => $return_to),
                                          null, false);

                header('Location: ' . $url);
                exit;
            }
        }
    }

    /**
     * Clears any authentication tokens in the current session.
     *
     * @param string $realm  The authentication realm to clear.
     */
    function clearAuth($realm = null)
    {
        if (!empty($realm) && isset($_SESSION['__auth'][$realm])) {
            $_SESSION['__auth'][$realm] = array();
            $_SESSION['__auth'][$realm]['authenticated'] = false;
        } elseif (isset($_SESSION['__auth'])) {
            $_SESSION['__auth'] = array();
            $_SESSION['__auth']['authenticated'] = false;
        }

        /* Remove the user's cached preferences if they are present. */
        if (isset($GLOBALS['registry'])) {
            $GLOBALS['registry']->unloadPrefs();
        }
    }

    /**
     * Is the current user an administrator?
     *
     * @param string $permission  Allow users with this permission admin access
     *                            in the current context.
     * @param integer $permlevel  The level of permissions to check for
     *                            (PERMS_EDIT, PERMS_DELETE, etc). Defaults
     *                            to PERMS_EDIT.
     * @param string $user        The user to check. Defaults to Auth::getAuth().
     *
     * @return boolean  Whether or not this is an admin user.
     */
    function isAdmin($permission = null, $permlevel = null, $user = null)
    {
        global $conf;

        if ($user === null) {
            $user = Auth::getAuth();
        }

        if (@is_array($conf['auth']['admins'])) {
            if ($user && in_array($user, $conf['auth']['admins'])) {
                return true;
            }
        }

        if (!is_null($permission)) {
            if (is_null($permlevel)) {
                $permlevel = PERMS_EDIT;
            }
            return $GLOBALS['perms']->hasPermission($permission, $user, $permlevel);
        }

        return false;
    }

    /**
     * Applies a hook defined by the function _username_hook_frombackend() to
     * the given user name if this function exists and user hooks are enabled.
     *
     * This method should be called if a backend's user name needs to be
     * converted to a (unique) Horde user name.
     *
     * @param string $userId  The original user name.
     *
     * @return string  The user name with the hook applied to it.
     */
    function addHook($userId)
    {
        global $conf;

        if (!empty($conf['hooks']['username'])) {
            require_once HORDE_BASE . '/config/hooks.php';
            if (function_exists('_username_hook_frombackend')) {
                $userId = call_user_func('_username_hook_frombackend', $userId);
            }
        }

        return $userId;
    }

    /**
     * Applies a hook defined by the function _username_hook_tobackend() to
     * the given user name if this function exists and user hooks are enabled.
     *
     * This method should be called if a Horde user name needs to be converted
     * to a backend's user name or displayed to the user.
     *
     * @param string $userId  The Horde user name.
     *
     * @return string  The user name with the hook applied to it.
     */
    function removeHook($userId)
    {
        global $conf;

        if (!empty($conf['hooks']['username'])) {
            require_once HORDE_BASE . '/config/hooks.php';
            if (function_exists('_username_hook_tobackend')) {
                $userId = call_user_func('_username_hook_tobackend', $userId);
            }
        }

        return $userId;
    }

    /**
     * Queries the current Auth object to find out if it supports the given
     * capability.
     *
     * @param string $capability  The capability to test for.
     *
     * @return boolean  Whether or not the capability is supported.
     */
    function hasCapability($capability)
    {
        return !empty($this->capabilities[$capability]);
    }

    /**
     * Returns the URI of the login screen for the current authentication
     * method.
     *
     * @param string $app  The application to use.
     * @param string $url  The URL to redirect to after login.
     *
     * @return string  The login screen URI.
     */
    function getLoginScreen($app = 'horde', $url = '')
    {
        global $conf;
        $auth = &Auth::singleton($conf['auth']['driver']);
        return $auth->_getLoginScreen($app, $url);
    }

    /**
     * Returns the named parameter for the current auth driver.
     *
     * @param string $param  The parameter to fetch.
     *
     * @return string  The parameter's value.
     */
    function getParam($param)
    {
        return isset($this->_params[$param]) ? $this->_params[$param] : null;
    }

    /**
     * Returns the name of the authentication provider.
     *
     * @param string $driver  Used by recursive calls when untangling composite
     *                        auth.
     * @param array  $params  Used by recursive calls when untangling composite
     *                        auth.
     *
     * @return string  The name of the driver currently providing
     *                 authentication.
     */
    function getProvider($driver = null, $params = null)
    {
        global $conf;

        if (is_null($driver)) {
            $driver = $conf['auth']['driver'];
        }
        if (is_null($params)) {
            $params = Horde::getDriverConfig('auth',
                is_array($driver) ? $driver[1] : $driver);
        }

        if ($driver == 'application') {
            return isset($params['app']) ? $params['app'] : 'application';
        } elseif ($driver == 'composite') {
            if (($login_driver = Auth::_getDriverByParam('loginscreen_switch', $params)) &&
                !empty($params['drivers'][$login_driver])) {
                return Auth::getProvider($params['drivers'][$login_driver]['driver'],
                                         isset($params['drivers'][$login_driver]['params']) ? $params['drivers'][$login_driver]['params'] : null);
            }
            return 'composite';
        } else {
            return $driver;
        }
    }

    /**
     * Returns the logout reason.
     *
     * @return string One of the logout reasons (see the AUTH_LOGOUT_*
     *                constants for the valid reasons).  Returns null if there
     *                is no logout reason present.
     */
    function getLogoutReason()
    {
        if (isset($GLOBALS['__autherror']['type'])) {
            return $GLOBALS['__autherror']['type'];
        } else {
            return Util::getFormData(AUTH_REASON_PARAM);
        }
    }

    /**
     * Returns the status string to use for logout messages.
     *
     * @return string  The logout reason string.
     */
    function getLogoutReasonString()
    {
        switch (Auth::getLogoutReason()) {
        case AUTH_REASON_SESSION:
            $text = sprintf(_("Your %s session has expired. Please login again."), $GLOBALS['registry']->get('name'));
            break;

        case AUTH_REASON_SESSIONIP:
            $text = sprintf(_("Your Internet Address has changed since the beginning of your %s session. To protect your security, you must login again."), $GLOBALS['registry']->get('name'));
            break;

        case AUTH_REASON_BROWSER:
            $text = sprintf(_("Your browser appears to have changed since the beginning of your %s session. To protect your security, you must login again."), $GLOBALS['registry']->get('name'));
            break;

        case AUTH_REASON_LOGOUT:
            $text = _("You have been logged out.");
            break;

        case AUTH_REASON_FAILED:
            $text = _("Login failed.");
            break;

        case AUTH_REASON_BADLOGIN:
            $text = _("Login failed because your username or password was entered incorrectly.");
            break;

        case AUTH_REASON_EXPIRED:
            $text = _("Your login has expired.");
            break;

        case AUTH_REASON_MESSAGE:
            if (isset($GLOBALS['__autherror']['msg'])) {
                $text = $GLOBALS['__autherror']['msg'];
            } else {
                $text = Util::getFormData(AUTH_REASON_MSG_PARAM);
            }
            break;

        default:
            $text = '';
            break;
        }

        return $text;
    }

    /**
     * Generates the correct parameters to pass to the given logout URL.
     *
     * If no reason/msg is passed in, use the current global authentication
     * error message.
     *
     * @param string $url     The URL to redirect to.
     * @param string $reason  The reason for logout.
     * @param string $msg     If reason is AUTH_REASON_MESSAGE, the message to
     *                        display to the user.
     * @return string The formatted URL
     */
    function addLogoutParameters($url, $reason = null, $msg = null)
    {
        if (is_null($reason)) {
            $reason = Auth::getLogoutReason();
        }

        if ($reason) {
            $url = Util::addParameter($url, AUTH_REASON_PARAM, $reason, false);
            if ($reason == AUTH_REASON_MESSAGE) {
                if (is_null($msg)) {
                    $msg = Auth::getLogoutReasonString();
                }
                $url = Util::addParameter($url, AUTH_REASON_MSG_PARAM, $msg, false);
            }
        }

        return $url;
    }

    /**
     * Returns the URI of the login screen for this authentication object.
     *
     * @access private
     *
     * @param string $app  The application to use.
     * @param string $url  The URL to redirect to after login.
     *
     * @return string  The login screen URI.
     */
    function _getLoginScreen($app = 'horde', $url = '')
    {
        $login = Horde::url($GLOBALS['registry']->get('webroot', $app) . '/login.php', true);
        if (!empty($url)) {
            $login = Util::addParameter($login, 'url', $url);
        }
        return $login;
    }

    /**
     * Authentication stub.
     *
     * @abstract
     * @access private
     *
     * @return boolean  False.
     */
    function _authenticate()
    {
        return false;
    }

    /**
     * Sets the error message for an invalid authentication.
     *
     * @access private
     *
     * @param string $type  The type of error (AUTH_REASON constant).
     * @param string $msg   The error message/reason for invalid
     *                      authentication.
     */
    function _setAuthError($type, $msg = null)
    {
        $GLOBALS['__autherror'] = array();
        $GLOBALS['__autherror']['type'] = $type;
        $GLOBALS['__autherror']['msg'] = $msg;
    }

    /**
     * Returns the error type for an invalid authentication or false on error.
     *
     * @access private
     *
     * @return mixed Error type or false on error
     */
    function _getAuthError()
    {
        if (isset($GLOBALS['__autherror']['type'])) {
            return $GLOBALS['__autherror']['type'];
        }

        return false;
    }

    /**
     * Returns the appropriate authentication driver, if any, selecting by the
     * specified parameter.
     *
     * @access private
     *
     * @param string $name          The parameter name.
     * @param array $params         The parameter list.
     * @param string $driverparams  A list of parameters to pass to the driver.
     *
     * @return mixed Return value or called user func or null if unavailable
     */
    function _getDriverByParam($name, $params, $driverparams = array())
    {
        if (isset($params[$name]) &&
            function_exists($params[$name])) {
            return call_user_func_array($params[$name], $driverparams);
        }

        return null;
    }

    /**
     * Performs check on session to see if IP Address has changed since the
     * last access.
     *
     * @access private
     *
     * @return boolean  True if IP Address is the same (or the check is
     *                  disabled), false if the address has changed.
     */
    function _checkSessionIP()
    {
        return (empty($GLOBALS['conf']['auth']['checkip']) ||
                (isset($_SESSION['__auth']['remote_addr']) && $_SESSION['__auth']['remote_addr'] == $_SERVER['REMOTE_ADDR']));
    }

    /**
     * Performs check on session to see if browser string has changed since
     * the last access.
     *
     * @access private
     *
     * @return boolean  True if browser string is the same, false if the
     *                  string has changed.
     */
    function _checkBrowserString()
    {
        return (empty($GLOBALS['conf']['auth']['checkbrowser']) ||
                $_SESSION['__auth']['browser'] == $GLOBALS['browser']->getAgentString());
    }

    /**
     * Converts to allowed 64 characters for APRMD5 passwords.
     *
     * @access private
     *
     * @param string  $value
     * @param integer $count
     *
     * @return string  $value converted to the 64 MD5 characters.
     */
    function _toAPRMD5($value, $count)
    {
        /* 64 characters that are valid for APRMD5 passwords. */
        $APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

        $aprmd5 = '';
        $count = abs($count);
        while (--$count) {
            $aprmd5 .= $APRMD5[$value & 0x3f];
            $value >>= 6;
        }
        return $aprmd5;
    }

    /**
     * Converts hexadecimal string to binary data.
     *
     * @access private
     *
     * @param string $hex  Hex data.
     *
     * @return string  Binary data.
     */
    function _bin($hex)
    {
        $bin = '';
        $length = strlen($hex);
        for ($i = 0; $i < $length; $i += 2) {
            $tmp = sscanf(substr($hex, $i, 2), '%x');
            $bin .= chr(array_shift($tmp));
        }
        return $bin;
    }

    /**
     * Attempts to return a concrete Auth instance based on $driver.
     *
     * @param mixed $driver  The type of concrete Auth subclass to return. This
     *                       is based on the storage driver ($driver). The code
     *                       is dynamically included. If $driver is an array,
     *                       then we will look in $driver[0]/lib/Auth/ for the
     *                       subclass implementation named $driver[1].php.
     * @param array $params  A hash containing any additional configuration or
     *                       connection parameters a subclass might need.
     *
     * @return Auth  The newly created concrete Auth instance, or false on an
     *               error.
     */
    function &factory($driver, $params = null)
    {
        if (is_array($driver)) {
            $app = $driver[0];
            $driver = $driver[1];
        }

        $driver = basename($driver);

        if (empty($driver) || ($driver == 'none')) {
            $auth = &new Auth();
            return $auth;
        }

        if (is_null($params)) {
            $params = Horde::getDriverConfig('auth', $driver);
        }

        ini_set('track_errors', 1);
        $include_error = '';
        if (!empty($app)) {
            @include_once $GLOBALS['registry']->get('fileroot', $app) . '/lib/Auth/' . $driver . '.php';
        } else {
            @include_once 'Horde/Auth/' . $driver . '.php';
        }
        if (isset($php_errormsg)) {
            $include_error = $php_errormsg;
        }
        ini_restore('track_errors');

        $class = 'Auth_' . $driver;
        if (class_exists($class)) {
            $auth = &new $class($params);
        } else {
            $auth = PEAR::raiseError('Auth Driver (' . $class . ') not found' . ($include_error ? ': ' . $include_error : '') . '.');
        }

        return $auth;
    }

    /**
     * Attempts to return a reference to a concrete Auth instance based on
     * $driver. It will only create a new instance if no Auth instance with
     * the same parameters currently exists.
     *
     * This should be used if multiple authentication sources (and, thus,
     * multiple Auth instances) are required.
     *
     * This method must be invoked as: $var = &Auth::singleton()
     *
     * @param string $driver  The type of concrete Auth subclass to return.
     *                        This is based on the storage driver ($driver).
     *                        The code is dynamically included.
     * @param array $params   A hash containing any additional configuration or
     *                        connection parameters a subclass might need.
     *
     * @return Auth  The concrete Auth reference, or false on an error.
     */
    function &singleton($driver, $params = null)
    {
        static $instances = array();

        if (is_null($params)) {
            $params = Horde::getDriverConfig('auth',
                is_array($driver) ? $driver[1] : $driver);
        }

        $signature = serialize(array($driver, $params));
        if (empty($instances[$signature])) {
            $instances[$signature] = &Auth::factory($driver, $params);
        }

        return $instances[$signature];
    }

}