]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
renamed ->Username => _userid for consistency
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.7 2004-01-27 23:23: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;
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             $dbh = $this->getAuthDbh();
575             // preparate the SELECT statement
576             $this->_prefselect = $dbh->_backend->prepare(
577                 preg_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             $dbh = $this->getAuthDbh();
583             // preparate the SELECT statement
584             $this->_prefselect = preg_replace('"$userid"','%s',$DBAuthParams['pref_select']);
585         }
586         if (!empty($DBAuthParams['pref_update']) and $DBParams['dbtype'] == 'SQL') {
587             $this->_prefmethod = 'SQL';
588             $dbh = $this->getAuthDbh();
589             $this->_prefupdate = $dbh->_backend->prepare(
590                 preg_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             $dbh = $this->getAuthDbh();
596             // preparate the SELECT statement
597             $this->_prefupdate = preg_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_AUTH_SEARCH') 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'] == 'dba' or empty($DBAuthParams['auth_dsn']))
646                 $this->_auth_dbi = $request->getDbh(); // use phpwiki database 
647             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
648                 $this->_auth_dbi = $request->getDbh(); // same phpwiki database 
649             else // use another external database handle. needs PHP 4.1
650                 $this->_auth_dbi = WikiDB::open($DBAuthParams);
651         }
652         return $this->_auth_dbi;
653     }
654
655     //TODO: password changing
656     //TODO: email verification
657
658     function getPreferences() {
659
660         // We don't necessarily have to read the cookie first. Since
661         // the user has a password, the prefs stored in the homepage
662         // cannot be arbitrarily altered by other Bogo users.
663         _AnonUser::getPreferences();
664
665         // database prefs
666         if ((! $this->_prefs) && $this->_prefselect) {
667             if ($this->_prefmethod == 'ADODB') {
668                 $dbh = & $this->_auth_dbi;
669                 $db_result = $dbh->_backend->Execute($this->_prefselect,$dbh->qstr($this->_userid));
670                 if (!$rs->EOF)
671                     $prefs_blob = $db_result->fields['pref_blob'];
672                 $db_result->Close();
673             }
674             else { // pear db methods
675                 $db_result = $this->_auth_dbi->_backend->execute($this->_prefselect,$this->_userid);
676                 list($prefs_blob) = $db_result->fetchRow();
677             }
678             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
679                 $this->_prefs = new UserPreferences($restored_from_db);
680                 return $this->_prefs;
681             }
682         }
683         
684         // User may have deleted cookie, retrieve from his
685         // PersonalPage if there is one.
686         if ((! $this->_prefs) && $this->_HomePagehandle) {
687             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
688                 $this->_prefs = new UserPreferences($restored_from_page);
689                 return $this->_prefs;
690             }
691         }
692         return $this->_prefs;
693     }
694
695     function setPreferences($prefs, $id_only=false) {
696         _AnonUser::setPreferences($prefs, $id_only);
697         // Encode only the _prefs array of the UserPreference object
698         $serialized = $this->_prefs->store();
699
700         // database prefs
701         if ((! $this->_prefs) && $this->_prefupdate) {
702             if ($this->_prefmethod == 'ADODB') {
703                 $dbh =& $this->_auth_dbi;
704                 $db_result = $dbh->_backend->Execute($this->_prefupdate,$dbh->qstr($serialized),$dbh->qstr($this->_userid));
705                 $db_result->Close();
706             }
707             else { // pear db methods
708                 $db_result = $this->_auth_dbi->_backend->execute($this->_prefupdate,$serialized,$this->_userid);
709             }
710         }
711         else
712             $this->_HomePagehandle->set('pref', $serialized);
713     }
714
715     function mayChangePass() {
716         return true;
717     }
718
719     //The default method is getting the password from prefs. 
720     // child methods obtain $stored_password from external auth.
721     function userExists() {
722         //if ($this->_HomePagehandle) return true;
723
724         if (USER_AUTH_POLICY === 'strict') {
725             if ($user = $this->nextClass())
726                 return $user->userExists();
727         }
728         return false;
729     }
730
731     //The default method is getting the password from prefs. 
732     // child methods obtain $stored_password from external auth.
733     function checkPass($submitted_password) {
734         $stored_password = $this->_prefs->get('passwd');
735         $result = $this->_checkPass($submitted_password, $stored_password);
736         if ($result) $this->_level = WIKIAUTH_USER;
737
738         if (!$result) {
739             if (USER_AUTH_POLICY === 'strict') {
740                 if ($user = $this->nextClass()) {
741                     if ($user = $user->userExists())
742                         return $user->checkPass($submitted_password);
743                 }
744             }
745             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
746                 if ($user = $this->nextClass())
747                     return $user->checkPass($submitted_password);
748             }
749         }
750         return $this->_level;
751     }
752
753     //TODO: remove crypt() function check from config.php:396 ??
754     function _checkPass($submitted_password, $stored_password) {
755         if(!empty($submitted_password)) {
756             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
757                 // Verify against encrypted password.
758                 if (function_exists('crypt')) {
759                     if (crypt($submitted_password, $stored_password) == $stored_password )
760                         return true; // matches encrypted password
761                     else
762                         return false;
763                 }
764                 else {
765                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
766                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and change ADMIN_PASSWD."),
767                                   E_USER_WARNING);
768                     return false;
769                 }
770             }
771             else {
772                 // Verify against cleartext password.
773                 if ($submitted_password == $stored_password)
774                     return true;
775                 else {
776                     // Check whether we forgot to enable ENCRYPTED_PASSWD
777                     if (function_exists('crypt')) {
778                         if (crypt($submitted_password, $stored_password) == $stored_password) {
779                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
780                                           E_USER_WARNING);
781                             return true;
782                         }
783                     }
784                 }
785             }
786         }
787         return false;
788     }
789 }
790
791 class _BogoLoginUser
792 extends _PassUser
793 {
794     function userExists() {
795         if (isWikiWord($this->_userid)) {
796             $this->_level = WIKIAUTH_BOGO;
797             return true;
798         } else {
799             $this->_level = WIKIAUTH_ANON;
800             return false;
801         }
802     }
803
804     function checkPass($submitted_password) {
805         // A BogoLoginUser requires PASSWORD_LENGTH_MINIMUM.
806         if ($this->userExists())
807         return $this->_level;
808     }
809 }
810
811
812 class _PersonalPagePassUser
813 extends _PassUser
814 /**
815  * This class is only to simplify the auth method dispatcher.
816  * It inherits all methods from _PassUser.
817  */
818 {
819     function dummy() {}
820 }
821
822 class _DbPassUser
823 extends _PassUser
824 /**
825  * Authenticate against a database, to be able to use shared users.
826  *   internal: no different $DbAuthParams['dsn'] defined, or
827  *   external: different $DbAuthParams['dsn']
828  * The magic is done in the symbolic SQL statements in index.php
829  *
830  * We support only the SQL and ADODB backends.
831  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
832  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
833  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
834  * Flat files for auth use is handled by the auth method "File".
835  *
836  * Preferences are handled in the parent class.
837  */
838 {
839     var $_authselect, $_authupdate;
840
841     // This can only be called from _PassUser, because the parent class 
842     // sets the auth_dbi and pref methods, before this class is initialized.
843     function _DbPassUser() {
844         if (!$this->_prefs) {
845             trigger_error(__vsprintf("Internal error: %s may only called from %s","_DbPassUser","_PassUser"),
846                           E_USER_WARNING);
847             return false;
848         }
849         $this->_authmethod = 'DB';
850         $this->_auth_dbi = $this->getAuthDbh();
851         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
852
853         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') 
854             return new _AdoDbPassUser();
855         else 
856             return new _PearDbPassUser();
857     }
858
859     function mayChangePass() {
860         return !empty($this->_authupdate);
861     }
862
863 }
864
865 class _PearDbPassUser
866 extends _DbPassUser
867 /**
868  * Pear DB methods
869  */
870 {
871     function _PearDbPassUser() {
872         global $DBAuthParams;
873         if (!$this->_prefs) {
874             trigger_error(__vsprintf("Internal error: %s may only called from %s","_PearDbPassUser","_DbPassUser"),
875                           E_USER_WARNING);
876             return false;
877         }
878         // Prepare the configured auth statements
879         if (!empty($DBAuthParams['auth_check'])) {
880             $this->_authselect = $this->_auth_dbi->_backend->prepare (
881                      preg_replace(array('"$userid"','"$password"'),array('?','?'),
882                                   $DBAuthParams['auth_check'])
883                      );
884         }
885         if (!empty($DBAuthParams['auth_update'])) {
886             $this->_authupdate = $this->_auth_dbi->_backend->prepare(
887                     preg_replace(array('"$userid"','"$password"'),array('?','?'),$DBAuthParams['auth_update'])
888                     );
889         }
890     }
891
892     function getPreferences() {
893         // override the generic slow method here for efficiency and not to 
894         // clutter the homepage metadata with prefs.
895         _AnonUser::getPreferences();
896         if ((! $this->_prefs) && $this->_prefselect) {
897             $db_result = $this->_auth_dbi->_backend->execute($this->_prefselect,$this->_userid);
898             list($prefs_blob) = $db_result->fetchRow();
899             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
900                 $this->_prefs = new UserPreferences($restored_from_db);
901                 return $this->_prefs;
902             }
903         }
904         if ((! $this->_prefs) && $this->_HomePagehandle) {
905             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
906                 $this->_prefs = new UserPreferences($restored_from_page);
907                 return $this->_prefs;
908             }
909         }
910         return $this->_prefs;
911     }
912
913     function setPreferences($prefs, $id_only=false) {
914         $serialized = $this->_prefs->store();
915         if ($this->_prefupdate) {
916             $db_result = $this->_auth_dbi->_backend->execute($this->_prefupdate,$serialized,$this->_userid);
917         } else {
918             _AnonUser::setPreferences($prefs, $id_only);
919             $this->_HomePagehandle->set('pref', $serialized);
920         }
921     }
922
923     function userExists() {
924         if (!$this->_authselect)
925             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
926                           E_USER_WARNING);
927         $dbh = &$this->_auth_dbi;
928         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
929         if ($this->_auth_crypt_method == 'crypt') {
930             $rs = $dbh->_backend->Execute($this->_authselect,$this->_userid) ;
931             if ($rs->numRows())
932                 return true;
933         }
934         else {
935             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
936                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
937                               E_USER_WARNING);
938             $this->_authcheck = preg_replace('/"$userid"/','? ',
939                                              $GLOBALS['DBAuthParams']['auth_user_exists']);
940             $rs = $dbh->_backend->Execute($this->_authcheck,
941                                           $this->_userid) ;
942             if ($rs->numRows())
943                 return true;
944         }
945         
946         if (USER_AUTH_POLICY === 'strict') {
947             if ($user = $this->nextClass()) {
948                 return $user->userExists();
949             }
950         }
951     }
952  
953     function checkPass($submitted_password) {
954         if (!$this->_authselect)
955             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
956                           E_USER_WARNING);
957
958         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
959         if ($this->_auth_crypt_method == 'crypt') {
960             $db_result = $this->_auth_dbi->_backend->execute($this->_authselect,$this->_userid);
961             list($stored_password) = $db_result->fetchRow();
962             $result = $this->_checkPass($submitted_password, $stored_password);
963         } else {
964             $db_result = $this->_auth_dbi->_backend->execute($this->_authselect,$submitted_password,$this->_userid);
965             list($okay) = $db_result->fetchRow();
966             $result = !empty($okay);
967         }
968
969         if ($result) {
970             $this->_level = WIKIAUTH_USER;
971         } else {
972             if (USER_AUTH_POLICY === 'strict') {
973                 if ($user = $this->nextClass()) {
974                     if ($user = $user->userExists())
975                         return $user->checkPass($submitted_password);
976                 }
977             }
978             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
979                 if ($user = $this->nextClass())
980                     return $user->checkPass($submitted_password);
981             }
982         }
983         return $this->_level;
984     }
985
986     function storePass($submitted_password) {
987         if (!$this->_authupdate) {
988             //CHECKME
989             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
990                           E_USER_WARNING);
991             return false;
992         }
993
994         if ($this->_auth_crypt_method == 'crypt') {
995             if (function_exists('crypt'))
996                 $submitted_password = crypt($submitted_password);
997         }
998         $db_result = $this->_auth_dbi->_backend->execute($this->_authupdate,$submitted_password,$this->_userid);
999     }
1000
1001 }
1002
1003 class _AdoDbPassUser
1004 extends _DbPassUser
1005 /**
1006  * ADODB methods
1007  */
1008 {
1009     function _AdoDbPassUser() {
1010         global $DBAuthParams;
1011         if (!$this->_prefs) {
1012             trigger_error(__vsprintf("Internal error: %s may only called from %s","_AdoDbPassUser","_DbPassUser"),
1013                           E_USER_WARNING);
1014             return false;
1015         }
1016         // Prepare the configured auth statements
1017         if (!empty($DBAuthParams['auth_check'])) {
1018             $this->_authselect = preg_replace(array('"$userid"','"$password"'),array('%s','%s'),
1019                                               $DBAuthParams['auth_check']);
1020         }
1021         if (!empty($DBAuthParams['auth_update'])) {
1022             $this->_authupdate = preg_replace(array('"$userid"','"$password"'),array('%s','%s'),
1023                                               $DBAuthParams['auth_update']);
1024         }
1025     }
1026
1027     function getPreferences() {
1028         // override the generic slow method here for efficiency
1029         _AnonUser::getPreferences();
1030         if ((! $this->_prefs) && $this->_prefselect) {
1031             $dbh = & $this->_auth_dbi;
1032             $rs = $dbh->_backend->Execute($this->_prefselect,$dbh->qstr($this->_userid));
1033             if ($rs->EOF) {
1034                 $rs->Close();
1035             } else {
1036                 $prefs_blob = $rs->fields['pref_blob'];
1037                 $rs->Close();
1038                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1039                     $this->_prefs = new UserPreferences($restored_from_db);
1040                     return $this->_prefs;
1041                 }
1042             }
1043         }
1044         if ((! $this->_prefs) && $this->_HomePagehandle) {
1045             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1046                 $this->_prefs = new UserPreferences($restored_from_page);
1047                 return $this->_prefs;
1048             }
1049         }
1050         return $this->_prefs;
1051     }
1052
1053     function setPreferences($prefs, $id_only=false) {
1054         $serialized = $this->_prefs->store();
1055         if ($this->_prefupdate) {
1056             $dbh = & $this->_auth_dbi;
1057             $db_result = $dbh->_backend->Execute($this->_prefupdate,$dbh->qstr($serialized),$dbh->qstr($this->_userid));
1058             $db_result->Close();
1059         } else {
1060             _AnonUser::setPreferences($prefs, $id_only);
1061             $this->_HomePagehandle->set('pref', $serialized);
1062         }
1063     }
1064  
1065     function userExists() {
1066         if (!$this->_authselect)
1067             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1068                           E_USER_WARNING);
1069         $dbh = &$this->_auth_dbi;
1070         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1071         if ($this->_auth_crypt_method == 'crypt') {
1072             $rs = $dbh->_backend->Execute($this->_authselect,$dbh->qstr($this->_userid));
1073             if (!$rs->EOF) {
1074                 $rs->Close();
1075                 return true;
1076             } else {
1077                 $rs->Close();
1078             }
1079         }
1080         else {
1081             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1082                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1083                               E_USER_WARNING);
1084             $this->_authcheck = preg_replace('/"$userid"/','%s',
1085                                              $GLOBALS['DBAuthParams']['auth_user_exists']);
1086             $rs = $dbh->_backend->Execute($this->_authcheck,
1087                                           $dbh->qstr($this->_userid));
1088             if (!$rs->EOF) {
1089                 $rs->Close();
1090                 return true;
1091             } else {
1092                 $rs->Close();
1093             }
1094         }
1095         
1096         if (USER_AUTH_POLICY === 'strict') {
1097             if ($user = $this->nextClass())
1098                 return $user->userExists();
1099         }
1100         return false;
1101     }
1102
1103     function checkPass($submitted_password) {
1104         if (!$this->_authselect)
1105             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1106                           E_USER_WARNING);
1107         $dbh = &$this->_auth_dbi;
1108         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1109         if ($this->_auth_crypt_method == 'crypt') {
1110             $rs = $dbh->_backend->Execute($this->_authselect,$dbh->qstr($this->_userid));
1111             if (!$rs->EOF) {
1112                 $stored_password = $rs->fields['password'];
1113                 $rs->Close();
1114                 $result = $this->_checkPass($submitted_password, $stored_password);
1115             } else {
1116                 $rs->Close();
1117                 $result = false;
1118             }
1119         }
1120         else {
1121             $rs = $dbh->_backend->Execute($this->_authselect,
1122                                           $dbh->qstr($submitted_password),
1123                                           $dbh->qstr($this->_userid));
1124             $okay = $rs->fields['ok'];
1125             $rs->Close();
1126             $result = !empty($okay);
1127         }
1128
1129         if ($result) { 
1130             $this->_level = WIKIAUTH_USER;
1131         } else {
1132             if (USER_AUTH_POLICY === 'strict') {
1133                 if ($user = $this->nextClass()) {
1134                     if ($user = $user->userExists())
1135                         return $user->checkPass($submitted_password);
1136                 }
1137             }
1138             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1139                 if ($user = $this->nextClass())
1140                     return $user->checkPass($submitted_password);
1141             }
1142         }
1143         return $this->_level;
1144     }
1145
1146     function storePass($submitted_password) {
1147         if (!$this->_authupdate) {
1148             //CHECKME
1149             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1150                           E_USER_WARNING);
1151             return false;
1152         }
1153
1154         if ($this->_auth_crypt_method == 'crypt') {
1155             if (function_exists('crypt'))
1156                 $submitted_password = crypt($submitted_password);
1157         }
1158         $dbh = &$this->_auth_dbi;
1159         $rs = $dbh->_backend->Execute($this->_authupdate,
1160                                       $dbh->qstr($submitted_password),
1161                                       $dbh->qstr($this->_userid));
1162         $rs->Close();
1163     }
1164
1165 }
1166
1167 class _LDAPPassUser
1168 extends _PassUser
1169 /**
1170  * Define the vars LDAP_HOST and LDAP_AUTH_SEARCH in index.php
1171  *
1172  * Preferences are handled in _PassUser
1173  */
1174 {
1175     function checkPass($submitted_password) {
1176         $this->_authmethod = 'LDAP';
1177         $userid = $this->_userid;
1178         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1179             $r = @ldap_bind($ldap); // this is an anonymous bind
1180             $st_search = "uid=$userid";
1181             // Need to set the right root search information. see ../index.php
1182             $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
1183                               "$st_search");
1184             $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1185             for ($i = 0; $i < $info["count"]; $i++) {
1186                 $dn = $info[$i]["dn"];
1187                 // The password is still plain text.
1188                 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
1189                     // ldap_bind will return TRUE if everything matches
1190                     ldap_close($ldap);
1191                     $this->_level = WIKIAUTH_USER;
1192                     return $this->_level;
1193                 }
1194             }
1195         } else {
1196             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1197         }
1198
1199         if (USER_AUTH_POLICY === 'strict') {
1200             if ($user = $this->nextClass()) {
1201                 if ($user = $user->userExists())
1202                     return $user->checkPass($submitted_password);
1203             }
1204         }
1205         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1206             if ($user = $this->nextClass())
1207                 return $user->checkPass($submitted_password);
1208         }
1209         return false;
1210     }
1211
1212     function userExists() {
1213         $userid = $this->_userid;
1214         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1215             $r = @ldap_bind($ldap); // this is an anonymous bind
1216             $st_search = "uid=$userid";
1217             // Need to set the right root search information. see ../index.php
1218             $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
1219                               "$st_search");
1220             $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1221             if ($info["count"]) {
1222                 ldap_close($ldap);
1223                 return true;
1224             }
1225         } else {
1226             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1227         }
1228
1229         if (USER_AUTH_POLICY === 'strict') {
1230             if ($user = $this->nextClass())
1231                 return $user->userExists();
1232         }
1233         return false;
1234     }
1235
1236     function mayChangePass() {
1237         return false;
1238     }
1239
1240 }
1241
1242 class _IMAPPassUser
1243 extends _PassUser
1244 /**
1245  * Define the var IMAP_HOST in index.php
1246  *
1247  * Preferences are handled in _PassUser
1248  */
1249 {
1250     function checkPass($submitted_password) {
1251         $userid = $this->_userid;
1252         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1253                             $userid, $submitted_password, OP_HALFOPEN );
1254         if ($mbox) {
1255             imap_close($mbox);
1256             $this->_authmethod = 'IMAP';
1257             $this->_level = WIKIAUTH_USER;
1258             return $this->_level;
1259         } else {
1260             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1261         }
1262         if (USER_AUTH_POLICY === 'strict') {
1263             if ($user = $this->nextClass()) {
1264                 if ($user = $user->userExists())
1265                     return $user->checkPass($submitted_password);
1266             }
1267         }
1268         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1269             if ($user = $this->nextClass())
1270                 return $user->checkPass($submitted_password);
1271         }
1272         return false;
1273     }
1274
1275     //CHECKME: this will not be okay for the auth policy strict
1276     function userExists() {
1277         if (checkPass($this->_prefs->get('passwd')))
1278             return true;
1279             
1280         if (USER_AUTH_POLICY === 'strict') {
1281             if ($user = $this->nextClass())
1282                 return $user->userExists();
1283         }
1284     }
1285
1286     function mayChangePass() {
1287         return false;
1288     }
1289
1290 }
1291
1292 class _FilePassUser
1293 extends _PassUser
1294 /**
1295  * Check users defined in a .htaccess style file
1296  * username:crypt\n...
1297  *
1298  * Preferences are handled in _PassUser
1299  */
1300 {
1301     var $_file, $_may_change;
1302
1303     // This can only be called from _PassUser, because the parent class 
1304     // sets the pref methods, before this class is initialized.
1305     function _FilePassUser($file = '') {
1306         global $DBAuthParams;
1307         if (!$this->_prefs) {
1308             trigger_error(__vsprintf("Internal error: %s may only called from %s","_FilePassUser","_PassUser"),
1309                           E_USER_WARNING);
1310             return false;
1311         }
1312
1313         // read the .htaccess style file. We use our own copy of the standard pear class.
1314         require 'lib/pear/File_Passwd.php';
1315         // if passwords may be changed we have to lock them:
1316         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1317         if (empty($file) and defined('AUTH_USER_FILE'))
1318             $this->_file = AUTH_USER_FILE;
1319         elseif (!empty($file))
1320             $this->_file = File_Passwd($file, !empty($this->_may_change));
1321         else
1322             return false;
1323         return $this;
1324     }
1325  
1326     function mayChangePass() {
1327         return $this->_may_change;
1328     }
1329
1330     function userExists() {
1331         if (isset($this->_file->users[$this->_userid]))
1332             return true;
1333             
1334         if (USER_AUTH_POLICY === 'strict') {
1335             if ($user = $this->nextClass())
1336                 return $user->userExists();
1337         }
1338     }
1339
1340     function checkPass($submitted_password) {
1341         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1342             $this->_authmethod = 'File';
1343             $this->_level = WIKIAUTH_USER;
1344             return $this->_level;
1345         }
1346         
1347         if (USER_AUTH_POLICY === 'strict') {
1348             if ($user = $this->nextClass()) {
1349                 if ($user = $user->userExists())
1350                     return $user->checkPass($submitted_password);
1351             }
1352         }
1353         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1354             if ($user = $this->nextClass())
1355                 return $user->checkPass($submitted_password);
1356         }
1357         return false;
1358     }
1359
1360     function storePass($submitted_password) {
1361         if ($this->_may_change)
1362             return $this->_file->modUser($this->_userid,$submitted_password);
1363         else 
1364             return false;
1365     }
1366
1367 }
1368
1369 /**
1370  * Insert more auth classes here...
1371  *
1372  */
1373
1374
1375 /**
1376  * For security, this class should not be extended. Instead, extend
1377  * from _PassUser (think of this as unix "root").
1378  */
1379 class _AdminUser
1380 extends _PassUser
1381 {
1382     //var $_level = WIKIAUTH_ADMIN;
1383
1384     function checkPass($submitted_password) {
1385         $stored_password = ADMIN_PASSWD;
1386         if ($this->_checkPass($submitted_password, $stored_password)) {
1387             $this->_level = WIKIAUTH_ADMIN;
1388             return $this->_level;
1389         } else {
1390             $this->_level = WIKIAUTH_ANON;
1391             return false;
1392         }
1393     }
1394
1395 }
1396
1397 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1398 /**
1399  * Various data classes for the preference types, 
1400  * to support get, set, sanify (range checking, ...)
1401  * update() will do the neccessary side-effects if a 
1402  * setting gets changed (theme, language, ...)
1403 */
1404
1405 class _UserPreference
1406 {
1407     var $default_value;
1408
1409     function _UserPreference ($default_value) {
1410         $this->default_value = $default_value;
1411     }
1412
1413     function sanify ($value) {
1414         return (string)$value;
1415     }
1416
1417     function get ($name) {
1418         if (isset($this->$name))
1419             return $this->{$name};
1420         else 
1421             return $this->default_value;
1422     }
1423
1424     function getraw ($name) {
1425         if (!empty($this->{$name}))
1426             return $this->{$name};
1427     }
1428
1429     // stores the value as $this->$name, and not as $this->value (clever?)
1430     function set ($name, $value) {
1431         if ($value != $this->default_value)
1432             $this->$name = $value;
1433         else 
1434             unset($this->$name);
1435     }
1436
1437     // default: no side-effects 
1438     function update ($value) {
1439     }
1440 }
1441
1442 class _UserPreference_numeric
1443 extends _UserPreference
1444 {
1445     function _UserPreference_numeric ($default, $minval = false,
1446                                       $maxval = false) {
1447         $this->_UserPreference((double)$default);
1448         $this->_minval = (double)$minval;
1449         $this->_maxval = (double)$maxval;
1450     }
1451
1452     function sanify ($value) {
1453         $value = (double)$value;
1454         if ($this->_minval !== false && $value < $this->_minval)
1455             $value = $this->_minval;
1456         if ($this->_maxval !== false && $value > $this->_maxval)
1457             $value = $this->_maxval;
1458         return $value;
1459     }
1460 }
1461
1462 class _UserPreference_int
1463 extends _UserPreference_numeric
1464 {
1465     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1466         $this->_UserPreference_numeric((int)$default, (int)$minval,
1467                                        (int)$maxval);
1468     }
1469
1470     function sanify ($value) {
1471         return (int)parent::sanify((int)$value);
1472     }
1473 }
1474
1475 class _UserPreference_bool
1476 extends _UserPreference
1477 {
1478     function _UserPreference_bool ($default = false) {
1479         $this->_UserPreference((bool)$default);
1480     }
1481
1482     function sanify ($value) {
1483         if (is_array($value)) {
1484             /* This allows for constructs like:
1485              *
1486              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1487              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1488              *
1489              * (If the checkbox is not checked, only the hidden input
1490              * gets sent. If the checkbox is sent, both inputs get
1491              * sent.)
1492              */
1493             foreach ($value as $val) {
1494                 if ($val)
1495                     return true;
1496             }
1497             return false;
1498         }
1499         return (bool) $value;
1500     }
1501 }
1502
1503 class _UserPreference_language
1504 extends _UserPreference
1505 {
1506     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1507         $this->_UserPreference($default);
1508     }
1509
1510     // FIXME: check for valid locale
1511     function sanify ($value) {
1512         // Revert to DEFAULT_LANGUAGE if user does not specify
1513         // language in UserPreferences or chooses <system language>.
1514         if ($value == '' or empty($value))
1515             $value = DEFAULT_LANGUAGE;
1516
1517         return (string) $value;
1518     }
1519 }
1520
1521 class _UserPreference_theme
1522 extends _UserPreference
1523 {
1524     function _UserPreference_theme ($default = THEME) {
1525         $this->_UserPreference($default);
1526     }
1527
1528     function sanify ($value) {
1529         if (file_exists($this->_themefile($value)))
1530             return $value;
1531         return $this->default_value;
1532     }
1533
1534     function update ($newvalue) {
1535         global $Theme;
1536         include_once($this->_themefile($newvalue));
1537         if (empty($Theme))
1538             include_once($this->_themefile(THEME));
1539     }
1540
1541     function _themefile ($theme) {
1542         return "themes/$theme/themeinfo.php";
1543     }
1544 }
1545
1546 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1547
1548 /**
1549  * UserPreferences
1550  * 
1551  * This object holds the $request->_prefs subobjects.
1552  * A simple packed array of non-default values get's stored as cookie,
1553  * homepage, and database, which are converted to the array of 
1554  * ->_prefs objects.
1555  * We don't store the objects, because otherwise we will
1556  * not be able to upgrade any subobject. And it's a waste of space also.
1557  */
1558 class UserPreferences
1559 {
1560     function UserPreferences ($saved_prefs = false) {
1561         // userid stored too, to ensure the prefs are being loaded for
1562         // the correct (currently signing in) userid if stored in a
1563         // cookie.
1564         $this->_prefs
1565             = array(
1566                     'userid'        => new _UserPreference(''),
1567                     'passwd'        => new _UserPreference(''),
1568                     'autologin'     => new _UserPreference_bool(),
1569                     'email'         => new _UserPreference(''),
1570                     'emailVerified' => new _UserPreference_bool(),
1571                     'notifyPages'   => new _UserPreference(''),
1572                     'theme'         => new _UserPreference_theme(THEME),
1573                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
1574                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1575                                                                EDITWIDTH_MIN_COLS,
1576                                                                EDITWIDTH_MAX_COLS),
1577                     'noLinkIcons'   => new _UserPreference_bool(),
1578                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1579                                                                EDITHEIGHT_MIN_ROWS,
1580                                                                EDITHEIGHT_DEFAULT_ROWS),
1581                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1582                                                                    TIMEOFFSET_MIN_HOURS,
1583                                                                    TIMEOFFSET_MAX_HOURS),
1584                     'relativeDates' => new _UserPreference_bool()
1585                     );
1586
1587         if (is_array($saved_prefs)) {
1588             foreach ($saved_prefs as $name => $value)
1589                 $this->set($name, $value);
1590         }
1591     }
1592
1593     function _getPref ($name) {
1594         if (!isset($this->_prefs[$name])) {
1595             if ($name == 'passwd2') return false;
1596             trigger_error("$name: unknown preference", E_USER_NOTICE);
1597             return false;
1598         }
1599         return $this->_prefs[$name];
1600     }
1601     
1602     // get the value or default_value of the subobject
1603     function get ($name) {
1604         if ($_pref = $this->_getPref($name))
1605           return $_pref->get($name);
1606         else 
1607           return false;  
1608         /*      
1609         if (is_object($this->_prefs[$name]))
1610             return $this->_prefs[$name]->get($name);
1611         elseif (($value = $this->_getPref($name)) === false)
1612             return false;
1613         elseif (!isset($value))
1614             return $this->_prefs[$name]->default_value;
1615         else return $value;
1616         */
1617     }
1618
1619     // check and set the new value in the subobject
1620     function set ($name, $value) {
1621         $pref = $this->_getPref($name);
1622         if ($pref === false)
1623             return false;
1624
1625         /* do it here or outside? */
1626         if ($name == 'passwd' and 
1627             defined('PASSWORD_LENGTH_MINIMUM') and 
1628             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1629             //TODO: How to notify the user?
1630             return false;
1631         }
1632
1633         $newvalue = $pref->sanify($value);
1634         $oldvalue = $pref->get($name);
1635
1636         // update on changes
1637         if ($newvalue != $oldvalue)
1638             $pref->update($newvalue);
1639         return true;
1640
1641         // don't set default values to save space (in cookies, db and
1642         // sesssion)
1643         /*
1644         if ($value == $pref->default_value)
1645             unset($this->_prefs[$name]);
1646         else
1647             $this->_prefs[$name] = $pref;
1648         */
1649     }
1650
1651     // array of objects => array of values
1652     function store() {
1653         $prefs = array();
1654         foreach ($this->_prefs as $name => $object) {
1655             if ($value = $object->getraw($name))
1656                 $prefs[] = array($name => $value);
1657         }
1658         return $this->pack($prefs);
1659     }
1660
1661     // packed string or array of values => array of values
1662     function retrieve($packed) {
1663         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1664             $packed = unserialize($packed);
1665         if (!is_array($packed)) return false;
1666         $prefs = array();
1667         foreach ($packed as $name => $packed_pref) {
1668             if (substr($packed_pref, 0, 2) == "O:") {
1669                 //legacy: check if it's an old array of objects
1670                 // Looks like a serialized object. 
1671                 // This might fail if the object definition does not exist anymore.
1672                 // object with ->$name and ->default_value vars.
1673                 $pref = unserialize($packed_pref);
1674                 $prefs[$name] = $pref->get($name);
1675             } else {
1676                 $prefs[$name] = unserialize($packed_pref);
1677             }
1678         }
1679         return $prefs;
1680     }
1681     
1682     // array of objects
1683     function getAll() {
1684         return $this->_prefs;
1685     }
1686
1687     function pack($nonpacked) {
1688         return serialize($nonpacked);
1689     }
1690
1691     function unpack($packed) {
1692         if (!$packed)
1693             return false;
1694         if (substr($packed, 0, 2) == "O:") {
1695             // Looks like a serialized object
1696             return unserialize($packed);
1697         }
1698         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1699         //E_USER_WARNING);
1700         return false;
1701     }
1702
1703     function hash () {
1704         return hash($this->_prefs);
1705     }
1706 }
1707
1708
1709 // $Log: not supported by cvs2svn $
1710 // Revision 1.6  2004/01/26 09:17:49  rurban
1711 // * changed stored pref representation as before.
1712 //   the array of objects is 1) bigger and 2)
1713 //   less portable. If we would import packed pref
1714 //   objects and the object definition was changed, PHP would fail.
1715 //   This doesn't happen with an simple array of non-default values.
1716 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1717 //   understands the interim format of array of objects also.
1718 // * simplified $prefs->get() and fixed $prefs->set()
1719 // * added $user->_userid and class '_WikiUser' portability functions
1720 // * fixed $user object ->_level upgrading, mostly using sessions.
1721 //   this fixes yesterdays problems with loosing authorization level.
1722 // * fixed WikiUserNew::checkPass to return the _level
1723 // * fixed WikiUserNew::isSignedIn
1724 // * added explodePageList to class PageList, support sortby arg
1725 // * fixed UserPreferences for WikiUserNew
1726 // * fixed WikiPlugin for empty defaults array
1727 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1728 //   removed sort arg, support sortby arg
1729 //
1730 // Revision 1.5  2004/01/25 03:05:00  rurban
1731 // First working version, but has some problems with the current main loop.
1732 // Implemented new auth method dispatcher and policies, all the external
1733 // _PassUser classes (also for ADODB and Pear DB).
1734 // The two global funcs UserExists() and CheckPass() are probably not needed,
1735 // since the auth loop is done recursively inside the class code, upgrading
1736 // the user class within itself.
1737 // Note: When a higher user class is returned, this doesn't mean that the user
1738 // is authorized, $user->_level is still low, and only upgraded on successful
1739 // login.
1740 //
1741 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
1742 // Code Housecleaning: fixed syntax errors. (php -l *.php)
1743 //
1744 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
1745 // Finished off logic for determining user class, including
1746 // PassUser. Removed ability of BogoUser to save prefs into a page.
1747 //
1748 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
1749 // Added admin user, password user, and preference classes. Added
1750 // password checking functions for users and the admin. (Now the easy
1751 // parts are nearly done).
1752 //
1753 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
1754 // Complete rewrite of WikiUser.php.
1755 //
1756 // This should make it easier to hook in user permission groups etc. some
1757 // time in the future. Most importantly, to finally get UserPreferences
1758 // fully working properly for all classes of users: AnonUser, BogoUser,
1759 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
1760 // want a cookie or not, and to bring back optional AutoLogin with the
1761 // UserName stored in a cookie--something that was lost after PhpWiki had
1762 // dropped the default http auth login method.
1763 //
1764 // Added WikiUser classes which will (almost) work together with existing
1765 // UserPreferences class. Other parts of PhpWiki need to be updated yet
1766 // before this code can be hooked up.
1767 //
1768
1769 // Local Variables:
1770 // mode: php
1771 // tab-width: 8
1772 // c-basic-offset: 4
1773 // c-hanging-comment-ender-p: nil
1774 // indent-tabs-mode: nil
1775 // End:
1776 ?>