File: Auth.php

package info (click to toggle)
php-auth 1.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze, wheezy
  • size: 480 kB
  • ctags: 764
  • sloc: php: 3,296; xml: 952; makefile: 65; sql: 4
file content (1365 lines) | stat: -rw-r--r-- 39,310 bytes parent folder | download
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
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */

/**
 * The main include file for Auth package
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Authentication
 * @package    Auth
 * @author     Martin Jansen <mj@php.net>
 * @author     Adam Ashley <aashley@php.net>
 * @copyright  2001-2006 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    CVS: $Id: Auth.php 289651 2009-10-15 04:39:07Z aashley $
 * @link       http://pear.php.net/package/Auth
 */

/**
 * Returned if session exceeds idle time
 */
define('AUTH_IDLED',                    -1);
/**
 * Returned if session has expired
 */
define('AUTH_EXPIRED',                  -2);
/**
 * Returned if container is unable to authenticate user/password pair
 */
define('AUTH_WRONG_LOGIN',              -3);
/**
 * Returned if a container method is not supported.
 */
define('AUTH_METHOD_NOT_SUPPORTED',     -4);
/**
 * Returned if new Advanced security system detects a breach
 */
define('AUTH_SECURITY_BREACH',          -5);
/**
 * Returned if checkAuthCallback says session should not continue.
 */
define('AUTH_CALLBACK_ABORT',           -6);

/**
 * Auth Log level - INFO
 */
define('AUTH_LOG_INFO',     6);
/**
 * Auth Log level - DEBUG
 */
define('AUTH_LOG_DEBUG',    7);

/**
 * Auth Advanced Security - IP Checks
 */
define('AUTH_ADV_IPCHECK', 1);
/**
 * Auth Advanced Security - User Agent Checks
 */
define('AUTH_ADV_USERAGENT', 2);
/**
 * Auth Advanced Security - Challenge Response
 */
define('AUTH_ADV_CHALLENGE', 3);


/**
 * PEAR::Auth
 *
 * The PEAR::Auth class provides methods for creating an
 * authentication system using PHP.
 *
 * @category   Authentication
 * @package    Auth
 * @author     Martin Jansen <mj@php.net>
 * @author     Adam Ashley <aashley@php.net>
 * @copyright  2001-2006 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    Release: 1.6.2  File: $Revision: 289651 $
 * @link       http://pear.php.net/package/Auth
 */
class Auth {

    // {{{ properties

    /**
     * Auth lifetime in seconds
     *
     * If this variable is set to 0, auth never expires
     *
     * @var  integer
     * @see  setExpire(), checkAuth()
     */
    var $expire = 0;

    /**
     * Has the auth session expired?
     *
     * @var   bool
     * @see   checkAuth()
     */
    var $expired = false;

    /**
     * Maximum idletime in seconds
     *
     * The difference to $expire is, that the idletime gets
     * refreshed each time checkAuth() is called. If this
     * variable is set to 0, idletime is never checked.
     *
     * @var integer
     * @see setIdle(), checkAuth()
     */
    var $idle = 0;

    /**
     * Is the maximum idletime over?
     *
     * @var boolean
     * @see checkAuth()
     */
    var $idled = false;

    /**
     * Storage object
     *
     * @var object
     * @see Auth(), validateLogin()
     */
    var $storage = '';

    /**
     * User-defined function that creates the login screen
     *
     * @var string
     */
    var $loginFunction = '';

    /**
     * Should the login form be displayed
     *
     * @var   bool
     * @see   setShowlogin()
     */
    var $showLogin = true;

    /**
      * Is Login Allowed from this page
      *
      * @var  bool
      * @see setAllowLogin
      */
    var $allowLogin = true;

    /**
     * Current authentication status
     *
     * @var string
     */
    var $status = '';

    /**
     * Username
     *
     * @var string
     */
    var $username = '';

    /**
     * Password
     *
     * @var string
     */
    var $password = '';

    /**
     * checkAuth callback function name
     *
     * @var string
     * @see setCheckAuthCallback()
     */
    var $checkAuthCallback = '';

    /**
     * Login callback function name
     *
     * @var string
     * @see setLoginCallback()
     */
    var $loginCallback = '';

    /**
     * Failed Login callback function name
     *
     * @var string
     * @see setFailedLoginCallback()
     */
    var $loginFailedCallback = '';

