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