]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
LDAP cleanup, start of new Pref classes
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.11 2004-02-03 09:45:39 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             // Need to set the right root search information. see ../index.php
1182             $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1183             $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1184             for ($i = 0; $i < $info["count"]; $i++) {
1185                 $dn = $info[$i]["dn"];
1186                 // The password is still plain text.
1187                 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
1188                     // ldap_bind will return TRUE if everything matches
1189                     ldap_close($ldap);
1190                     $this->_level = WIKIAUTH_USER;
1191                     return $this->_level;
1192                 }
1193             }
1194         } else {
1195             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1196         }
1197
1198         if (USER_AUTH_POLICY === 'strict') {
1199             if ($user = $this->nextClass()) {
1200                 if ($user = $user->userExists())
1201                     return $user->checkPass($submitted_password);
1202             }
1203         }
1204         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1205             if ($user = $this->nextClass())
1206                 return $user->checkPass($submitted_password);
1207         }
1208         return false;
1209     }
1210
1211     function userExists() {
1212         $userid = $this->_userid;
1213         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1214             $r = @ldap_bind($ldap);                 // this is an anonymous bind
1215             $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1216             $info = ldap_get_entries($ldap, $sr);
1217             if ($info["count"] > 0) {
1218                 ldap_close($ldap);
1219                 return true;
1220             }
1221         } else {
1222             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1223         }
1224
1225         if (USER_AUTH_POLICY === 'strict') {
1226             if ($user = $this->nextClass())
1227                 return $user->userExists();
1228         }
1229         return false;
1230     }
1231
1232     function mayChangePass() {
1233         return false;
1234     }
1235
1236 }
1237
1238 class _IMAPPassUser
1239 extends _PassUser
1240 /**
1241  * Define the var IMAP_HOST in index.php
1242  *
1243  * Preferences are handled in _PassUser
1244  */
1245 {
1246     function checkPass($submitted_password) {
1247         $userid = $this->_userid;
1248         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1249                             $userid, $submitted_password, OP_HALFOPEN );
1250         if ($mbox) {
1251             imap_close($mbox);
1252             $this->_authmethod = 'IMAP';
1253             $this->_level = WIKIAUTH_USER;
1254             return $this->_level;
1255         } else {
1256             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1257         }
1258         if (USER_AUTH_POLICY === 'strict') {
1259             if ($user = $this->nextClass()) {
1260                 if ($user = $user->userExists())
1261                     return $user->checkPass($submitted_password);
1262             }
1263         }
1264         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1265             if ($user = $this->nextClass())
1266                 return $user->checkPass($submitted_password);
1267         }
1268         return false;
1269     }
1270
1271     //CHECKME: this will not be okay for the auth policy strict
1272     function userExists() {
1273         if (checkPass($this->_prefs->get('passwd')))
1274             return true;
1275             
1276         if (USER_AUTH_POLICY === 'strict') {
1277             if ($user = $this->nextClass())
1278                 return $user->userExists();
1279         }
1280     }
1281
1282     function mayChangePass() {
1283         return false;
1284     }
1285
1286 }
1287
1288 class _FilePassUser
1289 extends _PassUser
1290 /**
1291  * Check users defined in a .htaccess style file
1292  * username:crypt\n...
1293  *
1294  * Preferences are handled in _PassUser
1295  */
1296 {
1297     var $_file, $_may_change;
1298
1299     // This can only be called from _PassUser, because the parent class 
1300     // sets the pref methods, before this class is initialized.
1301     function _FilePassUser($file = '') {
1302         global $DBAuthParams;
1303         if (!$this->_prefs) {
1304             trigger_error(__vsprintf("Internal error: %s may only called from %s","_FilePassUser","_PassUser"),
1305                           E_USER_WARNING);
1306             return false;
1307         }
1308
1309         // read the .htaccess style file. We use our own copy of the standard pear class.
1310         require 'lib/pear/File_Passwd.php';
1311         // if passwords may be changed we have to lock them:
1312         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1313         if (empty($file) and defined('AUTH_USER_FILE'))
1314             $this->_file = AUTH_USER_FILE;
1315         elseif (!empty($file))
1316             $this->_file = File_Passwd($file, !empty($this->_may_change));
1317         else
1318             return false;
1319         return $this;
1320     }
1321  
1322     function mayChangePass() {
1323         return $this->_may_change;
1324     }
1325
1326     function userExists() {
1327         if (isset($this->_file->users[$this->_userid]))
1328             return true;
1329             
1330         if (USER_AUTH_POLICY === 'strict') {
1331             if ($user = $this->nextClass())
1332                 return $user->userExists();
1333         }
1334     }
1335
1336     function checkPass($submitted_password) {
1337         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1338             $this->_authmethod = 'File';
1339             $this->_level = WIKIAUTH_USER;
1340             return $this->_level;
1341         }
1342         
1343         if (USER_AUTH_POLICY === 'strict') {
1344             if ($user = $this->nextClass()) {
1345                 if ($user = $user->userExists())
1346                     return $user->checkPass($submitted_password);
1347             }
1348         }
1349         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1350             if ($user = $this->nextClass())
1351                 return $user->checkPass($submitted_password);
1352         }
1353         return false;
1354     }
1355
1356     function storePass($submitted_password) {
1357         if ($this->_may_change)
1358             return $this->_file->modUser($this->_userid,$submitted_password);
1359         else 
1360             return false;
1361     }
1362
1363 }
1364
1365 /**
1366  * Insert more auth classes here...
1367  *
1368  */
1369
1370
1371 /**
1372  * For security, this class should not be extended. Instead, extend
1373  * from _PassUser (think of this as unix "root").
1374  */
1375 class _AdminUser
1376 extends _PassUser
1377 {
1378     //var $_level = WIKIAUTH_ADMIN;
1379
1380     function checkPass($submitted_password) {
1381         $stored_password = ADMIN_PASSWD;
1382         if ($this->_checkPass($submitted_password, $stored_password)) {
1383             $this->_level = WIKIAUTH_ADMIN;
1384             return $this->_level;
1385         } else {
1386             $this->_level = WIKIAUTH_ANON;
1387             return false;
1388         }
1389     }
1390
1391 }
1392
1393 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1394 /**
1395  * Various data classes for the preference types, 
1396  * to support get, set, sanify (range checking, ...)
1397  * update() will do the neccessary side-effects if a 
1398  * setting gets changed (theme, language, ...)
1399 */
1400
1401 class _UserPreference
1402 {
1403     var $default_value;
1404
1405     function _UserPreference ($default_value) {
1406         $this->default_value = $default_value;
1407     }
1408
1409     function sanify ($value) {
1410         return (string)$value;
1411     }
1412
1413     function get ($name) {
1414         if (isset($this->$name))
1415             return $this->{$name};
1416         else 
1417             return $this->default_value;
1418     }
1419
1420     function getraw ($name) {
1421         if (!empty($this->{$name}))
1422             return $this->{$name};
1423     }
1424
1425     // stores the value as $this->$name, and not as $this->value (clever?)
1426     function set ($name, $value) {
1427         if ($value != $this->default_value)
1428             $this->$name = $value;
1429         else 
1430             unset($this->$name);
1431     }
1432
1433     // default: no side-effects 
1434     function update ($value) {
1435     }
1436 }
1437
1438 class _UserPreference_numeric
1439 extends _UserPreference
1440 {
1441     function _UserPreference_numeric ($default, $minval = false,
1442                                       $maxval = false) {
1443         $this->_UserPreference((double)$default);
1444         $this->_minval = (double)$minval;
1445         $this->_maxval = (double)$maxval;
1446     }
1447
1448     function sanify ($value) {
1449         $value = (double)$value;
1450         if ($this->_minval !== false && $value < $this->_minval)
1451             $value = $this->_minval;
1452         if ($this->_maxval !== false && $value > $this->_maxval)
1453             $value = $this->_maxval;
1454         return $value;
1455     }
1456 }
1457
1458 class _UserPreference_int
1459 extends _UserPreference_numeric
1460 {
1461     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1462         $this->_UserPreference_numeric((int)$default, (int)$minval,
1463                                        (int)$maxval);
1464     }
1465
1466     function sanify ($value) {
1467         return (int)parent::sanify((int)$value);
1468     }
1469 }
1470
1471 class _UserPreference_bool
1472 extends _UserPreference
1473 {
1474     function _UserPreference_bool ($default = false) {
1475         $this->_UserPreference((bool)$default);
1476     }
1477
1478     function sanify ($value) {
1479         if (is_array($value)) {
1480             /* This allows for constructs like:
1481              *
1482              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1483              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1484              *
1485              * (If the checkbox is not checked, only the hidden input
1486              * gets sent. If the checkbox is sent, both inputs get
1487              * sent.)
1488              */
1489             foreach ($value as $val) {
1490                 if ($val)
1491                     return true;
1492             }
1493             return false;
1494         }
1495         return (bool) $value;
1496     }
1497 }
1498
1499 class _UserPreference_language
1500 extends _UserPreference
1501 {
1502     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1503         $this->_UserPreference($default);
1504     }
1505
1506     // FIXME: check for valid locale
1507     function sanify ($value) {
1508         // Revert to DEFAULT_LANGUAGE if user does not specify
1509         // language in UserPreferences or chooses <system language>.
1510         if ($value == '' or empty($value))
1511             $value = DEFAULT_LANGUAGE;
1512
1513         return (string) $value;
1514     }
1515 }
1516
1517 class _UserPreference_theme
1518 extends _UserPreference
1519 {
1520     function _UserPreference_theme ($default = THEME) {
1521         $this->_UserPreference($default);
1522     }
1523
1524     function sanify ($value) {
1525         if (file_exists($this->_themefile($value)))
1526             return $value;
1527         return $this->default_value;
1528     }
1529
1530     function update ($newvalue) {
1531         global $Theme;
1532         include_once($this->_themefile($newvalue));
1533         if (empty($Theme))
1534             include_once($this->_themefile(THEME));
1535     }
1536
1537     function _themefile ($theme) {
1538         return "themes/$theme/themeinfo.php";
1539     }
1540 }
1541
1542 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1543
1544 /**
1545  * UserPreferences
1546  * 
1547  * This object holds the $request->_prefs subobjects.
1548  * A simple packed array of non-default values get's stored as cookie,
1549  * homepage, or database, which are converted to the array of 
1550  * ->_prefs objects.
1551  * We don't store the objects, because otherwise we will
1552  * not be able to upgrade any subobject. And it's a waste of space also.
1553  */
1554 class UserPreferences
1555 {
1556     function UserPreferences ($saved_prefs = false) {
1557         // userid stored too, to ensure the prefs are being loaded for
1558         // the correct (currently signing in) userid if stored in a
1559         // cookie.
1560         $this->_prefs
1561             = array(
1562                     'userid'        => new _UserPreference(''),
1563                     'passwd'        => new _UserPreference(''),
1564                     'autologin'     => new _UserPreference_bool(),
1565                     'email'         => new _UserPreference(''),
1566                     'emailVerified' => new _UserPreference_bool(),
1567                     'notifyPages'   => new _UserPreference(''),
1568                     'theme'         => new _UserPreference_theme(THEME),
1569                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
1570                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1571                                                                EDITWIDTH_MIN_COLS,
1572                                                                EDITWIDTH_MAX_COLS),
1573                     'noLinkIcons'   => new _UserPreference_bool(),
1574                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1575                                                                EDITHEIGHT_MIN_ROWS,
1576                                                                EDITHEIGHT_DEFAULT_ROWS),
1577                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1578                                                                    TIMEOFFSET_MIN_HOURS,
1579                                                                    TIMEOFFSET_MAX_HOURS),
1580                     'relativeDates' => new _UserPreference_bool()
1581                     );
1582
1583         if (is_array($saved_prefs)) {
1584             foreach ($saved_prefs as $name => $value)
1585                 $this->set($name, $value);
1586         }
1587     }
1588
1589     function _getPref ($name) {
1590         if (!isset($this->_prefs[$name])) {
1591             if ($name == 'passwd2') return false;
1592             trigger_error("$name: unknown preference", E_USER_NOTICE);
1593             return false;
1594         }
1595         return $this->_prefs[$name];
1596     }
1597     
1598     // get the value or default_value of the subobject
1599     function get ($name) {
1600         if ($_pref = $this->_getPref($name))
1601           return $_pref->get($name);
1602         else 
1603           return false;  
1604         /*      
1605         if (is_object($this->_prefs[$name]))
1606             return $this->_prefs[$name]->get($name);
1607         elseif (($value = $this->_getPref($name)) === false)
1608             return false;
1609         elseif (!isset($value))
1610             return $this->_prefs[$name]->default_value;
1611         else return $value;
1612         */
1613     }
1614
1615     // check and set the new value in the subobject
1616     function set ($name, $value) {
1617         $pref = $this->_getPref($name);
1618         if ($pref === false)
1619             return false;
1620
1621         /* do it here or outside? */
1622         if ($name == 'passwd' and 
1623             defined('PASSWORD_LENGTH_MINIMUM') and 
1624             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1625             //TODO: How to notify the user?
1626             return false;
1627         }
1628
1629         $newvalue = $pref->sanify($value);
1630         $oldvalue = $pref->get($name);
1631
1632         // update on changes
1633         if ($newvalue != $oldvalue)
1634             $pref->update($newvalue);
1635         return true;
1636
1637         // don't set default values to save space (in cookies, db and
1638         // sesssion)
1639         /*
1640         if ($value == $pref->default_value)
1641             unset($this->_prefs[$name]);
1642         else
1643             $this->_prefs[$name] = $pref;
1644         */
1645     }
1646
1647     // array of objects => array of values
1648     function store() {
1649         $prefs = array();
1650         foreach ($this->_prefs as $name => $object) {
1651             if ($value = $object->getraw($name))
1652                 $prefs[] = array($name => $value);
1653         }
1654         return $this->pack($prefs);
1655     }
1656
1657     // packed string or array of values => array of values
1658     function retrieve($packed) {
1659         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1660             $packed = unserialize($packed);
1661         if (!is_array($packed)) return false;
1662         $prefs = array();
1663         foreach ($packed as $name => $packed_pref) {
1664             if (substr($packed_pref, 0, 2) == "O:") {
1665                 //legacy: check if it's an old array of objects
1666                 // Looks like a serialized object. 
1667                 // This might fail if the object definition does not exist anymore.
1668                 // object with ->$name and ->default_value vars.
1669                 $pref = unserialize($packed_pref);
1670                 $prefs[$name] = $pref->get($name);
1671             } else {
1672                 $prefs[$name] = unserialize($packed_pref);
1673             }
1674         }
1675         return $prefs;
1676     }
1677     
1678     // array of objects
1679     function getAll() {
1680         return $this->_prefs;
1681     }
1682
1683     function pack($nonpacked) {
1684         return serialize($nonpacked);
1685     }
1686
1687     function unpack($packed) {
1688         if (!$packed)
1689             return false;
1690         if (substr($packed, 0, 2) == "O:") {
1691             // Looks like a serialized object
1692             return unserialize($packed);
1693         }
1694         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1695         //E_USER_WARNING);
1696         return false;
1697     }
1698
1699     function hash () {
1700         return hash($this->_prefs);
1701     }
1702 }
1703
1704 class CookieUserPreferences
1705 extends UserPreferences
1706 {
1707     function CookieUserPreferences ($saved_prefs = false) {
1708         UserPreferences::UserPreferences($saved_prefs);
1709     }
1710 }
1711
1712 class PageUserPreferences
1713 extends UserPreferences
1714 {
1715     function PageUserPreferences ($saved_prefs = false) {
1716         UserPreferences::UserPreferences($saved_prefs);
1717     }
1718 }
1719
1720 class DbUserPreferences
1721 extends UserPreferences
1722 {
1723     function DbUserPreferences ($saved_prefs = false) {
1724         UserPreferences::UserPreferences($saved_prefs);
1725     }
1726 }
1727
1728
1729 // $Log: not supported by cvs2svn $
1730 // Revision 1.10  2004/02/01 09:14:11  rurban
1731 // Started with Group_Ldap (not yet ready)
1732 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
1733 // fixed some configurator vars
1734 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
1735 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
1736 // USE_DB_SESSION defaults to true on SQL
1737 // changed GROUP_METHOD definition to string, not constants
1738 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
1739 //   create users. (Not to be used with external databases generally, but
1740 //   with the default internal user table)
1741 //
1742 // fixed the IndexAsConfigProblem logic. this was flawed:
1743 //   scripts which are the same virtual path defined their own lib/main call
1744 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
1745 //
1746 // Revision 1.9  2004/01/30 19:57:58  rurban
1747 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1748 //
1749 // Revision 1.8  2004/01/30 18:46:15  rurban
1750 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
1751 //
1752 // Revision 1.7  2004/01/27 23:23:39  rurban
1753 // renamed ->Username => _userid for consistency
1754 // renamed mayCheckPassword => mayCheckPass
1755 // fixed recursion problem in WikiUserNew
1756 // fixed bogo login (but not quite 100% ready yet, password storage)
1757 //
1758 // Revision 1.6  2004/01/26 09:17:49  rurban
1759 // * changed stored pref representation as before.
1760 //   the array of objects is 1) bigger and 2)
1761 //   less portable. If we would import packed pref
1762 //   objects and the object definition was changed, PHP would fail.
1763 //   This doesn't happen with an simple array of non-default values.
1764 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1765 //   understands the interim format of array of objects also.
1766 // * simplified $prefs->get() and fixed $prefs->set()
1767 // * added $user->_userid and class '_WikiUser' portability functions
1768 // * fixed $user object ->_level upgrading, mostly using sessions.
1769 //   this fixes yesterdays problems with loosing authorization level.
1770 // * fixed WikiUserNew::checkPass to return the _level
1771 // * fixed WikiUserNew::isSignedIn
1772 // * added explodePageList to class PageList, support sortby arg
1773 // * fixed UserPreferences for WikiUserNew
1774 // * fixed WikiPlugin for empty defaults array
1775 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1776 //   removed sort arg, support sortby arg
1777 //
1778 // Revision 1.5  2004/01/25 03:05:00  rurban
1779 // First working version, but has some problems with the current main loop.
1780 // Implemented new auth method dispatcher and policies, all the external
1781 // _PassUser classes (also for ADODB and Pear DB).
1782 // The two global funcs UserExists() and CheckPass() are probably not needed,
1783 // since the auth loop is done recursively inside the class code, upgrading
1784 // the user class within itself.
1785 // Note: When a higher user class is returned, this doesn't mean that the user
1786 // is authorized, $user->_level is still low, and only upgraded on successful
1787 // login.
1788 //
1789 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
1790 // Code Housecleaning: fixed syntax errors. (php -l *.php)
1791 //
1792 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
1793 // Finished off logic for determining user class, including
1794 // PassUser. Removed ability of BogoUser to save prefs into a page.
1795 //
1796 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
1797 // Added admin user, password user, and preference classes. Added
1798 // password checking functions for users and the admin. (Now the easy
1799 // parts are nearly done).
1800 //
1801 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
1802 // Complete rewrite of WikiUser.php.
1803 //
1804 // This should make it easier to hook in user permission groups etc. some
1805 // time in the future. Most importantly, to finally get UserPreferences
1806 // fully working properly for all classes of users: AnonUser, BogoUser,
1807 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
1808 // want a cookie or not, and to bring back optional AutoLogin with the
1809 // UserName stored in a cookie--something that was lost after PhpWiki had
1810 // dropped the default http auth login method.
1811 //
1812 // Added WikiUser classes which will (almost) work together with existing
1813 // UserPreferences class. Other parts of PhpWiki need to be updated yet
1814 // before this code can be hooked up.
1815 //
1816
1817 // Local Variables:
1818 // mode: php
1819 // tab-width: 8
1820 // c-basic-offset: 4
1821 // c-hanging-comment-ender-p: nil
1822 // indent-tabs-mode: nil
1823 // End:
1824 ?>