    /**
     * Logout callback function name
     *
     * @var string
     * @see setLogoutCallback()
     */
    var $logoutCallback = '';

    /**
     * Auth session-array name
     *
     * @var string
     */
    var $_sessionName = '_authsession';

    /**
     * Package Version
     *
     * @var string
     */
    var $version = "@version@";

    /**
     * Flag to use advanced security
     * When set extra checks will be made to see if the
     * user's IP or useragent have changed across requests.
     * Turned off by default to preserve BC.
     *
     * @var mixed Boolean to turn all advanced security options on or off
     *            Array containing named values turning specific advanced
     *            security features on or off individually
     *              array(
     *                  AUTH_ADV_IPCHECK    => true,
     *                  AUTH_ADV_USERAGENT  => true,
     *                  AUTH_ADV_CHALLENGE  => true,
     *              );
     */
    var $advancedsecurity = false;

    /**
     * Username key in POST array
     *
     * @var string
     */
    var $_postUsername = 'username';

    /**
     * Password key in POST array
     *
     * @var string
     */
    var $_postPassword = 'password';

    /**
     * Holds a reference to the session auth variable
     * @var array
     */
    var $session;

    /**
     * Holds a reference to the global server variable
     * @var array
     */
    var $server;

    /**
     * Holds a reference to the global post variable
     * @var array
     */
    var $post;

    /**
     * Holds a reference to the global cookie variable
     * @var array
     */
    var $cookie;

    /**
     * A hash to hold various superglobals as reference
     * @var array
     */
    var $authdata;

    /**
      * How many times has checkAuth been called
      * @var int
      */
    var $authChecks = 0;

    /**
     * PEAR::Log object
     *
     * @var object Log
     */
    var $logger = null;

    /**
     * Whether to enable logging of behaviour
     *
     * @var boolean
     */
    var $enableLogging = false;

    /**
     * Whether to regenerate session id everytime start is called
     *
     * @var boolean
     */
    var $regenerateSessionId = false;

    // }}}
    // {{{ Auth() [constructor]

    /**
     * Constructor
     *
     * Set up the storage driver.
     *
     * @param string    Type of the storage driver
     * @param mixed     Additional options for the storage driver
     *                  (example: if you are using DB as the storage
     *                   driver, you have to pass the dsn string here)
     *
     * @param string    Name of the function that creates the login form
     * @param boolean   Should the login form be displayed if necessary?
     * @return void
     */
    function Auth($storageDriver, $options = '', $loginFunction = '', $showLogin = true)
    {
        $this->applyAuthOptions($options);

        // Start the session suppress error if already started
        if(!session_id()){
            @session_start();
            if(!session_id()) {
                // Throw error
                include_once 'PEAR.php';
                PEAR::throwError('Session could not be started by Auth, '
                        .'possibly headers are already sent, try putting '
                        .'ob_start in the beginning of your script');
            }
        }

        // Make Sure Auth session variable is there
        if(!isset($_SESSION[$this->_sessionName])) {
            $_SESSION[$this->_sessionName] = array();
        }

        // Assign Some globals to internal references, this will replace _importGlobalVariable
        $this->session =& $_SESSION[$this->_sessionName];
        $this->server =& $_SERVER;
        $this->post =& $_POST;
        $this->cookie =& $_COOKIE;

        if ($loginFunction != '' && is_callable($loginFunction)) {
            $this->loginFunction = $loginFunction;
        }

        if (is_bool($showLogin)) {
            $this->showLogin = $showLogin;
        }

        if (is_object($storageDriver)) {
            $this->storage =& $storageDriver;
            // Pass a reference to auth to the container, ugly but works
            // this is used by the DB container to use method setAuthData not staticaly.
            $this->storage->_auth_obj =& $this;
        } else {
            // $this->storage = $this->_factory($storageDriver, $options);
            //
            $this->storage_driver = $storageDriver;
            $this->storage_options =& $options;
        }
    }

    // }}}
    // {{{ applyAuthOptions()

