]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
Started with Group_Ldap (not yet ready)
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.10 2004-02-01 09:14:11 rurban Exp $');
3
4 // This is a complete OOP rewrite of the old WikiUser code with various
5 // configurable external authentification methods.
6 //
7 // There's only one entry point, the function WikiUser which returns 
8 // a WikiUser object, which contains the user's preferences.
9 // This object might get upgraded during the login step and later also.
10 // There exist three preferences storage methods: cookie, homepage and db,
11 // and multiple password checking methods.
12 // See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if 
13 // ALLOW_USER_PASSWORDS is defined.
14 //
15 // Each user object must define the two preferences methods 
16 //  getPreferences(), setPreferences(), 
17 // and the following 1-3 auth methods: 
18 //  checkPass()  must be defined by all classes,
19 //  userExists() only if USER_AUTH_POLICY'=='strict' 
20 //  mayChangePass()  only if the password is storable.
21 //  storePass()  only if the password is storable.
22 //
23 // WikiUser() given no name, returns an _AnonUser (anonymous user)
24 // object, who may or may not have a cookie. Given a user name,
25 // returns a _BogoUser object, who may or may not have a cookie and/or
26 // PersonalPage, a _PassUser object or an _AdminUser object.
27 //
28 // Takes care of passwords, all preference loading/storing in the
29 // user's page and any cookies. main.php will query the user object to
30 // verify the password as appropriate.
31 //
32 // Notes by 2004-01-25 03:43:45 rurban
33 // Currently this library doesn't look good enough with 
34 // the current configuration options.
35 // Test it by defining ENABLE_USER_NEW in index.php
36 // The problem is that the previous code was written to do auth checks 
37 // only on action != browse, and this code requires a good enough 
38 // user object even for browse. I don't think that this is a good idea.
39 // 1) Now a ForbideenUser is returned instead of false.
40 // 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, 
41 // but may browse. Now with ALLOW_ANON_USER = false he may not browse, 
42 // which is needed to disable browse PagePermissions. Hmm...
43 // I added now ALLOW_ANON_EDIT = true to makes things clear. 
44 // (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
45
46 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
47 define('WIKIAUTH_ANON', 0);       // Not signed in.
48 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
49 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
50 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
51
52 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
53 if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
54
55 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
56 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
57 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
58
59 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
60 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
61 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
62
63 define('TIMEOFFSET_MIN_HOURS', -26);
64 define('TIMEOFFSET_MAX_HOURS',  26);
65 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
66
67 /**
68  * There are be the following constants in index.php to 
69  * establish login parameters:
70  *
71  * ALLOW_ANON_USER         default true
72  * ALLOW_ANON_EDIT         default true
73  * ALLOW_BOGO_LOGIN        default true
74  * ALLOW_USER_PASSWORDS    default true
75  * PASSWORD_LENGTH_MINIMUM default 6?
76  *
77  * To require user passwords for editing:
78  * ALLOW_ANON_USER  = true
79  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
80  * ALLOW_BOGO_LOGIN = false
81  * ALLOW_USER_PASSWORDS = true
82  *
83  * To establish a COMPLETELY private wiki, such as an internal
84  * corporate one:
85  * ALLOW_ANON_USER = false
86  * (and probably require user passwords as described above). In this
87  * case the user will be prompted to login immediately upon accessing
88  * any page.
89  *
90  * There are other possible combinations, but the typical wiki (such
91  * as PhpWiki.sf.net) would usually just leave all four enabled.
92  *
93  */
94
95 // The last object in the row is the bad guy...
96 if (!is_array($USER_AUTH_ORDER))
97     $USER_AUTH_ORDER = array("Forbidden");
98 else
99     $USER_AUTH_ORDER[] = "Forbidden";
100
101 // Local convenience functions.
102 function _isAnonUserAllowed() {
103     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
104 }
105 function _isBogoUserAllowed() {
106     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
107 }
108 function _isUserPasswordsAllowed() {
109     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
110 }
111
112
113 // Possibly upgrade userobject functions.
114 function _determineAdminUserOrOtherUser($UserName) {
115     // Sanity check. User name is a condition of the definition of the
116     // _AdminUser, _BogoUser and _passuser.
117     if (!$UserName)
118         return $GLOBALS['ForbiddenUser'];
119
120     if ($UserName == ADMIN_USER)
121         return new _AdminUser($UserName);
122     else
123         return _determineBogoUserOrPassUser($UserName);
124 }
125
126 function _determineBogoUserOrPassUser($UserName) {
127     global $ForbiddenUser;
128
129     // Sanity check. User name is a condition of the definition of
130     // _BogoUser and _PassUser.
131     if (!$UserName)
132         return $ForbiddenUser;
133
134     // Check for password and possibly upgrade user object.
135     $_BogoUser = new _BogoUser($UserName);
136     if (_isUserPasswordsAllowed()) {
137         if (/*$has_password =*/ $_BogoUser->_prefs->get('passwd'))
138             return new _PassUser($UserName);
139         else { // PassUsers override BogoUsers if they exist
140             $_PassUser = new _PassUser($UserName);
141             if ($_PassUser->userExists())
142                 return $_PassUser;
143         }
144     }
145     // User has no password.
146     if (_isBogoUserAllowed())
147         return $_BogoUser;
148
149     // Passwords are not allowed, and Bogo is disallowed too. (Only
150     // the admin can sign in).
151     return $ForbiddenUser;
152 }
153
154 /**
155  * Primary WikiUser function, called by main.php.
156  * 
157  * This determines the user's type and returns an appropriate user
158  * object. main.php then querys the resultant object for password
159  * validity as necessary.
160  *
161  * If an _AnonUser object is returned, the user may only browse pages
162  * (and save prefs in a cookie).
163  *
164  * To disable access but provide prefs the global $ForbiddenUser class 
165  * is returned. (was previously false)
166  * 
167  */
168 function WikiUser ($UserName = '') {
169     global $ForbiddenUser;
170
171     //TODO: Check sessionvar for username & save username into
172     //sessionvar (may be more appropriate to do this in main.php).
173     if ($UserName) {
174         $ForbiddenUser = new _ForbiddenUser($UserName);
175         // Found a user name.
176         return _determineAdminUserOrOtherUser($UserName);
177     }
178     elseif (!empty($_SESSION['userid'])) {
179         // Found a user name.
180         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
181         return _determineAdminUserOrOtherUser($_SESSION['userid']);
182     }
183     else {
184         // Check for autologin pref in cookie and possibly upgrade
185         // user object to another type.
186         $_AnonUser = new _AnonUser();
187         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
188             // Found a user name.
189             $ForbiddenUser = new _ForbiddenUser($UserName);
190             return _determineAdminUserOrOtherUser($UserName);
191         }
192         else {
193             $ForbiddenUser = new _ForbiddenUser();
194             if (_isAnonUserAllowed())
195                 return $_AnonUser;
196             return $ForbiddenUser; // User must sign in to browse pages.
197         }
198         return $ForbiddenUser;     // User must sign in with a password.
199     }
200     /*
201     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
202                   . "Unexpectedly, an appropriate user class could not be determined.");
203     return $ForbiddenUser; // Failsafe.
204     */
205 }
206
207 function WikiUserClassname() {
208     return '_WikiUser';
209 }
210
211 function UpgradeUser ($olduser, $user) {
212     if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
213         // populate the upgraded class with the values from the old object
214         foreach (get_object_vars($user) as $k => $v) {
215             if (!empty($v)) $olduser->$k = $v;  
216         }
217         $GLOBALS['request']->_user = $olduser;
218         return $olduser;
219     } else {
220         return false;
221     }
222 }
223
224 function UserExists ($UserName) {
225     global $request;
226     if (!($user = $request->getUser()))
227         $user = WikiUser($UserName);
228     if (!$user) 
229         return false;
230     if ($user->userExists($UserName)) {
231         $request->_user = $user;
232         return true;
233     }
234     elseif ($user = $user->nextClass())
235         return $user->userExists($UserName);
236     $request->_user = $GLOBALS['ForbiddenUser'];
237     return false;
238 }
239
240 function CheckPass ($UserName, $Password) {
241     global $request;
242     if (!($user = $request->getUser()))
243         $user = WikiUser($UserName);
244     if (!$user) 
245         return false;
246     if ($user->checkPass($Password)) {
247         $request->_user = $user;
248         return true;
249     }
250     elseif ($user = $user->nextClass())
251         return $user->userExists($Password);
252     $request->_user = $GLOBALS['ForbiddenUser'];
253     return false;
254 }
255
256
257 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
258
259 // Base WikiUser class.
260 class _WikiUser
261 {
262     var $_userid = '';
263
264     var $_level = WIKIAUTH_FORBIDDEN;
265     var $_prefs = false;
266     var $_HomePagehandle = false;
267
268     // constructor
269     function _WikiUser($UserName = '') {
270
271         $this->_userid = $UserName;
272         if ($UserName) {
273             $this->_HomePagehandle = $this->hasHomePage();
274         }
275         $this->getPreferences();
276     }
277
278     function UserName() {
279         if (!empty($this->_userid))
280             return $this->_userid;
281     }
282
283     function getPreferences() {
284         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
285                       . "New subclasses of _WikiUser must override this function.");
286         return false;
287     }
288
289     function setPreferences($prefs, $id_only) {
290         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
291                       . "New subclasses of _WikiUser must override this function.");
292         return false;
293     }
294
295     function userExists() {
296         return $this->hasHomePage();
297     }
298
299     function checkPass($submitted_password) {
300         // By definition, an undefined user class cannot sign in.
301         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
302                       . "New subclasses of _WikiUser must override this function.");
303         return false;
304     }
305
306     // returns page_handle to user's home page or false if none
307     function hasHomePage() {
308         if ($this->_userid) {
309             if ($this->_HomePagehandle) {
310                 return $this->_HomePagehandle;
311             }
312             else {
313                 // check db again (maybe someone else created it since
314                 // we logged in.)
315                 global $request;
316                 $this->_HomePagehandle = $request->getPage($this->_userid);
317                 return $this->_HomePagehandle;
318             }
319         }
320         // nope
321         return false;
322     }
323
324     function nextAuthMethod() {
325         if (! $this->_current_method) {
326             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
327             $this->_current_index = -1;
328         }
329         $this->_current_index++;
330         if ($this->_current_index >= count($this->_auth_methods))
331             return false;
332         $this->_current_method = $this->_auth_methods[$this->_current_index];
333         return $this->_current_method;
334     }
335
336     // upgrade the user object
337     function nextClass() {
338         if ($method = $this->nextAuthMethod()) {
339             $class = "_".$method."PassUser";
340             if ($user = new $class($this->_userid)) {
341                 // prevent from endless recursion.
342                 UpgradeUser($this, $user);
343             }
344             return $user;
345         }
346     }
347
348     function PrintLoginForm (&$request, $args, $fail_message = false,
349                              $seperate_page = true) {
350         include_once('lib/Template.php');
351         // Call update_locale in case the system's default language is not 'en'.
352         // (We have no user pref for lang at this point yet, no one is logged in.)
353         update_locale(DEFAULT_LANGUAGE);
354         $userid = $this->_userid;
355         $require_level = 0;
356         extract($args); // fixme
357
358         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
359
360         $pagename = $request->getArg('pagename');
361         $nocache = 1;
362         $login = new Template('login', $request,
363                               compact('pagename', 'userid', 'require_level',
364                                       'fail_message', 'pass_required', 'nocache'));
365         if ($seperate_page) {
366             $top = new Template('html', $request,
367                                 array('TITLE' => _("Sign In")));
368             return $top->printExpansion($login);
369         } else {
370             return $login;
371         }
372     }
373
374     // signed in but probably not password checked
375     function isSignedIn() {
376         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
377     }
378
379     function isAuthenticated () {
380         //return isa($this,'_PassUser');
381         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
382         return $this->_level >= WIKIAUTH_BOGO;
383     }
384
385     function isAdmin () {
386         return $this->_level == WIKIAUTH_ADMIN;
387     }
388
389     function getId () {
390         return ( $this->UserName()
391                  ? $this->UserName()
392                  : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
393     }
394
395     function getAuthenticatedId() {
396         return ( $this->isAuthenticated()
397                  ? $this->_userid
398                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
399     }
400
401     function hasAuthority ($require_level) {
402         return $this->_level >= $require_level;
403     }
404
405     function AuthCheck ($postargs) {
406         // Normalize args, and extract.
407         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
408                       'cancel');
409         foreach ($keys as $key)
410             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
411         extract($args);
412         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
413
414         if ($logout) { // Log out
415             $GLOBALS['request']->_user = new _AnonUser();
416             return $GLOBALS['request']->_user; 
417         } elseif ($cancel)
418             return false;        // User hit cancel button.
419         elseif (!$login && !$userid)
420             return false;       // Nothing to do?
421
422         $authlevel = $this->checkPass($passwd);
423         if (!$authlevel)
424             return _("Invalid password or userid.");
425         elseif ($authlevel < $require_level)
426             return _("Insufficient permissions.");
427
428         // Successful login.
429         $user = $GLOBALS['request']->_user;
430         $user->_userid = $userid;
431         $user->_level = $authlevel;
432         return $user;
433     }
434
435 }
436
437 class _AnonUser
438 extends _WikiUser
439 {
440     var $_level = WIKIAUTH_ANON;
441
442     // Anon only gets to load and save prefs in a cookie, that's it.
443     function getPreferences() {
444         global $request;
445
446         if (empty($this->_prefs))
447             $this->_prefs = new UserPreferences;
448         $UserName = $this->UserName();
449         if ($cookie = $request->getCookieVar(WIKI_NAME)) {
450             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
451                 trigger_error(_("Format of UserPreferences cookie not recognised.") . " "
452                               . _("Default preferences will be used."),
453                               E_USER_WARNING);
454             }
455             // TODO: try reading userid from old PhpWiki cookie
456             // formats, then delete old cookie from browser!
457             //
458             //else {
459                 // try old cookie format.
460                 //$cookie = $request->getCookieVar('WIKI_ID');
461             //}
462
463             /**
464              * Only keep the cookie if it matches the UserName who is
465              * signing in or if this really is an Anon login (no
466              * username). (Remember, _BogoUser and higher inherit this
467              * function too!).
468              */
469             if (! $UserName || $UserName == $unboxedcookie['userid']) {
470                 $this->_prefs = new UserPreferences($unboxedcookie);
471                 $this->_userid = $unboxedcookie['userid'];
472             }
473         }
474         // initializeTheme() needs at least an empty object
475         if (! $this->_prefs )
476             $this->_prefs = new UserPreferences;
477         return $this->_prefs;
478     }
479
480     function setPreferences($prefs, $id_only=false) {
481         // Allow for multiple wikis in same domain. Encode only the
482         // _prefs array of the UserPreference object. Ideally the
483         // prefs array should just be imploded into a single string or
484         // something so it is completely human readable by the end
485         // user. In that case stricter error checking will be needed
486         // when loading the cookie.
487         setcookie(WIKI_NAME, $this->_prefs->store(),
488                   COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
489     }
490
491     function userExists() {
492         return true;
493     }
494
495     function checkPass($submitted_password) {
496         // By definition, the _AnonUser does not HAVE a password
497         // (compared to _BogoUser, who has an EMPTY password).
498         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
499                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
500                       . "New subclasses of _WikiUser must override this function.");
501         return false;
502     }
503
504 }
505
506 class _ForbiddenUser
507 extends _AnonUser
508 {
509     var $_level = WIKIAUTH_FORBIDDEN;
510
511     function checkPass($submitted_password) {
512         return false;
513     }
514
515     function userExists() {
516         if ($this->_HomePagehandle) return true;
517         return false;
518     }
519 }
520 /**
521  * Do NOT extend _BogoUser to other classes, for checkPass()
522  * security. (In case of defects in code logic of the new class!)
523  */
524 class _BogoUser
525 extends _AnonUser
526 {
527     function userExists() {
528         if (isWikiWord($this->_userid)) {
529             $this->_level = WIKIAUTH_BOGO;
530             return true;
531         } else {
532             $this->_level = WIKIAUTH_ANON;
533             return false;
534         }
535     }
536
537     function checkPass($submitted_password) {
538         // By definition, BogoUser has an empty password.
539         $this->userExists();
540         return $this->_level;
541     }
542 }
543
544 class _PassUser
545 extends _AnonUser
546 /**
547  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
548  *
549  * The classes for all subsequent auth methods extend from
550  * this class. 
551  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
552  * the three auth method policies first-only, strict and stacked
553  * and the two methods for prefs: homepage or database, 
554  * if $DBAuthParams['pref_select'] is defined.
555  *
556  * Default is PersonalPage auth and prefs.
557  * 
558  */
559 {
560     var $_auth_dbi, $_prefmethod, $_prefselect, $_prefupdate;
561     var $_current_method, $_current_index;
562
563     // check and prepare the auth and pref methods only once
564     function _PassUser($UserName = '') {
565         global $DBAuthParams, $DBParams;
566
567         if ($UserName) {
568             $this->_userid = $UserName;
569             $this->_HomePagehandle = $this->hasHomePage();
570         }
571         // Check the configured Prefs methods
572         if (!empty($DBAuthParams['pref_select']) and $DBParams['dbtype'] == 'SQL') {
573             $this->_prefmethod = 'SQL'; // really pear db
574             $this->getAuthDbh();
575             // preparate the SELECT statement
576             $this->_prefselect = $this->_auth_dbi->prepare(
577                 str_replace('"$userid"','?',$DBAuthParams['pref_select'])
578             );
579         }
580         if (!empty($DBAuthParams['pref_select']) and $DBParams['dbtype'] == 'ADODB') {
581             $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
582             $this->getAuthDbh();
583             // preparate the SELECT statement
584             $this->_prefselect = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
585         }
586         if (!empty($DBAuthParams['pref_update']) and $DBParams['dbtype'] == 'SQL') {
587             $this->_prefmethod = 'SQL';
588             $this->getAuthDbh();
589             $this->_prefupdate = $this->_auth_dbi->prepare(
590                 str_replace(array('"$userid"','"$pref_blob"'),array('?','?'),$DBAuthParams['pref_update'])
591             );
592         }
593         if (!empty($DBAuthParams['pref_update']) and $DBParams['dbtype'] == 'ADODB') {
594             $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
595             $this->getAuthDbh();
596             // preparate the SELECT statement
597             $this->_prefupdate = str_replace(array('"$userid"','"$pref_blob"'),array('%s','%s'),$DBAuthParams['pref_update']);
598         }
599         $this->getPreferences();
600
601         // Upgrade to the next parent _PassUser class. Avoid recursion.
602         if ( get_class($this) === '_PassUser' ) {
603             //Auth policy: Check the order of the configured auth methods
604             // 1. first-only: Upgrade the class here in the constructor
605             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as in the previous PhpWiki releases (slow)
606             // 3. strict:    upgrade the class after checking the user existance in userExists()
607             // 4. stacked:   upgrade the class after the password verification in checkPass()
608             // Methods: PersonalPage, HTTP_AUTH, DB, LDAP, IMAP, File
609             if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
610             if (defined('USER_AUTH_POLICY')) {
611                 // policy 1: only pre-define one method for all users
612                 if (USER_AUTH_POLICY === 'first-only') {
613                     if ($user = $this->nextClass())
614                         return $user;
615                     else 
616                         return $GLOBALS['ForbiddenUser'];
617                 }
618                 // use the default behaviour from the previous versions:
619                 elseif (USER_AUTH_POLICY === 'old') {
620                     // default: try to be smart
621                     if (!empty($GLOBALS['PHP_AUTH_USER'])) {
622                         return new _HttpAuthUserClass($UserName);
623                     } elseif (!empty($DBAuthParams['auth_check']) and ($DBAuthParams['auth_dsn'] or $GLOBALS ['DBParams']['dsn'])) {
624                         return new _DbUserClass($UserName);
625                     } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
626                         return new _LDAPUserClass($UserName);
627                     } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
628                         return new _IMAPUserClass($UserName);
629                     } elseif (defined('AUTH_USER_FILE')) {
630                         return new _FileUserClass($UserName);
631                     } else {
632                         return new _PersonalPageUserClass($UserName);
633                     }
634                 }
635                 else 
636                     // else use the page methods defined in _PassUser.
637                     return $this;
638             }
639         }
640     }
641
642     function getAuthDbh () {
643         global $request, $DBParams, $DBAuthParams;
644         if (empty($this->_auth_dbi)) {
645             if ($DBParams['dbtype'] == 'SQL' and empty($DBAuthParams['auth_dsn']))
646                 $dbh = $request->getDbh(); // use phpwiki database 
647             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
648                 $dbh = $request->getDbh(); // same phpwiki database 
649             else // use another external database handle. needs PHP >= 4.1
650                 $dbh = WikiDB::open($DBAuthParams);
651             $this->_auth_dbi = & $dbh->_backend->_dbh;    
652         }
653         return $this->_auth_dbi;
654     }
655
656     //TODO: password changing
657     //TODO: email verification
658
659     function getPreferences() {
660
661         // We don't necessarily have to read the cookie first. Since
662         // the user has a password, the prefs stored in the homepage
663         // cannot be arbitrarily altered by other Bogo users.
664         _AnonUser::getPreferences();
665
666         // database prefs
667         if ((! $this->_prefs) && $this->_prefselect) {
668             if ($this->_prefmethod == 'ADODB') {
669                 $dbh = & $this->_auth_dbi;
670                 $db_result = $dbh->Execute($this->_prefselect,$dbh->qstr($this->_userid));
671                 if (!$rs->EOF)
672                     $prefs_blob = $db_result->fields['pref_blob'];
673                 $db_result->Close();
674             }
675             else { // pear db methods
676                 $db_result = $this->_auth_dbi->execute($this->_prefselect,$this->_userid);
677                 list($prefs_blob) = $db_result->fetchRow();
678             }
679             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
680                 $this->_prefs = new UserPreferences($restored_from_db);
681                 return $this->_prefs;
682             }
683         }
684         
685         // User may have deleted cookie, retrieve from his
686         // PersonalPage if there is one.
687         if ((! $this->_prefs) && $this->_HomePagehandle) {
688             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
689                 $this->_prefs = new UserPreferences($restored_from_page);
690                 return $this->_prefs;
691             }
692         }
693         return $this->_prefs;
694     }
695
696     function setPreferences($prefs, $id_only=false) {
697         _AnonUser::setPreferences($prefs, $id_only);
698         // Encode only the _prefs array of the UserPreference object
699         $serialized = $this->_prefs->store();
700
701         // database prefs
702         if ((! $this->_prefs) && $this->_prefupdate) {
703             if ($this->_prefmethod == 'ADODB') {
704                 $dbh =& $this->_auth_dbi;
705                 $db_result = $dbh->Execute($this->_prefupdate,$dbh->qstr($serialized),$dbh->qstr($this->_userid));
706                 $db_result->Close();
707             }
708             else { // pear db methods
709                 $db_result = $this->_auth_dbi->execute($this->_prefupdate,$serialized,$this->_userid);
710             }
711         }
712         else
713             $this->_HomePagehandle->set('pref', $serialized);
714     }
715
716     function mayChangePass() {
717         return true;
718     }
719
720     //The default method is getting the password from prefs. 
721     // child methods obtain $stored_password from external auth.
722     function userExists() {
723         //if ($this->_HomePagehandle) return true;
724
725         if (USER_AUTH_POLICY === 'strict') {
726             if ($user = $this->nextClass())
727                 return $user->userExists();
728         }
729         return false;
730     }
731
732     //The default method is getting the password from prefs. 
733     // child methods obtain $stored_password from external auth.
734     function checkPass($submitted_password) {
735         $stored_password = $this->_prefs->get('passwd');
736         $result = $this->_checkPass($submitted_password, $stored_password);
737         if ($result) $this->_level = WIKIAUTH_USER;
738
739         if (!$result) {
740             if (USER_AUTH_POLICY === 'strict') {
741                 if ($user = $this->nextClass()) {
742                     if ($user = $user->userExists())
743                         return $user->checkPass($submitted_password);
744                 }
745             }
746             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
747                 if ($user = $this->nextClass())
748                     return $user->checkPass($submitted_password);
749             }
750         }
751         return $this->_level;
752     }
753
754     //TODO: remove crypt() function check from config.php:396 ??
755     function _checkPass($submitted_password, $stored_password) {
756         if(!empty($submitted_password)) {
757             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
758                 // Verify against encrypted password.
759                 if (function_exists('crypt')) {
760                     if (crypt($submitted_password, $stored_password) == $stored_password )
761                         return true; // matches encrypted password
762                     else
763                         return false;
764                 }
765                 else {
766                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
767                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and change ADMIN_PASSWD."),
768                                   E_USER_WARNING);
769                     return false;
770                 }
771             }
772             else {
773                 // Verify against cleartext password.
774                 if ($submitted_password == $stored_password)
775                     return true;
776                 else {
777                     // Check whether we forgot to enable ENCRYPTED_PASSWD
778                     if (function_exists('crypt')) {
779                         if (crypt($submitted_password, $stored_password) == $stored_password) {
780                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
781                                           E_USER_WARNING);
782                             return true;
783                         }
784                     }
785                 }
786             }
787         }
788         return false;
789     }
790 }
791
792 class _BogoLoginUser
793 extends _PassUser
794 {
795     function userExists() {
796         if (isWikiWord($this->_userid)) {
797             $this->_level = WIKIAUTH_BOGO;
798             return true;
799         } else {
800             $this->_level = WIKIAUTH_ANON;
801             return false;
802         }
803     }
804
805     function checkPass($submitted_password) {
806         // A BogoLoginUser requires PASSWORD_LENGTH_MINIMUM.
807         if ($this->userExists())
808         return $this->_level;
809     }
810 }
811
812
813 class _PersonalPagePassUser
814 extends _PassUser
815 /**
816  * This class is only to simplify the auth method dispatcher.
817  * It inherits all methods from _PassUser.
818  */
819 {
820     function dummy() {}
821 }
822
823 class _DbPassUser
824 extends _PassUser
825 /**
826  * Authenticate against a database, to be able to use shared users.
827  *   internal: no different $DbAuthParams['dsn'] defined, or
828  *   external: different $DbAuthParams['dsn']
829  * The magic is done in the symbolic SQL statements in index.php
830  *
831  * We support only the SQL and ADODB backends.
832  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
833  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
834  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
835  * Flat files for auth use is handled by the auth method "File".
836  *
837  * Preferences are handled in the parent class.
838  */
839 {
840     var $_authselect, $_authupdate;
841
842     // This can only be called from _PassUser, because the parent class 
843     // sets the auth_dbi and pref methods, before this class is initialized.
844     function _DbPassUser() {
845         if (!$this->_prefs) {
846             trigger_error(__vsprintf("Internal error: %s may only called from %s","_DbPassUser","_PassUser"),
847                           E_USER_WARNING);
848             return false;
849         }
850         $this->_authmethod = 'DB';
851         $this->_auth_dbi = $this->getAuthDbh();
852         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
853
854         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') 
855             return new _AdoDbPassUser();
856         else 
857             return new _PearDbPassUser();
858     }
859
860     function mayChangePass() {
861         return !empty($this->_authupdate);
862     }
863
864 }
865
866 class _PearDbPassUser
867 extends _DbPassUser
868 /**
869  * Pear DB methods
870  */
871 {
872     function _PearDbPassUser() {
873         global $DBAuthParams;
874         if (!$this->_prefs) {
875             trigger_error(__vsprintf("Internal error: %s may only called from %s","_PearDbPassUser","_DbPassUser"),
876                           E_USER_WARNING);
877             return false;
878         }
879         // Prepare the configured auth statements
880         if (!empty($DBAuthParams['auth_check'])) {
881             $this->_authselect = $this->_auth_dbi->prepare (
882                      str_replace(array('"$userid"','"$password"'),array('?','?'),
883                                   $DBAuthParams['auth_check'])
884                      );
885         }
886         if (!empty($DBAuthParams['auth_update'])) {
887             $this->_authupdate = $this->_auth_dbi->prepare(
888                     str_replace(array('"$userid"','"$password"'),array('?','?'),$DBAuthParams['auth_update'])
889                     );
890         }
891     }
892
893     function getPreferences() {
894         // override the generic slow method here for efficiency and not to 
895         // clutter the homepage metadata with prefs.
896         _AnonUser::getPreferences();
897         if ((! $this->_prefs) && $this->_prefselect) {
898             $db_result = $this->_auth_dbi->execute($this->_prefselect,$this->_userid);
899             list($prefs_blob) = $db_result->fetchRow();
900             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
901                 $this->_prefs = new UserPreferences($restored_from_db);
902                 return $this->_prefs;
903             }
904         }
905         if ((! $this->_prefs) && $this->_HomePagehandle) {
906             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
907                 $this->_prefs = new UserPreferences($restored_from_page);
908                 return $this->_prefs;
909             }
910         }
911         return $this->_prefs;
912     }
913
914     function setPreferences($prefs, $id_only=false) {
915         $serialized = $this->_prefs->store();
916         if ($this->_prefupdate) {
917             $db_result = $this->_auth_dbi->execute($this->_prefupdate,$serialized,$this->_userid);
918         } else {
919             _AnonUser::setPreferences($prefs, $id_only);
920             $this->_HomePagehandle->set('pref', $serialized);
921         }
922     }
923
924     function userExists() {
925         if (!$this->_authselect)
926             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
927                           E_USER_WARNING);
928         $dbh = &$this->_auth_dbi;
929         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
930         if ($this->_auth_crypt_method == 'crypt') {
931             $rs = $dbh->Execute($this->_authselect,$this->_userid) ;
932             if ($rs->numRows())
933                 return true;
934         }
935         else {
936             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
937                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
938                               E_USER_WARNING);
939             $this->_authcheck = str_replace('"$userid"','?',
940                                              $GLOBALS['DBAuthParams']['auth_user_exists']);
941             $rs = $dbh->Execute($this->_authcheck,
942                                           $this->_userid) ;
943             if ($rs->numRows())
944                 return true;
945         }
946         
947         if (USER_AUTH_POLICY === 'strict') {
948             if ($user = $this->nextClass()) {
949                 return $user->userExists();
950             }
951         }
952     }
953  
954     function checkPass($submitted_password) {
955         if (!$this->_authselect)
956             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
957                           E_USER_WARNING);
958
959         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
960         if ($this->_auth_crypt_method == 'crypt') {
961             $db_result = $this->_auth_dbi->execute($this->_authselect,$this->_userid);
962             list($stored_password) = $db_result->fetchRow();
963             $result = $this->_checkPass($submitted_password, $stored_password);
964         } else {
965             $db_result = $this->_auth_dbi->execute($this->_authselect,$submitted_password,$this->_userid);
966             list($okay) = $db_result->fetchRow();
967             $result = !empty($okay);
968         }
969
970         if ($result) {
971             $this->_level = WIKIAUTH_USER;
972         } else {
973             if (USER_AUTH_POLICY === 'strict') {
974                 if ($user = $this->nextClass()) {
975                     if ($user = $user->userExists())
976                         return $user->checkPass($submitted_password);
977                 }
978             }
979             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
980                 if ($user = $this->nextClass())
981                     return $user->checkPass($submitted_password);
982             }
983         }
984         return $this->_level;
985     }
986
987     function storePass($submitted_password) {
988         if (!$this->_authupdate) {
989             //CHECKME
990             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
991                           E_USER_WARNING);
992             return false;
993         }
994
995         if ($this->_auth_crypt_method == 'crypt') {
996             if (function_exists('crypt'))
997                 $submitted_password = crypt($submitted_password);
998         }
999         $db_result = $this->_auth_dbi->execute($this->_authupdate,$submitted_password,$this->_userid);
1000     }
1001
1002 }
1003
1004 class _AdoDbPassUser
1005 extends _DbPassUser
1006 /**
1007  * ADODB methods
1008  */
1009 {
1010     function _AdoDbPassUser() {
1011         global $DBAuthParams;
1012         if (!$this->_prefs) {
1013             trigger_error(__vsprintf("Internal error: %s may only called from %s","_AdoDbPassUser","_DbPassUser"),
1014                           E_USER_WARNING);
1015             return false;
1016         }
1017         // Prepare the configured auth statements
1018         if (!empty($DBAuthParams['auth_check'])) {
1019             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1020                                               $DBAuthParams['auth_check']);
1021         }
1022         if (!empty($DBAuthParams['auth_update'])) {
1023             $this->_authupdate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1024                                               $DBAuthParams['auth_update']);
1025         }
1026     }
1027
1028     function getPreferences() {
1029         // override the generic slow method here for efficiency
1030         _AnonUser::getPreferences();
1031         if ((! $this->_prefs) && $this->_prefselect) {
1032             $dbh = & $this->_auth_dbi;
1033             $rs = $dbh->Execute($this->_prefselect,$dbh->qstr($this->_userid));
1034             if ($rs->EOF) {
1035                 $rs->Close();
1036             } else {
1037                 $prefs_blob = $rs->fields['pref_blob'];
1038                 $rs->Close();
1039                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1040                     $this->_prefs = new UserPreferences($restored_from_db);
1041                     return $this->_prefs;
1042                 }
1043             }
1044         }
1045         if ((! $this->_prefs) && $this->_HomePagehandle) {
1046             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1047                 $this->_prefs = new UserPreferences($restored_from_page);
1048                 return $this->_prefs;
1049             }
1050         }
1051         return $this->_prefs;
1052     }
1053
1054     function setPreferences($prefs, $id_only=false) {
1055         $serialized = $this->_prefs->store();
1056         if ($this->_prefupdate) {
1057             $dbh = & $this->_auth_dbi;
1058             $db_result = $dbh->Execute($this->_prefupdate,$dbh->qstr($serialized),$dbh->qstr($this->_userid));
1059             $db_result->Close();
1060         } else {
1061             _AnonUser::setPreferences($prefs, $id_only);
1062             $this->_HomePagehandle->set('pref', $serialized);
1063         }
1064     }
1065  
1066     function userExists() {
1067         if (!$this->_authselect)
1068             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1069                           E_USER_WARNING);
1070         $dbh = &$this->_auth_dbi;
1071         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1072         if ($this->_auth_crypt_method == 'crypt') {
1073             $rs = $dbh->Execute($this->_authselect,$dbh->qstr($this->_userid));
1074             if (!$rs->EOF) {
1075                 $rs->Close();
1076                 return true;
1077             } else {
1078                 $rs->Close();
1079             }
1080         }
1081         else {
1082             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1083                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1084                               E_USER_WARNING);
1085             $this->_authcheck = str_replace('"$userid"','%s',
1086                                              $GLOBALS['DBAuthParams']['auth_user_exists']);
1087             $rs = $dbh->Execute($this->_authcheck,
1088                                           $dbh->qstr($this->_userid));
1089             if (!$rs->EOF) {
1090                 $rs->Close();
1091                 return true;
1092             } else {
1093                 $rs->Close();
1094             }
1095         }
1096         
1097         if (USER_AUTH_POLICY === 'strict') {
1098             if ($user = $this->nextClass())
1099                 return $user->userExists();
1100         }
1101         return false;
1102     }
1103
1104     function checkPass($submitted_password) {
1105         if (!$this->_authselect)
1106             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1107                           E_USER_WARNING);
1108         $dbh = &$this->_auth_dbi;
1109         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1110         if ($this->_auth_crypt_method == 'crypt') {
1111             $rs = $dbh->Execute($this->_authselect,$dbh->qstr($this->_userid));
1112             if (!$rs->EOF) {
1113                 $stored_password = $rs->fields['password'];
1114                 $rs->Close();
1115                 $result = $this->_checkPass($submitted_password, $stored_password);
1116             } else {
1117                 $rs->Close();
1118                 $result = false;
1119             }
1120         }
1121         else {
1122             $rs = $dbh->Execute($this->_authselect,
1123                                           $dbh->qstr($submitted_password),
1124                                           $dbh->qstr($this->_userid));
1125             $okay = $rs->fields['ok'];
1126             $rs->Close();
1127             $result = !empty($okay);
1128         }
1129
1130         if ($result) { 
1131             $this->_level = WIKIAUTH_USER;
1132         } else {
1133             if (USER_AUTH_POLICY === 'strict') {
1134                 if ($user = $this->nextClass()) {
1135                     if ($user = $user->userExists())
1136                         return $user->checkPass($submitted_password);
1137                 }
1138             }
1139             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1140                 if ($user = $this->nextClass())
1141                     return $user->checkPass($submitted_password);
1142             }
1143         }
1144         return $this->_level;
1145     }
1146
1147     function storePass($submitted_password) {
1148         if (!$this->_authupdate) {
1149             //CHECKME
1150             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1151                           E_USER_WARNING);
1152             return false;
1153         }
1154
1155         if ($this->_auth_crypt_method == 'crypt') {
1156             if (function_exists('crypt'))
1157                 $submitted_password = crypt($submitted_password);
1158         }
1159         $dbh = &$this->_auth_dbi;
1160         $rs = $dbh->Execute($this->_authupdate,
1161                                       $dbh->qstr($submitted_password),
1162                                       $dbh->qstr($this->_userid));
1163         $rs->Close();
1164     }
1165
1166 }
1167
1168 class _LDAPPassUser
1169 extends _PassUser
1170 /**
1171  * Define the vars LDAP_HOST and LDAP_BASE_DN in index.php
1172  *
1173  * Preferences are handled in _PassUser
1174  */
1175 {
1176     function checkPass($submitted_password) {
1177         $this->_authmethod = 'LDAP';
1178         $userid = $this->_userid;
1179         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1180             $r = @ldap_bind($ldap); // this is an anonymous bind
1181             $st_search = "uid=$userid";
1182             // Need to set the right root search information. see ../index.php
1183             $sr = ldap_search($ldap, LDAP_BASE_DN,
1184                               "$st_search");
1185             $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1186             for ($i = 0; $i < $info["count"]; $i++) {
1187                 $dn = $info[$i]["dn"];
1188                 // The password is still plain text.
1189                 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
1190                     // ldap_bind will return TRUE if everything matches
1191                     ldap_close($ldap);
1192                     $this->_level = WIKIAUTH_USER;
1193                     return $this->_level;
1194                 }
1195             }
1196         } else {
1197             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1198         }
1199
1200         if (USER_AUTH_POLICY === 'strict') {
1201             if ($user = $this->nextClass()) {
1202                 if ($user = $user->userExists())
1203                     return $user->checkPass($submitted_password);
1204             }
1205         }
1206         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1207             if ($user = $this->nextClass())
1208                 return $user->checkPass($submitted_password);
1209         }
1210         return false;
1211     }
1212
1213     function userExists() {
1214         $userid = $this->_userid;
1215         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1216             $r = @ldap_bind($ldap); // this is an anonymous bind
1217             $st_search = "uid=$userid";
1218             // Need to set the right root search information. see ../index.php
1219             $sr = ldap_search($ldap, LDAP_BASE_DN,
1220                               "$st_search");
1221             $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1222             if ($info["count"]) {
1223                 ldap_close($ldap);
1224                 return true;
1225             }
1226         } else {
1227             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1228         }
1229
1230         if (USER_AUTH_POLICY === 'strict') {
1231             if ($user = $this->nextClass())
1232                 return $user->userExists();
1233         }
1234         return false;
1235     }
1236
1237     function mayChangePass() {
1238         return false;
1239     }
1240
1241 }
1242
1243 class _IMAPPassUser
1244 extends _PassUser
1245 /**
1246  * Define the var IMAP_HOST in index.php
1247  *
1248  * Preferences are handled in _PassUser
1249  */
1250 {
1251     function checkPass($submitted_password) {
1252         $userid = $this->_userid;
1253         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1254                             $userid, $submitted_password, OP_HALFOPEN );
1255         if ($mbox) {
1256             imap_close($mbox);
1257             $this->_authmethod = 'IMAP';
1258             $this->_level = WIKIAUTH_USER;
1259             return $this->_level;
1260         } else {
1261             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1262         }
1263         if (USER_AUTH_POLICY === 'strict') {
1264             if ($user = $this->nextClass()) {
1265                 if ($user = $user->userExists())
1266                     return $user->checkPass($submitted_password);
1267             }
1268         }
1269         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1270             if ($user = $this->nextClass())
1271                 return $user->checkPass($submitted_password);
1272         }
1273         return false;
1274     }
1275
1276     //CHECKME: this will not be okay for the auth policy strict
1277     function userExists() {
1278         if (checkPass($this->_prefs->get('passwd')))
1279             return true;
1280             
1281         if (USER_AUTH_POLICY === 'strict') {
1282             if ($user = $this->nextClass())
1283                 return $user->userExists();
1284         }
1285     }
1286
1287     function mayChangePass() {
1288         return false;
1289     }
1290
1291 }
1292
1293 class _FilePassUser
1294 extends _PassUser
1295 /**
1296  * Check users defined in a .htaccess style file
1297  * username:crypt\n...
1298  *
1299  * Preferences are handled in _PassUser
1300  */
1301 {
1302     var $_file, $_may_change;
1303
1304     // This can only be called from _PassUser, because the parent class 
1305     // sets the pref methods, before this class is initialized.
1306     function _FilePassUser($file = '') {
1307         global $DBAuthParams;
1308         if (!$this->_prefs) {
1309             trigger_error(__vsprintf("Internal error: %s may only called from %s","_FilePassUser","_PassUser"),
1310                           E_USER_WARNING);
1311             return false;
1312         }
1313
1314         // read the .htaccess style file. We use our own copy of the standard pear class.
1315         require 'lib/pear/File_Passwd.php';
1316         // if passwords may be changed we have to lock them:
1317         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1318         if (empty($file) and defined('AUTH_USER_FILE'))
1319             $this->_file = AUTH_USER_FILE;
1320         elseif (!empty($file))
1321             $this->_file = File_Passwd($file, !empty($this->_may_change));
1322         else
1323             return false;
1324         return $this;
1325     }
1326  
1327     function mayChangePass() {
1328         return $this->_may_change;
1329     }
1330
1331     function userExists() {
1332         if (isset($this->_file->users[$this->_userid]))
1333             return true;
1334             
1335         if (USER_AUTH_POLICY === 'strict') {
1336             if ($user = $this->nextClass())
1337                 return $user->userExists();
1338         }
1339     }
1340
1341     function checkPass($submitted_password) {
1342         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1343             $this->_authmethod = 'File';
1344             $this->_level = WIKIAUTH_USER;
1345             return $this->_level;
1346         }
1347         
1348         if (USER_AUTH_POLICY === 'strict') {
1349             if ($user = $this->nextClass()) {
1350                 if ($user = $user->userExists())
1351                     return $user->checkPass($submitted_password);
1352             }
1353         }
1354         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1355             if ($user = $this->nextClass())
1356                 return $user->checkPass($submitted_password);
1357         }
1358         return false;
1359     }
1360
1361     function storePass($submitted_password) {
1362         if ($this->_may_change)
1363             return $this->_file->modUser($this->_userid,$submitted_password);
1364         else 
1365             return false;
1366     }
1367
1368 }
1369
1370 /**
1371  * Insert more auth classes here...
1372  *
1373  */
1374
1375
1376 /**
1377  * For security, this class should not be extended. Instead, extend
1378  * from _PassUser (think of this as unix "root").
1379  */
1380 class _AdminUser
1381 extends _PassUser
1382 {
1383     //var $_level = WIKIAUTH_ADMIN;
1384
1385     function checkPass($submitted_password) {
1386         $stored_password = ADMIN_PASSWD;
1387         if ($this->_checkPass($submitted_password, $stored_password)) {
1388             $this->_level = WIKIAUTH_ADMIN;
1389             return $this->_level;
1390         } else {
1391             $this->_level = WIKIAUTH_ANON;
1392             return false;
1393         }
1394     }
1395
1396 }
1397
1398 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1399 /**
1400  * Various data classes for the preference types, 
1401  * to support get, set, sanify (range checking, ...)
1402  * update() will do the neccessary side-effects if a 
1403  * setting gets changed (theme, language, ...)
1404 */
1405
1406 class _UserPreference
1407 {
1408     var $default_value;
1409
1410     function _UserPreference ($default_value) {
1411         $this->default_value = $default_value;
1412     }
1413
1414     function sanify ($value) {
1415         return (string)$value;
1416     }
1417
1418     function get ($name) {
1419         if (isset($this->$name))
1420             return $this->{$name};
1421         else 
1422             return $this->default_value;
1423     }
1424
1425     function getraw ($name) {
1426         if (!empty($this->{$name}))
1427             return $this->{$name};
1428     }
1429
1430     // stores the value as $this->$name, and not as $this->value (clever?)
1431     function set ($name, $value) {
1432         if ($value != $this->default_value)
1433             $this->$name = $value;
1434         else 
1435             unset($this->$name);
1436     }
1437
1438     // default: no side-effects 
1439     function update ($value) {
1440     }
1441 }
1442
1443 class _UserPreference_numeric
1444 extends _UserPreference
1445 {
1446     function _UserPreference_numeric ($default, $minval = false,
1447                                       $maxval = false) {
1448         $this->_UserPreference((double)$default);
1449         $this->_minval = (double)$minval;
1450         $this->_maxval = (double)$maxval;
1451     }
1452
1453     function sanify ($value) {
1454         $value = (double)$value;
1455         if ($this->_minval !== false && $value < $this->_minval)
1456             $value = $this->_minval;
1457         if ($this->_maxval !== false && $value > $this->_maxval)
1458             $value = $this->_maxval;
1459         return $value;
1460     }
1461 }
1462
1463 class _UserPreference_int
1464 extends _UserPreference_numeric
1465 {
1466     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1467         $this->_UserPreference_numeric((int)$default, (int)$minval,
1468                                        (int)$maxval);
1469     }
1470
1471     function sanify ($value) {
1472         return (int)parent::sanify((int)$value);
1473     }
1474 }
1475
1476 class _UserPreference_bool
1477 extends _UserPreference
1478 {
1479     function _UserPreference_bool ($default = false) {
1480         $this->_UserPreference((bool)$default);
1481     }
1482
1483     function sanify ($value) {
1484         if (is_array($value)) {
1485             /* This allows for constructs like:
1486              *
1487              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1488              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1489              *
1490              * (If the checkbox is not checked, only the hidden input
1491              * gets sent. If the checkbox is sent, both inputs get
1492              * sent.)
1493              */
1494             foreach ($value as $val) {
1495                 if ($val)
1496                     return true;
1497             }
1498             return false;
1499         }
1500         return (bool) $value;
1501     }
1502 }
1503
1504 class _UserPreference_language
1505 extends _UserPreference
1506 {
1507     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1508         $this->_UserPreference($default);
1509     }
1510
1511     // FIXME: check for valid locale
1512     function sanify ($value) {
1513         // Revert to DEFAULT_LANGUAGE if user does not specify
1514         // language in UserPreferences or chooses <system language>.
1515         if ($value == '' or empty($value))
1516             $value = DEFAULT_LANGUAGE;
1517
1518         return (string) $value;
1519     }
1520 }
1521
1522 class _UserPreference_theme
1523 extends _UserPreference
1524 {
1525     function _UserPreference_theme ($default = THEME) {
1526         $this->_UserPreference($default);
1527     }
1528
1529     function sanify ($value) {
1530         if (file_exists($this->_themefile($value)))
1531             return $value;
1532         return $this->default_value;
1533     }
1534
1535     function update ($newvalue) {
1536         global $Theme;
1537         include_once($this->_themefile($newvalue));
1538         if (empty($Theme))
1539             include_once($this->_themefile(THEME));
1540     }
1541
1542     function _themefile ($theme) {
1543         return "themes/$theme/themeinfo.php";
1544     }
1545 }
1546
1547 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1548
1549 /**
1550  * UserPreferences
1551  * 
1552  * This object holds the $request->_prefs subobjects.
1553  * A simple packed array of non-default values get's stored as cookie,
1554  * homepage, and database, which are converted to the array of 
1555  * ->_prefs objects.
1556  * We don't store the objects, because otherwise we will
1557  * not be able to upgrade any subobject. And it's a waste of space also.
1558  */
1559 class UserPreferences
1560 {
1561     function UserPreferences ($saved_prefs = false) {
1562         // userid stored too, to ensure the prefs are being loaded for
1563         // the correct (currently signing in) userid if stored in a
1564         // cookie.
1565         $this->_prefs
1566             = array(
1567                     'userid'        => new _UserPreference(''),
1568                     'passwd'        => new _UserPreference(''),
1569                     'autologin'     => new _UserPreference_bool(),
1570                     'email'         => new _UserPreference(''),
1571                     'emailVerified' => new _UserPreference_bool(),
1572                     'notifyPages'   => new _UserPreference(''),
1573                     'theme'         => new _UserPreference_theme(THEME),
1574                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
1575                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1576                                                                EDITWIDTH_MIN_COLS,
1577                                                                EDITWIDTH_MAX_COLS),
1578                     'noLinkIcons'   => new _UserPreference_bool(),
1579                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1580                                                                EDITHEIGHT_MIN_ROWS,
1581                                                                EDITHEIGHT_DEFAULT_ROWS),
1582                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1583                                                                    TIMEOFFSET_MIN_HOURS,
1584                                                                    TIMEOFFSET_MAX_HOURS),
1585                     'relativeDates' => new _UserPreference_bool()
1586                     );
1587
1588         if (is_array($saved_prefs)) {
1589             foreach ($saved_prefs as $name => $value)
1590                 $this->set($name, $value);
1591         }
1592     }
1593
1594     function _getPref ($name) {
1595         if (!isset($this->_prefs[$name])) {
1596             if ($name == 'passwd2') return false;
1597             trigger_error("$name: unknown preference", E_USER_NOTICE);
1598             return false;
1599         }
1600         return $this->_prefs[$name];
1601     }
1602     
1603     // get the value or default_value of the subobject
1604     function get ($name) {
1605         if ($_pref = $this->_getPref($name))
1606           return $_pref->get($name);
1607         else 
1608           return false;  
1609         /*      
1610         if (is_object($this->_prefs[$name]))
1611             return $this->_prefs[$name]->get($name);
1612         elseif (($value = $this->_getPref($name)) === false)
1613             return false;
1614         elseif (!isset($value))
1615             return $this->_prefs[$name]->default_value;
1616         else return $value;
1617         */
1618     }
1619
1620     // check and set the new value in the subobject
1621     function set ($name, $value) {
1622         $pref = $this->_getPref($name);
1623         if ($pref === false)
1624             return false;
1625
1626         /* do it here or outside? */
1627         if ($name == 'passwd' and 
1628             defined('PASSWORD_LENGTH_MINIMUM') and 
1629             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1630             //TODO: How to notify the user?
1631             return false;
1632         }
1633
1634         $newvalue = $pref->sanify($value);
1635         $oldvalue = $pref->get($name);
1636
1637         // update on changes
1638         if ($newvalue != $oldvalue)
1639             $pref->update($newvalue);
1640         return true;
1641
1642         // don't set default values to save space (in cookies, db and
1643         // sesssion)
1644         /*
1645         if ($value == $pref->default_value)
1646             unset($this->_prefs[$name]);
1647         else
1648             $this->_prefs[$name] = $pref;
1649         */
1650     }
1651
1652     // array of objects => array of values
1653     function store() {
1654         $prefs = array();
1655         foreach ($this->_prefs as $name => $object) {
1656             if ($value = $object->getraw($name))
1657                 $prefs[] = array($name => $value);
1658         }
1659         return $this->pack($prefs);
1660     }
1661
1662     // packed string or array of values => array of values
1663     function retrieve($packed) {
1664         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1665             $packed = unserialize($packed);
1666         if (!is_array($packed)) return false;
1667         $prefs = array();
1668         foreach ($packed as $name => $packed_pref) {
1669             if (substr($packed_pref, 0, 2) == "O:") {
1670                 //legacy: check if it's an old array of objects
1671                 // Looks like a serialized object. 
1672                 // This might fail if the object definition does not exist anymore.
1673                 // object with ->$name and ->default_value vars.
1674                 $pref = unserialize($packed_pref);
1675                 $prefs[$name] = $pref->get($name);
1676             } else {
1677                 $prefs[$name] = unserialize($packed_pref);
1678             }
1679         }
1680         return $prefs;
1681     }
1682     
1683     // array of objects
1684     function getAll() {
1685         return $this->_prefs;
1686     }
1687
1688     function pack($nonpacked) {
1689         return serialize($nonpacked);
1690     }
1691
1692     function unpack($packed) {
1693         if (!$packed)
1694             return false;
1695         if (substr($packed, 0, 2) == "O:") {
1696             // Looks like a serialized object
1697             return unserialize($packed);
1698         }
1699         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1700         //E_USER_WARNING);
1701         return false;
1702     }
1703
1704     function hash () {
1705         return hash($this->_prefs);
1706     }
1707 }
1708
1709
1710 // $Log: not supported by cvs2svn $
1711 // Revision 1.9  2004/01/30 19:57:58  rurban
1712 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1713 //
1714 // Revision 1.8  2004/01/30 18:46:15  rurban
1715 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
1716 //
1717 // Revision 1.7  2004/01/27 23:23:39  rurban
1718 // renamed ->Username => _userid for consistency
1719 // renamed mayCheckPassword => mayCheckPass
1720 // fixed recursion problem in WikiUserNew
1721 // fixed bogo login (but not quite 100% ready yet, password storage)
1722 //
1723 // Revision 1.6  2004/01/26 09:17:49  rurban
1724 // * changed stored pref representation as before.
1725 //   the array of objects is 1) bigger and 2)
1726 //   less portable. If we would import packed pref
1727 //   objects and the object definition was changed, PHP would fail.
1728 //   This doesn't happen with an simple array of non-default values.
1729 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1730 //   understands the interim format of array of objects also.
1731 // * simplified $prefs->get() and fixed $prefs->set()
1732 // * added $user->_userid and class '_WikiUser' portability functions
1733 // * fixed $user object ->_level upgrading, mostly using sessions.
1734 //   this fixes yesterdays problems with loosing authorization level.
1735 // * fixed WikiUserNew::checkPass to return the _level
1736 // * fixed WikiUserNew::isSignedIn
1737 // * added explodePageList to class PageList, support sortby arg
1738 // * fixed UserPreferences for WikiUserNew
1739 // * fixed WikiPlugin for empty defaults array
1740 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1741 //   removed sort arg, support sortby arg
1742 //
1743 // Revision 1.5  2004/01/25 03:05:00  rurban
1744 // First working version, but has some problems with the current main loop.
1745 // Implemented new auth method dispatcher and policies, all the external
1746 // _PassUser classes (also for ADODB and Pear DB).
1747 // The two global funcs UserExists() and CheckPass() are probably not needed,
1748 // since the auth loop is done recursively inside the class code, upgrading
1749 // the user class within itself.
1750 // Note: When a higher user class is returned, this doesn't mean that the user
1751 // is authorized, $user->_level is still low, and only upgraded on successful
1752 // login.
1753 //
1754 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
1755 // Code Housecleaning: fixed syntax errors. (php -l *.php)
1756 //
1757 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
1758 // Finished off logic for determining user class, including
1759 // PassUser. Removed ability of BogoUser to save prefs into a page.
1760 //
1761 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
1762 // Added admin user, password user, and preference classes. Added
1763 // password checking functions for users and the admin. (Now the easy
1764 // parts are nearly done).
1765 //
1766 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
1767 // Complete rewrite of WikiUser.php.
1768 //
1769 // This should make it easier to hook in user permission groups etc. some
1770 // time in the future. Most importantly, to finally get UserPreferences
1771 // fully working properly for all classes of users: AnonUser, BogoUser,
1772 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
1773 // want a cookie or not, and to bring back optional AutoLogin with the
1774 // UserName stored in a cookie--something that was lost after PhpWiki had
1775 // dropped the default http auth login method.
1776 //
1777 // Added WikiUser classes which will (almost) work together with existing
1778 // UserPreferences class. Other parts of PhpWiki need to be updated yet
1779 // before this code can be hooked up.
1780 //
1781
1782 // Local Variables:
1783 // mode: php
1784 // tab-width: 8
1785 // c-basic-offset: 4
1786 // c-hanging-comment-ender-p: nil
1787 // indent-tabs-mode: nil
1788 // End:
1789 ?>