    /**
      * Set the Auth options
      *
      * Some options which are Auth specific will be applied
      * the rest will be left for usage by the container
      *
      * @param array    An array of Auth options
      * @return array   The options which were not applied
      * @access private
      */
    function &applyAuthOptions(&$options)
    {
        if(is_array($options)){
            if (!empty($options['sessionName'])) {
                $this->_sessionName = $options['sessionName'];
                unset($options['sessionName']);
            }
            if (isset($options['allowLogin'])) {
                $this->allowLogin = $options['allowLogin'];
                unset($options['allowLogin']);
            }
            if (!empty($options['postUsername'])) {
                $this->_postUsername = $options['postUsername'];
                unset($options['postUsername']);
            }
            if (!empty($options['postPassword'])) {
                $this->_postPassword = $options['postPassword'];
                unset($options['postPassword']);
            }
            if (isset($options['advancedsecurity'])) {
                $this->advancedsecurity = $options['advancedsecurity'];
                unset($options['advancedsecurity']);
            }
            if (isset($options['enableLogging'])) {
                $this->enableLogging = $options['enableLogging'];
                unset($options['enableLogging']);
            }
            if (isset($options['regenerateSessionId']) && is_bool($options['regenerateSessionId'])) {
                $this->regenerateSessionId = $options['regenerateSessionId'];
            }
        }
        return($options);
    }

    // }}}
    // {{{ _loadStorage()

    /**
      * Load Storage Driver if not already loaded
      *
      * Suspend storage instantiation to make Auth lighter to use
      * for calls which do not require login
      *
      * @return bool    True if the conainer is loaded, false if the container
      *                 is already loaded
      * @access private
      */
    function _loadStorage()
    {
        if(!is_object($this->storage)) {
            $this->storage =& $this->_factory($this->storage_driver,
                    $this->storage_options);
            $this->storage->_auth_obj =& $this;
            $this->log('Loaded storage container ('.$this->storage_driver.')', AUTH_LOG_DEBUG);
            return(true);
        }
        return(false);
    }

    // }}}
    // {{{ _factory()

    /**
     * Return a storage driver based on $driver and $options
     *
     * @static
     * @param  string $driver  Type of storage class to return
     * @param  string $options Optional parameters for the storage class
     * @return object Object   Storage object
     * @access private
     */
    function &_factory($driver, $options = '')
    {
        $storage_class = 'Auth_Container_' . $driver;
        include_once 'Auth/Container/' . $driver . '.php';
        $obj =& new $storage_class($options);
        return $obj;
    }

    // }}}
    // {{{ assignData()

    /**
     * Assign data from login form to internal values
     *
     * This function takes the values for username and password
     * from $HTTP_POST_VARS/$_POST and assigns them to internal variables.
     * If you wish to use another source apart from $HTTP_POST_VARS/$_POST,
     * you have to derive this function.
     *
     * @global $HTTP_POST_VARS, $_POST
     * @see    Auth
     * @return void
     * @access private
     */
    function assignData()
    {
        $this->log('Auth::assignData() called.', AUTH_LOG_DEBUG);

        if (   isset($this->post[$this->_postUsername])
            && $this->post[$this->_postUsername] != '') {
            $this->username = (get_magic_quotes_gpc() == 1
                    ? stripslashes($this->post[$this->_postUsername])
                    : $this->post[$this->_postUsername]);
        }
        if (   isset($this->post[$this->_postPassword])
            && $this->post[$this->_postPassword] != '') {
            $this->password = (get_magic_quotes_gpc() == 1
                    ? stripslashes($this->post[$this->_postPassword])
                    : $this->post[$this->_postPassword] );
        }
    }

    // }}}
    // {{{ start()

    /**
     * Start new auth session
     *
     * @return void
     * @access public
     */
    function start()
    {
        $this->log('Auth::start() called.', AUTH_LOG_DEBUG);

        // #10729 - Regenerate session id here if we are generating it on every
        //          page load.
        if ($this->regenerateSessionId) {
            session_regenerate_id(true);
        }

        $this->assignData();
        if (!$this->checkAuth() && $this->allowLogin) {
            $this->login();
        }
    }

    // }}}
    // {{{ login()

    /**
     * Login function
     *
     * @return void
     * @access private
     */
    function login()
    {
        $this->log('Auth::login() called.', AUTH_LOG_DEBUG);

        $login_ok = false;
        $this->_loadStorage();

        // Check if using challenge response
        (isset($this->post['authsecret']) && $this->post['authsecret'] == 1)
            ? $usingChap = true
            : $usingChap = false;


        // When the user has already entered a username, we have to validate it.
        if (!empty($this->username)) {
            if (true === $this->storage->fetchData($this->username, $this->password, $usingChap)) {
                $this->session['challengekey'] = md5($this->username.$this->password);
                $login_ok = true;
                $this->log('Successful login.', AUTH_LOG_INFO);
            }
        }

        if (!empty($this->username) && $login_ok) {
            $this->setAuth($this->username);
            if (is_callable($this->loginCallback)) {
                $this->log('Calling loginCallback ('.$this->loginCallback.').', AUTH_LOG_DEBUG);
                call_user_func_array($this->loginCallback, array($this->username, &$this));
            }
        }

        // If the login failed or the user entered no username,
        // output the login screen again.
        if (!empty($this->username) && !$login_ok) {
            $this->log('Incorrect login.', AUTH_LOG_INFO);
            $this->status = AUTH_WRONG_LOGIN;
            if (is_callable($this->loginFailedCallback)) {
                $this->log('Calling loginFailedCallback ('.$this->loginFailedCallback.').', AUTH_LOG_DEBUG);
                call_user_func_array($this->loginFailedCallback, array($this->username, &$this));
            }
        }

        if ((empty($this->username) || !$login_ok) && $this->showLogin) {
            $this->log('Rendering Login Form.', AUTH_LOG_INFO);
            if (is_callable($this->loginFunction)) {
                $this->log('Calling loginFunction ('.$this->loginFunction.').', AUTH_LOG_DEBUG);
                call_user_func_array($this->loginFunction, array($this->username, $this->status, &$this));
            } else {
                // BC fix Auth used to use drawLogin for this
                // call is sub classes implement this
                if (is_callable(array($this, 'drawLogin'))) {
                    $this->log('Calling Auth::drawLogin()', AUTH_LOG_DEBUG);
                    return $this->drawLogin($this->username, $this);
                }

                $this->log('Using default Auth_Frontend_Html', AUTH_LOG_DEBUG);

                // New Login form
                include_once 'Auth/Frontend/Html.php';
                return Auth_Frontend_Html::render($this, $this->username);
            }
        } else {
            return;
        }
    }

    // }}}
    // {{{ setExpire()

    /**
     * Set the maximum expire time
     *
     * @param  integer time in seconds
     * @param  bool    add time to current expire time or not
     * @return void
     * @access public
     */
    function setExpire($time, $add = false)
    {
        $add ? $this->expire += $time : $this->expire = $time;
    }

    // }}}
    // {{{ setIdle()

    /**
     * Set the maximum idle time
     *
     * @param  integer time in seconds
     * @param  bool    add time to current maximum idle time or not
     * @return void
     * @access public
     */
    function setIdle($time, $add = false)
    {
        $add ? $this->idle += $time : $this->idle = $time;
    }

    // }}}
    // {{{ setSessionName()

    /**
     * Set name of the session to a customized value.
     *
     * If you are using multiple instances of PEAR::Auth
     * on the same domain, you can change the name of
     * session per application via this function.
     * This will chnage the name of the session variable
     * auth uses to store it's data in the session
     *
     * @param  string New name for the session
     * @return void
     * @access public
     */
    function setSessionName($name = 'session')
    {
        $this->_sessionName = '_auth_'.$name;
        // Make Sure Auth session variable is there
        if(!isset($_SESSION[$this->_sessionName])) {
            $_SESSION[$this->_sessionName] = array();
        }
        $this->session =& $_SESSION[$this->_sessionName];
    }

    // }}}
    // {{{ setShowLogin()

    /**
     * Should the login form be displayed if necessary?
     *
     * @param  bool    show login form or not
     * @return void
     * @access public
     */
    function setShowLogin($showLogin = true)
    {
        $this->showLogin = $showLogin;
    }

    // }}}
    // {{{ setAllowLogin()

    /**
     * Is Login Allowed from this page?
     *
     * @param  bool    allow login from this page or not
     * @return void
     * @access public
     */
    function setAllowLogin($allowLogin = true)
    {
        $this->allowLogin = $allowLogin;
    }

    // }}}
    // {{{ setCheckAuthCallback()

    /**
     * Register a callback function to be called whenever the validity of the login is checked
     * The function will receive two parameters, the username and a reference to the auth object.
     *
     * @param  string  callback function name
     * @return void
     * @access public
     * @since Method available since Release 1.4.3
     */
    function setCheckAuthCallback($checkAuthCallback)
    {
        $this->checkAuthCallback = $checkAuthCallback;
    }

    // }}}
    // {{{ setLoginCallback()

    /**
     * Register a callback function to be called on user login.
     * The function will receive two parameters, the username and a reference to the auth object.
     *
     * @param  string  callback function name
     * @return void
     * @see    setLogoutCallback()
     * @access public
     */
    function setLoginCallback($loginCallback)
    {
        $this->loginCallback = $loginCallback;
    }

    // }}}
    // {{{ setFailedLoginCallback()

    /**
     * Register a callback function to be called on failed user login.
     * The function will receive two parameters, the username and a reference to the auth object.
     *
     * @param  string  callback function name
     * @return void
     * @access public
     */
    function setFailedLoginCallback($loginFailedCallback)
    {
        $this->loginFailedCallback = $loginFailedCallback;
    }

    // }}}
    // {{{ setLogoutCallback()

    /**
     * Register a callback function to be called on user logout.
     * The function will receive three parameters, the username and a reference to the auth object.
     *
     * @param  string  callback function name
     * @return void
     * @see    setLoginCallback()
     * @access public
     */
    function setLogoutCallback($logoutCallback)
    {
        $this->logoutCallback = $logoutCallback;
    }

    // }}}
    // {{{ setAuthData()

    /**
     * Register additional information that is to be stored
     * in the session.
     *
     * @param  string  Name of the data field
     * @param  mixed   Value of the data field
     * @param  boolean Should existing data be overwritten? (default
     *                 is true)
     * @return void
     * @access public
     */
    function setAuthData($name, $value, $overwrite = true)
    {
        if (!empty($this->session['data'][$name]) && $overwrite == false) {
            return;
        }
        $this->session['data'][$name] = $value;
    }

    // }}}
    // {{{ getAuthData()

    /**
     * Get additional information that is stored in the session.
     *
     * If no value for the first parameter is passed, the method will
     * return all data that is currently stored.
     *
     * @param  string Name of the data field
     * @return mixed  Value of the data field.
     * @access public
     */
    function getAuthData($name = null)
    {
        if (!isset($this->session['data'])) {
            return null;
        }
        if(!isset($name)) {
            return $this->session['data'];
        }
        if (isset($name) && isset($this->session['data'][$name])) {
            return $this->session['data'][$name];
        }
        return null;
    }

    // }}}
    // {{{ setAuth()

    /**
     * Register variable in a session telling that the user
     * has logged in successfully
     *
     * @param  string Username
     * @return void
     * @access public
     */
    function setAuth($username)
    {
        $this->log('Auth::setAuth() called.', AUTH_LOG_DEBUG);

        // #10729 - Regenerate session id here only if generating at login only
        //          Don't do it if we are regenerating on every request so we don't
        //          regenerate it twice in one request.
        if (!$this->regenerateSessionId) {
            // #2021 - Change the session id to avoid session fixation attacks php 4.3.3 >
            session_regenerate_id(true);
        }

        if (!isset($this->session) || !is_array($this->session)) {
            $this->session = array();
        }

        if (!isset($this->session['data'])) {
            $this->session['data'] = array();
        }

        $this->session['sessionip'] = isset($this->server['REMOTE_ADDR'])
            ? $this->server['REMOTE_ADDR']
            : '';
        $this->session['sessionuseragent'] = isset($this->server['HTTP_USER_AGENT'])
            ? $this->server['HTTP_USER_AGENT']
            : '';
        $this->session['sessionforwardedfor'] = isset($this->server['HTTP_X_FORWARDED_FOR'])
            ? $this->server['HTTP_X_FORWARDED_FOR']
            : '';

        // This should be set by the container to something more safe
        // Like md5(passwd.microtime)
        if(empty($this->session['challengekey'])) {
            $this->session['challengekey'] = md5($username.microtime());
        }

        $this->session['challengecookie'] = md5($this->session['challengekey'].microtime());
        setcookie('authchallenge', $this->session['challengecookie'], 0, '/');

        $this->session['registered'] = true;
        $this->session['username']   = $username;
        $this->session['timestamp']  = time();
        $this->session['idle']       = time();
    }

    // }}}
    // {{{ setAdvancedSecurity()

    /**
      * Enables advanced security checks
      *
      * Currently only ip change and useragent change
      * are detected
      * @todo Add challenge cookies - Create a cookie which changes every time
      *       and contains some challenge key which the server can verify with
      *       a session var cookie might need to be crypted (user pass)
      * @param bool Enable or disable
      * @return void
      * @access public
      */
    function setAdvancedSecurity($flag=true)
    {
        $this->advancedsecurity = $flag;
    }

    // }}}
    // {{{ checkAuth()

    /**
     * Checks if there is a session with valid auth information.
     *
     * @access public
     * @return boolean  Whether or not the user is authenticated.
     */
    function checkAuth()
    {
        $this->log('Auth::checkAuth() called.', AUTH_LOG_DEBUG);
        $this->authChecks++;
        if (isset($this->session)) {
            // Check if authentication session is expired
            if (   $this->expire > 0
                && isset($this->session['timestamp'])
                && ($this->session['timestamp'] + $this->expire) < time()) {
                $this->log('Session Expired', AUTH_LOG_INFO);
                $this->expired = true;
                $this->status = AUTH_EXPIRED;
                $this->logout();
                return false;
            }

            // Check if maximum idle time is reached
            if (   $this->idle > 0
                && isset($this->session['idle'])
                && ($this->session['idle'] + $this->idle) < time()) {
                $this->log('Session Idle Time Reached', AUTH_LOG_INFO);
                $this->idled = true;
                $this->status = AUTH_IDLED;
                $this->logout();
                return false;
            }

            if (   isset($this->session['registered'])
                && isset($this->session['username'])
                && $this->session['registered'] == true
                && $this->session['username'] != '') {
                Auth::updateIdle();

                if ($this->_isAdvancedSecurityEnabled()) {
                    $this->log('Advanced Security Mode Enabled.', AUTH_LOG_DEBUG);

                    // Only Generate the challenge once
                    if (   $this->authChecks == 1
                        && $this->_isAdvancedSecurityEnabled(AUTH_ADV_CHALLENGE)) {
                        $this->log('Generating new Challenge Cookie.', AUTH_LOG_DEBUG);
                        $this->session['challengecookieold'] = $this->session['challengecookie'];
                        $this->session['challengecookie'] = md5($this->session['challengekey'].microtime());
                        setcookie('authchallenge', $this->session['challengecookie'], 0, '/');
                    }

                    // Check for ip change
                    if (   $this->_isAdvancedSecurityEnabled(AUTH_ADV_IPCHECK)
                        && isset($this->server['REMOTE_ADDR'])
                        && $this->session['sessionip'] != $this->server['REMOTE_ADDR']) {
                        $this->log('Security Breach. Remote IP Address changed.', AUTH_LOG_INFO);
                        // Check if the IP of the user has changed, if so we
                        // assume a man in the middle attack and log him out
                        $this->expired = true;
                        $this->status = AUTH_SECURITY_BREACH;
                        $this->logout();
                        return false;
                    }

                    // Check for ip change (if connected via proxy)
                    if (   $this->_isAdvancedSecurityEnabled(AUTH_ADV_IPCHECK)
                        && isset($this->server['HTTP_X_FORWARDED_FOR'])
                        && $this->session['sessionforwardedfor'] != $this->server['HTTP_X_FORWARDED_FOR']) {
                        $this->log('Security Breach. Forwarded For IP Address changed.', AUTH_LOG_INFO);
                        // Check if the IP of the user connecting via proxy has
                        // changed, if so we assume a man in the middle attack
                        // and log him out.
                        $this->expired = true;
                        $this->status = AUTH_SECURITY_BREACH;
                        $this->logout();
                        return false;
                    }

                    // Check for useragent change
                    if (   $this->_isAdvancedSecurityEnabled(AUTH_ADV_USERAGENT)
                        && isset($this->server['HTTP_USER_AGENT'])
                        && $this->session['sessionuseragent'] != $this->server['HTTP_USER_AGENT']) {
                        $this->log('Security Breach. User Agent changed.', AUTH_LOG_INFO);
                        // Check if the User-Agent of the user has changed, if
                        // so we assume a man in the middle attack and log him out
                        $this->expired = true;
                        $this->status = AUTH_SECURITY_BREACH;
                        $this->logout();
                        return false;
                    }

                    // Check challenge cookie here, if challengecookieold is not set
                    // this is the first time and check is skipped
                    // TODO when user open two pages similtaneuly (open in new window,open
                    // in tab) auth breach is caused find out a way around that if possible
                    if (   $this->_isAdvancedSecurityEnabled(AUTH_ADV_CHALLENGE)
                        && isset($this->session['challengecookieold'])
                        && $this->session['challengecookieold'] != $this->cookie['authchallenge']) {
                        $this->log('Security Breach. Challenge Cookie mismatch.', AUTH_LOG_INFO);
                        $this->expired = true;
                        $this->status = AUTH_SECURITY_BREACH;
                        $this->logout();
                        $this->login();
                        return false;
                    }
                }

                if (is_callable($this->checkAuthCallback)) {
                    $this->log('Calling checkAuthCallback ('.$this->checkAuthCallback.').', AUTH_LOG_DEBUG);
                    $checkCallback = call_user_func_array($this->checkAuthCallback, array($this->username, &$this));
                    if ($checkCallback == false) {
                        $this->log('checkAuthCallback failed.', AUTH_LOG_INFO);
                        $this->expired = true;
                        $this->status = AUTH_CALLBACK_ABORT;
                        $this->logout();
                        return false;
                    }
                }

                $this->log('Session OK.', AUTH_LOG_INFO);
                return true;
            }
        } else {
            $this->log('Unable to locate session storage.', AUTH_LOG_DEBUG);
            return false;
        }
        $this->log('No login session.', AUTH_LOG_DEBUG);
        return false;
    }

    // }}}
    // {{{ staticCheckAuth() [static]

    /**
     * Statically checks if there is a session with valid auth information.
     *
     * @access public
     * @see checkAuth
     * @return boolean  Whether or not the user is authenticated.
     * @static
     */
    function staticCheckAuth($options = null)
    {
        static $staticAuth;
        if(!isset($staticAuth)) {
            $staticAuth = new Auth('null', $options);
        }
        $staticAuth->log('Auth::staticCheckAuth() called', AUTH_LOG_DEBUG);
        return $staticAuth->checkAuth();
    }

    // }}}
    // {{{ getAuth()

    /**
     * Has the user been authenticated?
     *
     * Is there a valid login session. Previously this was different from
     * checkAuth() but now it is just an alias.
     *
     * @access public
     * @return bool  True if the user is logged in, otherwise false.
     */
    function getAuth()
    {
        $this->log('Auth::getAuth() called.', AUTH_LOG_DEBUG);
        return $this->checkAuth();
    }

    // }}}
    // {{{ logout()

    /**
     * Logout function
     *
     * This function clears any auth tokens in the currently
     * active session and executes the logout callback function,
     * if any
     *
     * @access public
     * @return void
     */
    function logout()
    {
        $this->log('Auth::logout() called.', AUTH_LOG_DEBUG);

        if (is_callable($this->logoutCallback) && isset($this->session['username'])) {
            $this->log('Calling logoutCallback ('.$this->logoutCallback.').', AUTH_LOG_DEBUG);
            call_user_func_array($this->logoutCallback, array($this->session['username'], &$this));
        }

        $this->username = '';
        $this->password = '';

        $this->session = null;
    }

    // }}}
    // {{{ updateIdle()

    /**
     * Update the idletime
     *
     * @access private
     * @return void
     */
    function updateIdle()
    {
        $this->session['idle'] = time();
    }

    // }}}
    // {{{ getUsername()

    /**
     * Get the username
     *
     * @return string
     * @access public
     */
    function getUsername()
    {
        if (isset($this->session['username'])) {
            return($this->session['username']);
        }
        return('');
    }

    // }}}
    // {{{ getStatus()

    /**
     * Get the current status
     *
     * @return string
     * @access public
     */
    function getStatus()
    {
        return $this->status;
    }

    // }}}
    // {{{ getPostUsernameField()

    /**
     * Gets the post varible used for the username
     *
     * @return string
     * @access public
     */
    function getPostUsernameField()
    {
        return($this->_postUsername);
    }

    // }}}
    // {{{ getPostPasswordField()

    /**
     * Gets the post varible used for the username
     *
     * @return string
     * @access public
     */
    function getPostPasswordField()
    {
        return($this->_postPassword);
    }

    // }}}
    // {{{ sessionValidThru()

    /**
     * Returns the time up to the session is valid
     *
     * @access public
     * @return integer
     */
    function sessionValidThru()
    {
        if (!isset($this->session['idle'])) {
            return 0;
        }
        if ($this->idle == 0) {
            return 0;
        }
        return ($this->session['idle'] + $this->idle);
    }

    // }}}
    // {{{ listUsers()

    /**
     * List all users that are currently available in the storage
     * container
     *
     * @access public
     * @return array
     */
    function listUsers()
    {
        $this->log('Auth::listUsers() called.', AUTH_LOG_DEBUG);
        $this->_loadStorage();
        return $this->storage->listUsers();
    }

    // }}}
    // {{{ addUser()

    /**
     * Add user to the storage container
     *
     * @access public
     * @param  string Username
     * @param  string Password
     * @param  mixed  Additional parameters
     * @return mixed  True on success, PEAR error object on error
     *                and AUTH_METHOD_NOT_SUPPORTED otherwise.
     */
    function addUser($username, $password, $additional = '')
    {
        $this->log('Auth::addUser() called.', AUTH_LOG_DEBUG);
        $this->_loadStorage();
        return $this->storage->addUser($username, $password, $additional);
    }

    // }}}
    // {{{ removeUser()

    /**
     * Remove user from the storage container
     *
     * @access public
     * @param  string Username
     * @return mixed  True on success, PEAR error object on error
     *                and AUTH_METHOD_NOT_SUPPORTED otherwise.
     */
    function removeUser($username)
    {
        $this->log('Auth::removeUser() called.', AUTH_LOG_DEBUG);
        $this->_loadStorage();
        return $this->storage->removeUser($username);
    }

    // }}}
    // {{{ changePassword()

    /**
     * Change password for user in the storage container
     *
     * @access public
     * @param string Username
     * @param string The new password
     * @return mixed True on success, PEAR error object on error
     *               and AUTH_METHOD_NOT_SUPPORTED otherwise.
     */
    function changePassword($username, $password)
    {
        $this->log('Auth::changePassword() called', AUTH_LOG_DEBUG);
        $this->_loadStorage();
        return $this->storage->changePassword($username, $password);
    }

    // }}}
    // {{{ log()

    /**
     * Log a message from the Auth system
     *
     * @access public
     * @param string The message to log
     * @param string The log level to log the message under. See the Log documentation for more info.
     * @return boolean
     */
    function log($message, $level = AUTH_LOG_DEBUG)
    {
        if (!$this->enableLogging) return false;

        $this->_loadLogger();

        $this->logger->log('AUTH: '.$message, $level);
    }

    // }}}
    // {{{ _loadLogger()

    /**
      * Load Log object if not already loaded
      *
      * Suspend logger instantiation to make Auth lighter to use
      * for calls which do not require logging
      *
      * @return bool    True if the logger is loaded, false if the logger
      *                 is already loaded
      * @access private
      */
    function _loadLogger()
    {
        if(is_null($this->logger)) {
            if (!class_exists('Log')) {
                include_once 'Log.php';
            }
            $this->logger =& Log::singleton('null',
                    null,
                    'auth['.getmypid().']',
                    array(),
                    AUTH_LOG_DEBUG);
            return(true);
        }
        return(false);
    }

    // }}}
    // {{{ attachLogObserver()

    /**
     * Attach an Observer to the Auth Log Source
     *
     * @param object Log_Observer A Log Observer instance
     * @return boolean
     */
    function attachLogObserver(&$observer) {

        $this->_loadLogger();

        return $this->logger->attach($observer);

    }

    // }}}
    // {{{ _isAdvancedSecurityEnabled()

    /**
     * Is advanced security enabled?
     *
     * Pass one of the Advanced Security constants as the first parameter
     * to check if that advanced security check is enabled.
     *
     * @param integer
     * @return boolean
     */
    function _isAdvancedSecurityEnabled($feature = null) {

        if (is_null($feature)) {

            if ($this->advancedsecurity === true)
                return true;

            if (   is_array($this->advancedsecurity)
                && in_array(true, $this->advancedsecurity, true))
                return true;

            return false;

        } else {

            if (is_array($this->advancedsecurity)) {

                if (   isset($this->advancedsecurity[$feature])
                    && $this->advancedsecurity[$feature] == true)
                    return true;

                return false;

            }

            return (bool)$this->advancedsecurity;

        }

    }

    // }}}

}
?>