]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
generally more PHPDOC docs
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.24 2004-02-28 21:14:08 rurban Exp $');
3 /* Copyright (C) 2004 $ThePhpWikiProgrammingTeam
4  */
5 /**
6  * This is a complete OOP rewrite of the old WikiUser code with various
7  * configurable external authentification methods.
8  *
9  * There's only one entry point, the function WikiUser which returns 
10  * a WikiUser object, which contains the user's preferences.
11  * This object might get upgraded during the login step and later also.
12  * There exist three preferences storage methods: cookie, homepage and db,
13  * and multiple password checking methods.
14  * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if 
15  * ALLOW_USER_PASSWORDS is defined.
16  *
17  * Each user object must define the two preferences methods 
18  *  getPreferences(), setPreferences(), 
19  * and the following 1-4 auth methods
20  *  checkPass()  must be defined by all classes,
21  *  userExists() only if USER_AUTH_POLICY'=='strict' 
22  *  mayChangePass()  only if the password is storable.
23  *  storePass()  only if the password is storable.
24  *
25  * WikiUser() given no name, returns an _AnonUser (anonymous user)
26  * object, who may or may not have a cookie. 
27  * However, if the there's a cookie with the userid or a session, 
28  * the user is upgraded to the matching user object.
29  * Given a user name, returns a _BogoUser object, who may or may not 
30  * have a cookie and/or PersonalPage, one of the various _PassUser objects 
31  * or an _AdminUser object.
32  * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might 
33  * have stored a password or not. If so, his account is secure, if not
34  * anybody can use it, because the username is visible e.g. in RecentChanges.
35  *
36  * Takes care of passwords, all preference loading/storing in the
37  * user's page and any cookies. lib/main.php will query the user object to
38  * verify the password as appropriate.
39  *
40  * @author: Reini Urban (the tricky parts), 
41  *          Carsten Klapp (started rolling the ball)
42  *
43  * Notes by 2004-01-25 03:43:45 rurban
44  * Test it by defining ENABLE_USER_NEW in index.php
45  * 1) Now a ForbiddenUser is returned instead of false.
46  * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, 
47  *    but may browse. Now with ALLOW_ANON_USER = false he may not browse, 
48  *    which is needed to disable browse PagePermissions.
49  *    I added now ALLOW_ANON_EDIT = true to makes things clear. 
50  *    (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
51  * 2004-02-27 rurban:
52  * 3) Removed pear prepare. Performance hog, and using integers as 
53  *    handler doesn't help. Do simple sprintf as with adodb. And a prepare
54  *    in the object init is no advantage, because in the init loop a lot of 
55  *    objects are tried, but not used.
56  * 4) Already gotten prefs are passed to the next object to avoid 
57  *    duplicate getPreferences() calls.
58  */
59
60 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
61 define('WIKIAUTH_ANON', 0);       // Not signed in.
62 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
63 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
64 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
65
66 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
67 if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
68
69 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
70 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
71 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
72
73 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
74 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
75 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
76
77 define('TIMEOFFSET_MIN_HOURS', -26);
78 define('TIMEOFFSET_MAX_HOURS',  26);
79 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
80
81 /**
82  * There are be the following constants in index.php to 
83  * establish login parameters:
84  *
85  * ALLOW_ANON_USER         default true
86  * ALLOW_ANON_EDIT         default true
87  * ALLOW_BOGO_LOGIN        default true
88  * ALLOW_USER_PASSWORDS    default true
89  * PASSWORD_LENGTH_MINIMUM default 6 ?
90  *
91  * To require user passwords for editing:
92  * ALLOW_ANON_USER  = true
93  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
94  * ALLOW_BOGO_LOGIN = false
95  * ALLOW_USER_PASSWORDS = true
96  *
97  * To establish a COMPLETELY private wiki, such as an internal
98  * corporate one:
99  * ALLOW_ANON_USER = false
100  * (and probably require user passwords as described above). In this
101  * case the user will be prompted to login immediately upon accessing
102  * any page.
103  *
104  * There are other possible combinations, but the typical wiki (such
105  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four 
106  * enabled.
107  *
108  */
109
110 // The last object in the row is the bad guy...
111 if (!is_array($USER_AUTH_ORDER))
112     $USER_AUTH_ORDER = array("Forbidden");
113 else
114     $USER_AUTH_ORDER[] = "Forbidden";
115
116 // Local convenience functions.
117 function _isAnonUserAllowed() {
118     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
119 }
120 function _isBogoUserAllowed() {
121     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
122 }
123 function _isUserPasswordsAllowed() {
124     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
125 }
126
127 // Possibly upgrade userobject functions.
128 function _determineAdminUserOrOtherUser($UserName) {
129     // Sanity check. User name is a condition of the definition of the
130     // _AdminUser, _BogoUser and _passuser.
131     if (!$UserName)
132         return $GLOBALS['ForbiddenUser'];
133
134     if ($UserName == ADMIN_USER)
135         return new _AdminUser($UserName);
136     else
137         return _determineBogoUserOrPassUser($UserName);
138 }
139
140 function _determineBogoUserOrPassUser($UserName) {
141     global $ForbiddenUser;
142
143     // Sanity check. User name is a condition of the definition of
144     // _BogoUser and _PassUser.
145     if (!$UserName)
146         return $ForbiddenUser;
147
148     // Check for password and possibly upgrade user object.
149     // $_BogoUser = new _BogoUser($UserName);
150     if (_isBogoUserAllowed()) {
151         $_BogoUser = new _BogoLoginPassUser($UserName);
152         if ($_BogoUser->userExists())
153             return $_BogoUser;
154     }
155     if (_isUserPasswordsAllowed()) {
156         // PassUsers override BogoUsers if a password is stored
157         if (isset($_BogoUser) and $_BogoUser->_prefs->get('passwd'))
158             return new _PassUser($UserName,$_BogoUser->_prefs);
159         else { 
160             $_PassUser = new _PassUser($UserName,isset($_BogoUser) ? $_BogoUser->_prefs : false);
161             if ($_PassUser->userExists())
162                 return $_PassUser;
163         }
164     }
165     // No Bogo- or PassUser exists, or
166     // passwords are not allowed, and bogo is disallowed too.
167     // (Only the admin can sign in).
168     return $ForbiddenUser;
169 }
170
171 /**
172  * Primary WikiUser function, called by lib/main.php.
173  * 
174  * This determines the user's type and returns an appropriate user
175  * object. lib/main.php then querys the resultant object for password
176  * validity as necessary.
177  *
178  * If an _AnonUser object is returned, the user may only browse pages
179  * (and save prefs in a cookie).
180  *
181  * To disable access but provide prefs the global $ForbiddenUser class 
182  * is returned. (was previously false)
183  * 
184  */
185 function WikiUser ($UserName = '') {
186     global $ForbiddenUser;
187
188     //Maybe: Check sessionvar for username & save username into
189     //sessionvar (may be more appropriate to do this in lib/main.php).
190     if ($UserName) {
191         $ForbiddenUser = new _ForbiddenUser($UserName);
192         // Found a user name.
193         return _determineAdminUserOrOtherUser($UserName);
194     }
195     elseif (!empty($_SESSION['userid'])) {
196         // Found a user name.
197         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
198         return _determineAdminUserOrOtherUser($_SESSION['userid']);
199     }
200     else {
201         // Check for autologin pref in cookie and possibly upgrade
202         // user object to another type.
203         $_AnonUser = new _AnonUser();
204         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
205             // Found a user name.
206             $ForbiddenUser = new _ForbiddenUser($UserName);
207             return _determineAdminUserOrOtherUser($UserName);
208         }
209         else {
210             $ForbiddenUser = new _ForbiddenUser();
211             if (_isAnonUserAllowed())
212                 return $_AnonUser;
213             return $ForbiddenUser; // User must sign in to browse pages.
214         }
215         return $ForbiddenUser;     // User must sign in with a password.
216     }
217     /*
218     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
219                   . "Unexpectedly, an appropriate user class could not be determined.");
220     return $ForbiddenUser; // Failsafe.
221     */
222 }
223
224 /**
225  * WikiUser.php use the name 'WikiUser'
226  */
227 function WikiUserClassname() {
228     return '_WikiUser';
229 }
230
231
232 /**
233  * Upgrade olduser by copying properties from user to olduser.
234  * We are not sure yet, for which php's a simple $this = $user works reliably,
235  * That's why try it the hard way.
236  */
237 function UpgradeUser ($olduser, $user) {
238     if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
239         // populate the upgraded class $olduser with the values from the new user object
240         foreach (get_object_vars($user) as $k => $v) {
241             if (!empty($v)) $olduser->$k = $v;  
242         }
243         $GLOBALS['request']->_user = $olduser;
244         return $olduser;
245     } else {
246         return false;
247     }
248 }
249
250 /**
251  * Probably not needed, since we use the various user objects methos so far.
252  * Anyway, here it is, looping through all available objects.
253  */
254 function UserExists ($UserName) {
255     global $request;
256     if (!($user = $request->getUser()))
257         $user = WikiUser($UserName);
258     if (!$user) 
259         return false;
260     if ($user->userExists($UserName)) {
261         $request->_user = $user;
262         return true;
263     }
264     if (isa($user,'_BogoUser'))
265         $user = new _PassUser($UserName,$user->_prefs);
266     while ($user = $user->nextClass()) {
267         return $user->userExists($UserName);
268         $this = $user; // does this work on all PHP version?
269     }
270     $request->_user = $GLOBALS['ForbiddenUser'];
271     return false;
272 }
273
274 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
275
276 /** 
277  * Base WikiUser class.
278  */
279 class _WikiUser
280 {
281     var $_userid = '';
282
283     var $_level = WIKIAUTH_FORBIDDEN;
284     var $_prefs = false;
285     var $_HomePagehandle = false;
286
287     // constructor
288     function _WikiUser($UserName='', $prefs=false) {
289
290         $this->_userid = $UserName;
291         if ($UserName) {
292             $this->hasHomePage();
293         }
294         if (!$this->_prefs) {
295             if ($prefs) $this->_prefs = $prefs;
296             else $this->getPreferences();
297         }
298     }
299
300     function UserName() {
301         if (!empty($this->_userid))
302             return $this->_userid;
303     }
304
305     function getPreferences() {
306         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
307                       . "New subclasses of _WikiUser must override this function.");
308         return false;
309     }
310
311     function setPreferences($prefs, $id_only) {
312         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
313                       . "New subclasses of _WikiUser must override this function.");
314         return false;
315     }
316
317     function userExists() {
318         return $this->hasHomePage();
319     }
320
321     function checkPass($submitted_password) {
322         // By definition, an undefined user class cannot sign in.
323         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
324                       . "New subclasses of _WikiUser must override this function.");
325         return false;
326     }
327
328     // returns page_handle to user's home page or false if none
329     function hasHomePage() {
330         if ($this->_userid) {
331             if ($this->_HomePagehandle) {
332                 return $this->_HomePagehandle->exists();
333             }
334             else {
335                 // check db again (maybe someone else created it since
336                 // we logged in.)
337                 global $request;
338                 $this->_HomePagehandle = $request->getPage($this->_userid);
339                 return $this->_HomePagehandle->exists();
340             }
341         }
342         // nope
343         return false;
344     }
345
346     // innocent helper: case-insensitive position in _auth_methods
347     function array_position ($string, $array) {
348         $string = strtolower($string);
349         for ($found = 0; $found < count($array); $found++) {
350             if (strtolower($array[$found]) == $string)
351                 return $found;
352         }
353         return false;
354     }
355
356     function nextAuthMethodIndex() {
357         if (empty($this->_auth_methods)) 
358             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
359         if (empty($this->_current_index)) {
360             if (get_class($this) != '_passuser') {
361                 $this->_current_method = substr(get_class($this),1,-8);
362                 $this->_current_index = $this->array_position($this->_current_method,
363                                                               $this->_auth_methods);
364             } else {
365                 $this->_current_index = -1;
366             }
367         }
368         $this->_current_index++;
369         if ($this->_current_index >= count($this->_auth_methods))
370             return false;
371         $this->_current_method = $this->_auth_methods[$this->_current_index];
372         return $this->_current_index;
373     }
374
375     function AuthMethod($index = false) {
376         return $this->_auth_methods[ $index === false ? 0 : $index];
377     }
378
379     // upgrade the user object
380     function nextClass() {
381         if (($next = $this->nextAuthMethodIndex()) !== false) {
382             $method = $this->AuthMethod($next);
383             $class = "_".$method."PassUser";
384             if ($user = new $class($this->_userid)) {
385                 // prevent from endless recursion.
386                 //$user->_current_method = $this->_current_method;
387                 //$user->_current_index = $this->_current_index;
388                 $user = UpgradeUser($user, $this);
389             }
390             return $user;
391         }
392     }
393
394     //Fixme: for _HttpAuthPassUser
395     function PrintLoginForm (&$request, $args, $fail_message = false,
396                              $seperate_page = true) {
397         include_once('lib/Template.php');
398         // Call update_locale in case the system's default language is not 'en'.
399         // (We have no user pref for lang at this point yet, no one is logged in.)
400         update_locale(DEFAULT_LANGUAGE);
401         $userid = $this->_userid;
402         $require_level = 0;
403         extract($args); // fixme
404
405         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
406
407         $pagename = $request->getArg('pagename');
408         $nocache = 1;
409         $login = new Template('login', $request,
410                               compact('pagename', 'userid', 'require_level',
411                                       'fail_message', 'pass_required', 'nocache'));
412         if ($seperate_page) {
413             $top = new Template('html', $request,
414                                 array('TITLE' => _("Sign In")));
415             return $top->printExpansion($login);
416         } else {
417             return $login;
418         }
419     }
420
421     /** Signed in but probably not password checked.
422      */
423     function isSignedIn() {
424         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
425     }
426
427     /** This is password checked for sure.
428      */
429     function isAuthenticated () {
430         //return isa($this,'_PassUser');
431         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
432         return $this->_level >= WIKIAUTH_BOGO; // hmm.
433     }
434
435     function isAdmin () {
436         return $this->_level == WIKIAUTH_ADMIN;
437     }
438
439     /** Name or IP for a signed user. UserName could come from a cookie e.g.
440      */
441     function getId () {
442         return ( $this->UserName()
443                  ? $this->UserName()
444                  : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
445     }
446
447     /** Name for an authenticated user. No IP here.
448      */
449     function getAuthenticatedId() {
450         return ( $this->isAuthenticated()
451                  ? $this->_userid
452                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
453     }
454
455     function hasAuthority ($require_level) {
456         return $this->_level >= $require_level;
457     }
458
459     /**
460      * Called on an auth_args POST request, such as login, logout or signin.
461      */
462     function AuthCheck ($postargs) {
463         // Normalize args, and extract.
464         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
465                       'cancel');
466         foreach ($keys as $key)
467             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
468         extract($args);
469         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
470
471         if ($logout) { // Log out
472             $GLOBALS['request']->_user = new _AnonUser();
473             return $GLOBALS['request']->_user; 
474         } elseif ($cancel)
475             return false;        // User hit cancel button.
476         elseif (!$login && !$userid)
477             return false;       // Nothing to do?
478
479         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
480         if (!$authlevel)
481             return _("Invalid password or userid.");
482         elseif ($authlevel < $require_level)
483             return _("Insufficient permissions.");
484
485         // Successful login.
486         $user = $GLOBALS['request']->_user;
487         $user->_userid = $userid;
488         $user->_level = $authlevel;
489         return $user;
490     }
491
492 }
493
494 /**
495  * Not authenticated in user, but he may be signed in. Basicly with view access only.
496  * prefs are stored in cookies, but only the userid.
497  */
498 class _AnonUser
499 extends _WikiUser
500 {
501     var $_level = WIKIAUTH_ANON;
502
503     /** Anon only gets to load and save prefs in a cookie, that's it.
504      */
505     function getPreferences() {
506         global $request;
507
508         if (empty($this->_prefs))
509             $this->_prefs = new UserPreferences;
510         $UserName = $this->UserName();
511         if ($cookie = $request->getCookieVar(WIKI_NAME)) {
512             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
513                 trigger_error(_("Format of UserPreferences cookie not recognised.") . " "
514                               . _("Default preferences will be used."),
515                               E_USER_WARNING);
516             }
517             // TODO: try reading userid from old PhpWiki cookie
518             // formats, then delete old cookie from browser!
519             //
520             //else {
521                 // try old cookie format.
522                 //$cookie = $request->getCookieVar('WIKI_ID');
523             //}
524
525             /**
526              * Only keep the cookie if it matches the UserName who is
527              * signing in or if this really is an Anon login (no
528              * username). (Remember, _BogoUser and higher inherit this
529              * function too!).
530              */
531             if (! $UserName || $UserName == $unboxedcookie['userid']) {
532                 $this->_prefs = new UserPreferences($unboxedcookie);
533                 $this->_userid = $unboxedcookie['userid'];
534             }
535         }
536         // initializeTheme() needs at least an empty object
537         if (! $this->_prefs )
538             $this->_prefs = new UserPreferences;
539         return $this->_prefs;
540     }
541
542     /** Save prefs in a cookie
543      */
544     function setPreferences($prefs, $id_only=false) {
545         // Allow for multiple wikis in same domain. Encode only the
546         // _prefs array of the UserPreference object. Ideally the
547         // prefs array should just be imploded into a single string or
548         // something so it is completely human readable by the end
549         // user. In that case stricter error checking will be needed
550         // when loading the cookie.
551         if (!is_object($prefs)) {
552             $prefs = new UserPreferences($prefs);
553         }
554         // check if different from the current prefs
555         $updated = $this->_prefs->isChanged($prefs);
556         if ($updated) {
557             if ($id_only) {
558                 setcookie(WIKI_NAME, serialize(array('userid' => $prefs->get('userid'))),
559                           COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
560             }
561         }
562         $packed = $prefs->store();
563         $unpacked = $prefs->unpack($packed);
564         if (count($unpacked)) {
565             global $request;
566             $this->_prefs = $prefs;
567             $request->_prefs =& $this->_prefs; 
568             $request->_user->_prefs =& $this->_prefs;
569             if (isset($request->_user->_auth_dbi)) {
570                 $user = $request->_user;
571                 unset($user->_auth_dbi);
572                 $request->setSessionVar('wiki_user', $user);
573             } else {
574               //$request->setSessionVar('wiki_prefs', $this->_prefs);
575               $request->setSessionVar('wiki_user', $request->_user);
576             }
577         }
578         return $updated;
579     }
580
581     function userExists() {
582         return true;
583     }
584
585     function checkPass($submitted_password) {
586         // By definition, the _AnonUser does not HAVE a password
587         // (compared to _BogoUser, who has an EMPTY password).
588         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
589                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
590                       . "New subclasses of _WikiUser must override this function.");
591         return false;
592     }
593
594 }
595
596 /** 
597  * Helper class to finish the PassUser auth loop. 
598  * This is added automatically to USER_AUTH_ORDER.
599  */
600 class _ForbiddenUser
601 extends _AnonUser
602 {
603     var $_level = WIKIAUTH_FORBIDDEN;
604
605     function checkPass($submitted_password) {
606         return WIKIAUTH_FORBIDDEN;
607     }
608
609     function userExists() {
610         if ($this->_HomePagehandle) return true;
611         return false;
612     }
613 }
614 /** 
615  * The PassUser name gets created automatically. 
616  * That's why this class is empty, but must exist.
617  */
618 class _ForbiddenPassUser
619 extends _ForbiddenUser
620 {
621     function dummy() {
622         return;
623     }
624 }
625
626 /**
627  * Do NOT extend _BogoUser to other classes, for checkPass()
628  * security. (In case of defects in code logic of the new class!)
629  * The intermediate step between anon and passuser.
630  * We also have the _BogoLoginPassUser class with stricter 
631  * password checking, which fits into the auth loop.
632  * Note: This class is not called anymore by WikiUser()
633  */
634 class _BogoUser
635 extends _AnonUser
636 {
637     function userExists() {
638         if (isWikiWord($this->_userid)) {
639             $this->_level = WIKIAUTH_BOGO;
640             return true;
641         } else {
642             $this->_level = WIKIAUTH_ANON;
643             return false;
644         }
645     }
646
647     function checkPass($submitted_password) {
648         // By definition, BogoUser has an empty password.
649         $this->userExists();
650         return $this->_level;
651     }
652 }
653
654 class _PassUser
655 extends _AnonUser
656 /**
657  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
658  *
659  * The classes for all subsequent auth methods extend from this class. 
660  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
661  * the three auth method policies first-only, strict and stacked
662  * and the two methods for prefs: homepage or database, 
663  * if $DBAuthParams['pref_select'] is defined.
664  *
665  * Default is PersonalPage auth and prefs.
666  * 
667  * TODO: email verification
668  *
669  * @author: Reini Urban
670  * @tables: pref
671  */
672 {
673     var $_auth_dbi, $_prefs;
674     var $_current_method, $_current_index;
675
676     // check and prepare the auth and pref methods only once
677     function _PassUser($UserName='', $prefs=false) {
678         global $DBAuthParams, $DBParams;
679         if ($UserName) {
680             $this->_userid = $UserName;
681             if ($this->hasHomePage())
682                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
683         }
684         $this->_authmethod = substr(get_class($this),1,-8);
685         if (!$this->_prefs) {
686             if ($prefs) $this->_prefs = $prefs;
687             else $this->getPreferences();
688         }
689
690         // Check the configured Prefs methods
691         if ( !isset($this->_prefs->_select) and !empty($DBAuthParams['pref_select']) 
692              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
693             $this->_prefs->_method = $DBParams['dbtype'];
694             $this->getAuthDbh();
695             // preparate the SELECT statement
696             $this->_prefs->_select = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
697         //} else {
698         //    unset($this->_prefs->_select);
699         }
700         if (  !isset($this->_prefs->_update) and !empty($DBAuthParams['pref_update'])
701              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
702             $this->_prefs->_method = $DBParams['dbtype'];
703             $this->getAuthDbh();
704             // preparate the SELECT statement
705             $this->_prefs->_update = str_replace(array('"$userid"','"$pref_blob"'),
706                                                  array('%s','%s'),
707                                              $DBAuthParams['pref_update']);
708         }
709         
710         // Upgrade to the next parent _PassUser class. Avoid recursion.
711         if ( strtolower(get_class($this)) === '_passuser' ) {
712             //auth policy: Check the order of the configured auth methods
713             // 1. first-only: Upgrade the class here in the constructor
714             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as 
715             ///              in the previous PhpWiki releases (slow)
716             // 3. strict:    upgrade the class after checking the user existance in userExists()
717             // 4. stacked:   upgrade the class after the password verification in checkPass()
718             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
719             if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
720             if (defined('USER_AUTH_POLICY')) {
721                 // policy 1: only pre-define one method for all users
722                 if (USER_AUTH_POLICY === 'first-only') {
723                     if ($user = $this->nextClass())
724                         return $user;
725                     else 
726                         return $GLOBALS['ForbiddenUser'];
727                 }
728                 // use the default behaviour from the previous versions:
729                 elseif (USER_AUTH_POLICY === 'old') {
730                     // default: try to be smart
731                     if (!empty($GLOBALS['PHP_AUTH_USER'])) {
732                         $this = new _HttpAuthPassUser($UserName,$this->_prefs);
733                         return $this;
734                     } elseif (!empty($DBAuthParams['auth_check']) and 
735                               (!empty($DBAuthParams['auth_dsn']) or !empty($GLOBALS ['DBParams']['dsn']))) {
736                         $this = new _DbPassUser($UserName,$this->_prefs);
737                         return $this;
738                     } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
739                         $this = new _LDAPPassUser($UserName,$this->_prefs);
740                         return $this;
741                     } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
742                         $this = new _IMAPPassUser($UserName,$this->_prefs);
743                         return $this;
744                     } elseif (defined('AUTH_USER_FILE')) {
745                         $this = new _FilePassUser($UserName,$this->_prefs);
746                         return $this;
747                     } else {
748                         $this = new _PersonalPagePassUser($UserName,$this->_prefs);
749                         return $this;
750                     }
751                 }
752                 else 
753                     // else use the page methods defined in _PassUser.
754                     return $this;
755             }
756         }
757     }
758
759     function getAuthDbh () {
760         global $request, $DBParams, $DBAuthParams;
761
762         // session restauration doesn't re-connect to the database automatically, so dirty it here.
763         if (($DBParams['dbtype'] == 'SQL') and isset($this->_auth_dbi) and 
764              empty($this->_auth_dbi->connection))
765             unset($this->_auth_dbi);
766         if (($DBParams['dbtype'] == 'ADODB') and isset($this->_auth_dbi) and 
767              empty($this->_auth_dbi->_connectionID))
768             unset($this->_auth_dbi);
769
770         if (empty($this->_auth_dbi)) {
771             if (empty($DBAuthParams['auth_dsn'])) {
772                 if ($DBParams['dbtype'] == 'SQL')
773                     $dbh = $request->getDbh(); // use phpwiki database 
774                 else 
775                     return false;
776             }
777             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
778                 $dbh = $request->getDbh(); // same phpwiki database 
779             else // use another external database handle. needs PHP >= 4.1
780                 $dbh = WikiDB::open($DBAuthParams);
781                 
782             $this->_auth_dbi =& $dbh->_backend->_dbh;    
783         }
784         return $this->_auth_dbi;
785     }
786
787     // not used anymore. have to do the prefix fixing somewhere else
788     function prepare ($stmt, $variables) {
789         global $DBParams, $request;
790         // preparate the SELECT statement, for ADODB and PearDB (MDB not)
791         $this->getAuthDbh();
792         $place = ($DBParams['dbtype'] == 'ADODB') ? '%s' : '?';
793         if (is_array($variables)) {
794             $new = array();
795             foreach ($variables as $v) { $new[] = $place; }
796         } else {
797             $new = $place;
798         }
799         // probably prefix table names if in same database
800         if (!empty($DBParams['prefix']) and 
801             $this->_auth_dbi === $request->_dbi->_backend->_dbh) {
802             if (!stristr($DBParams['prefix'],$stmt)) {
803                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
804                 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php: $stmt",
805                               E_USER_WARNING);
806                 $stmt = str_replace(array(" user "," pref "," member "),
807                                     array(" ".$prefix."user ",
808                                           " ".$prefix."prefs ",
809                                           " ".$prefix."member "),$stmt);
810             }
811         }
812         return $this->_auth_dbi->prepare(str_replace($variables,$new,$stmt));
813     }
814
815     function getPreferences() {
816         if (!empty($this->_prefs->_method)) {
817             if ($this->_prefs->_method == 'ADODB') {
818                 _AdoDbPassUser::_AdoDbPassUser();
819                 return _AdoDbPassUser::getPreferences();
820             } elseif ($this->_prefs->_method == 'SQL') {
821                 _PearDbPassUser::_PearDbPassUser();
822                 return _PearDbPassUser::getPreferences();
823             }
824         }
825
826         // We don't necessarily have to read the cookie first. Since
827         // the user has a password, the prefs stored in the homepage
828         // cannot be arbitrarily altered by other Bogo users.
829         _AnonUser::getPreferences();
830         // User may have deleted cookie, retrieve from his
831         // PersonalPage if there is one.
832         if (! $this->_prefs && $this->_HomePagehandle) {
833             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
834                 $this->_prefs = new UserPreferences($restored_from_page);
835                 return $this->_prefs;
836             }
837         }
838         return $this->_prefs;
839     }
840
841     function setPreferences($prefs, $id_only=false) {
842         if (!empty($this->_prefs->_method)) {
843             if ($this->_prefs->_method == 'ADODB') {
844                 _AdoDbPassUser::_AdoDbPassUser();
845                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
846             }
847             elseif ($this->_prefs->_method == 'SQL') {
848                 _PearDbPassUser::_PearDbPassUser();
849                 return _PearDbPassUser::setPreferences($prefs, $id_only);
850             }
851         }
852
853         if (!is_object($prefs)) {
854             $prefs = new UserPreferences($prefs);
855         }
856         _AnonUser::setPreferences($prefs, $id_only);
857         // Encode only the _prefs array of the UserPreference object
858         if ($this->_prefs->isChanged($prefs)) {
859             if ($this->_HomePagehandle and !$id_only)
860                 $this->_HomePagehandle->set('pref', $prefs->store());
861         }
862         return;
863     }
864
865     function mayChangePass() {
866         return true;
867     }
868
869     //The default method is getting the password from prefs. 
870     // child methods obtain $stored_password from external auth.
871     function userExists() {
872         //if ($this->_HomePagehandle) return true;
873         while ($user = $this->nextClass()) {
874               if ($user->userExists()) {
875                   $this = $user;
876                   return true;
877               }
878               $this = $user; // prevent endless loop. does this work on all PHP's?
879               // it just has to set the classname, what it correctly does.
880         }
881         return false;
882     }
883
884     //The default method is getting the password from prefs. 
885     // child methods obtain $stored_password from external auth.
886     function checkPass($submitted_password) {
887         $stored_password = $this->_prefs->get('passwd');
888         if ($this->_checkPass($submitted_password, $stored_password)) {
889             $this->_level = WIKIAUTH_USER;
890             return $this->_level;
891         } else {
892             return $this->_tryNextPass($submitted_password);
893         }
894     }
895
896     /**
897      * The basic password checker for all PassUser objects.
898      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
899      * Empty passwords are always false!
900      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
901      * @see UserPreferences::set
902      *
903      * DBPassUser password's have their own crypt definition.
904      * That's why DBPassUser::checkPass() doesn't call this method, if 
905      * the db password method is 'plain', which means that the DB SQL 
906      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
907      * don't store plain passwords in the DB.
908      * 
909      * TODO: remove crypt() function check from config.php:396 ??
910      */
911     function _checkPass($submitted_password, $stored_password) {
912         if(!empty($submitted_password)) {
913             if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
914                 // Todo. hmm...
915                 trigger_error(_("The length of the stored password is shorter than the system policy allows. Sorry, you cannot login.\n You have to ask the System Administrator to reset your password."));
916             }
917             if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
918                 return false;
919             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
920                 // Verify against encrypted password.
921                 if (function_exists('crypt')) {
922                     if (crypt($submitted_password, $stored_password) == $stored_password )
923                         return true; // matches encrypted password
924                     else
925                         return false;
926                 }
927                 else {
928                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
929                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and probably change ADMIN_PASSWD."),
930                                   E_USER_WARNING);
931                     return false;
932                 }
933             }
934             else {
935                 // Verify against cleartext password.
936                 if ($submitted_password == $stored_password)
937                     return true;
938                 else {
939                     // Check whether we forgot to enable ENCRYPTED_PASSWD
940                     if (function_exists('crypt')) {
941                         if (crypt($submitted_password, $stored_password) == $stored_password) {
942                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
943                                           E_USER_WARNING);
944                             return true;
945                         }
946                     }
947                 }
948             }
949         }
950         return false;
951     }
952
953     /** The default method is storing the password in prefs. 
954      *  Child methods (DB,File) may store in external auth also, but this 
955      *  must be explicitly enabled.
956      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
957      */
958     function changePass($submitted_password) {
959         $stored_password = $this->_prefs->get('passwd');
960         // check if authenticated
961         if ($this->isAuthenticated() and $stored_password != $submitted_password) {
962             $this->_prefs->set('passwd',$submitted_password);
963             //update the storage (session, homepage, ...)
964             $this->SetPreferences($this->_prefs);
965             return true;
966         }
967         //Todo: return an error msg to the caller what failed? 
968         // same password or no privilege
969         return false;
970     }
971
972     function _tryNextPass($submitted_password) {
973         if (USER_AUTH_POLICY === 'strict') {
974             if ($user = $this->nextClass()) {
975                 if ($user->userExists()) {
976                     return $user->checkPass($submitted_password);
977                 }
978             }
979         }
980         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
981             if ($user = $this->nextClass())
982                 return $user->checkPass($submitted_password);
983         }
984         return $this->_level;
985     }
986
987     function _tryNextUser() {
988         if (USER_AUTH_POLICY === 'strict') {
989             while ($user = $this->nextClass()) {
990                 if ($user->userExists()) {
991                     $this = $user;
992                     return true;
993                 }
994                 $this = $user;
995             }
996             /*
997             if ($user = $this->nextClass())
998                 return $user->userExists();
999             */
1000         }
1001         return false;
1002     }
1003
1004 }
1005
1006 /** Without stored password. A _BogoLoginPassUser with password 
1007  *  is automatically upgraded to a PersonalPagePassUser.
1008  */
1009 class _BogoLoginPassUser
1010 extends _PassUser
1011 {
1012     var $_authmethod = 'BogoLogin';
1013     function userExists() {
1014         if (isWikiWord($this->_userid)) {
1015             $this->_level = WIKIAUTH_BOGO;
1016             return true;
1017         } else {
1018             $this->_level = WIKIAUTH_ANON;
1019             return false;
1020         }
1021     }
1022
1023     /** A BogoLoginUser requires no password at all
1024      *  But if there's one stored, we should prefer PersonalPage instead
1025      */
1026     function checkPass($submitted_password) {
1027         if ($this->_prefs->get('passwd')) {
1028             $user = new _PersonalPagePassUser($this->_userid);
1029             if ($user->checkPass($submitted_password)) {
1030                 $this = $user;
1031                 $this->_level = WIKIAUTH_USER;
1032                 return $this->_level;
1033             } else {
1034                 $this->_level = WIKIAUTH_ANON;
1035                 return $this->_level;
1036             }
1037         }
1038         $this->userExists();
1039         return $this->_level;
1040     }
1041 }
1042
1043
1044 /**
1045  * This class is only to simplify the auth method dispatcher.
1046  * It inherits almost all all methods from _PassUser.
1047  */
1048 class _PersonalPagePassUser
1049 extends _PassUser
1050 {
1051     var $_authmethod = 'PersonalPage';
1052
1053     function userExists() {
1054         return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1055     }
1056         
1057     /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1058      *  BUT if the user already has a homepage with an empty password 
1059      *  stored, allow login but warn him to change it.
1060      */
1061     function checkPass($submitted_password) {
1062         if ($this->userExists()) {
1063             $stored_password = $this->_prefs->get('passwd');
1064             if (empty($stored_password)) {
1065                 trigger_error(sprintf(
1066                 _("\nYou stored an empty password in your %s page.\n").
1067                 _("Your access permissions are only for a BogoUser.\n").
1068                 _("Please set your password in UserPreferences."),
1069                                         $this->_userid), E_USER_NOTICE);
1070                 $this->_level = WIKIAUTH_BOGO;
1071                 return $this->_level;
1072             }
1073             if ($this->_checkPass($submitted_password, $stored_password))
1074                 return ($this->_level = WIKIAUTH_USER);
1075             return _PassUser::checkPass($submitted_password);
1076         }
1077         return WIKIAUTH_ANON;
1078     }
1079 }
1080
1081 /**
1082  * We have two possibilities here.
1083  * 1) The webserver location is already HTTP protected (usually Basic). Then just 
1084  *    use the username and do nothing
1085  * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1086  *    by sending a 401 error and let the client display the login dialog.
1087  *    This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1088  *    since the other methods cannot be transparently called after this enforced 
1089  *    external dialog.
1090  */
1091 class _HttpAuthPassUser
1092 extends _PassUser
1093 {
1094     function _HttpAuthPassUser($UserName='',$prefs=false) {
1095         if (!$this->_prefs) {
1096             if ($prefs) $this->_prefs = $prefs;
1097             else _PassUser::_PassUser($UserName);
1098         }
1099         $this->_authmethod = 'HttpAuth';
1100         if ($this->userExists())
1101             return $this;
1102         else 
1103             return $GLOBALS['ForbiddenUser'];
1104     }
1105
1106     //force http auth authorization
1107     function userExists() {
1108         // todo: older php's
1109         if (empty($_SERVER['PHP_AUTH_USER']) or 
1110             $_SERVER['PHP_AUTH_USER'] != $this->_userid) {
1111             header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1112             header('HTTP/1.0 401 Unauthorized'); 
1113             exit;
1114         }
1115         $this->_userid = $_SERVER['PHP_AUTH_USER'];
1116         $this->_level = WIKIAUTH_USER;
1117         return $this;
1118     }
1119         
1120     function checkPass($submitted_password) {
1121         return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1122     }
1123
1124     function mayChangePass() {
1125         return false;
1126     }
1127
1128     // hmm... either the server dialog or our own.
1129     function PrintLoginForm (&$request, $args, $fail_message = false,
1130                              $seperate_page = true) {
1131         header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1132         header('HTTP/1.0 401 Unauthorized'); 
1133         exit;
1134
1135         include_once('lib/Template.php');
1136         // Call update_locale in case the system's default language is not 'en'.
1137         // (We have no user pref for lang at this point yet, no one is logged in.)
1138         update_locale(DEFAULT_LANGUAGE);
1139         $userid = $this->_userid;
1140         $require_level = 0;
1141         extract($args); // fixme
1142
1143         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
1144
1145         $pagename = $request->getArg('pagename');
1146         $nocache = 1;
1147         $login = new Template('login', $request,
1148                               compact('pagename', 'userid', 'require_level',
1149                                       'fail_message', 'pass_required', 'nocache'));
1150         if ($seperate_page) {
1151             $top = new Template('html', $request,
1152                                 array('TITLE' => _("Sign In")));
1153             return $top->printExpansion($login);
1154         } else {
1155             return $login;
1156         }
1157     }
1158
1159 }
1160
1161
1162 /**
1163  * Baseclass for PearDB and ADODB PassUser's
1164  * Authenticate against a database, to be able to use shared users.
1165  *   internal: no different $DbAuthParams['dsn'] defined, or
1166  *   external: different $DbAuthParams['dsn']
1167  * The magic is done in the symbolic SQL statements in index.php, similar to
1168  * libnss-mysql.
1169  *
1170  * We support only the SQL and ADODB backends.
1171  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
1172  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
1173  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn']. 
1174  * (Not supported yet, since we require SQL. SQLite would make since when 
1175  * it will come to PHP)
1176  *
1177  * @tables: user, pref
1178  *
1179  * Preferences are handled in the parent class _PassUser, because the 
1180  * previous classes may also use DB pref_select and pref_update.
1181  *
1182  * Flat files auth is handled by the auth method "File".
1183  */
1184 class _DbPassUser
1185 extends _PassUser
1186 {
1187     var $_authselect, $_authupdate;
1188
1189     // This can only be called from _PassUser, because the parent class 
1190     // sets the auth_dbi and pref methods, before this class is initialized.
1191     function _DbPassUser($UserName='',$prefs=false) {
1192         if (!$this->_prefs) {
1193             if ($prefs) $this->_prefs = $prefs;
1194             else _PassUser::_PassUser($UserName);
1195         }
1196         $this->_authmethod = 'Db';
1197         //$this->getAuthDbh();
1198         //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1199         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') {
1200             $this = new _AdoDbPassUser($UserName,$this->_prefs);
1201             return $this;
1202         }
1203         else {
1204             $this = new _PearDbPassUser($UserName,$this->_prefs);
1205             return $this;
1206         }
1207     }
1208
1209     function mayChangePass() {
1210         return !isset($this->_authupdate);
1211     }
1212
1213 }
1214
1215 class _PearDbPassUser
1216 extends _DbPassUser
1217 /**
1218  * Pear DB methods
1219  * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1220  * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1221  *
1222  * @tables: user
1223  * @tables: pref
1224  */
1225 {
1226     function _PearDbPassUser($UserName='',$prefs=false) {
1227         global $DBAuthParams;
1228         if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1229             if ($prefs) $this->_prefs = $prefs;
1230             else _PassUser::_PassUser($UserName);
1231         }
1232         $this->_userid = $UserName;
1233         // make use of session data. generally we only initialize this every time, 
1234         // but do auth checks only once
1235         $this->_auth_crypt_method = @$DBAuthParams['auth_crypt_method'];
1236         //$this->getAuthDbh();
1237         return $this;
1238     }
1239
1240     function getPreferences() {
1241         // override the generic slow method here for efficiency and not to 
1242         // clutter the homepage metadata with prefs.
1243         _AnonUser::getPreferences();
1244         $this->getAuthDbh();
1245         $dbh = &$this->_auth_dbi;
1246         if ((! $this->_prefs) and isset($this->_prefs->_select)) {
1247             $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1248             list($prefs_blob) = $db_result->fetchRow();
1249             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1250                 $this->_prefs = new UserPreferences($restored_from_db);
1251                 return $this->_prefs;
1252             }
1253         }
1254         if ((! $this->_prefs) && $this->_HomePagehandle) {
1255             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1256                 $this->_prefs = new UserPreferences($restored_from_page);
1257                 return $this->_prefs;
1258             }
1259         }
1260         return $this->_prefs;
1261     }
1262
1263     function setPreferences($prefs, $id_only=false) {
1264         // Encode only the _prefs array of the UserPreference object
1265         if (!is_object($prefs)) {
1266             $prefs = new UserPreferences($prefs);
1267         }
1268         // if the prefs are changed
1269         if (_AnonUser::setPreferences($prefs, 1)) {
1270             global $request;
1271             $packed = $prefs->store();
1272             // $unpacked = $prefs->unpack($packed);
1273             if (isset($this->_prefs->_method))
1274                 $prefs->_method = $this->_prefs->_method;
1275             if (isset($this->_prefs->_select))
1276                 $prefs->_select = $this->_prefs->_select;
1277             if (isset($this->_prefs->_update))
1278                 $prefs->_update = $this->_prefs->_update;
1279             $this->_prefs = $prefs;
1280             $request->_prefs =& $this->_prefs; 
1281             $request->_user->_prefs =& $this->_prefs; 
1282             //$request->setSessionVar('wiki_prefs', $this->_prefs);
1283             //We don't store the dbi chain. DB connections don't survive sessions.
1284             $user = $request->_user;
1285             unset($user->_auth_dbi);
1286             $request->setSessionVar('wiki_user', $user);
1287             if (isset($this->_prefs->_update)) {
1288                 $this->getAuthDbh();
1289                 $dbh = &$this->_auth_dbi;
1290                 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1291                                           $dbh->quote($packed),
1292                                           $dbh->quote($this->_userid)));
1293             } else {
1294                 //store prefs in homepage, not in cookie
1295                 if ($this->_HomePagehandle and !$id_only)
1296                     $this->_HomePagehandle->set('pref', $packed);
1297             }
1298             return count($prefs->unpack($packed));
1299         }
1300         return 0;
1301     }
1302
1303     function userExists() {
1304         global $DBAuthParams;
1305         $this->getAuthDbh();
1306         $dbh = &$this->_auth_dbi;
1307         // Prepare the configured auth statements
1308         if (!empty($DBAuthParams['auth_check']) and !$this->_authselect) {
1309             $this->_authselect = str_replace(array('"$userid"','"$password"'),
1310                                              array('%s','%s'),
1311                                              $DBAuthParams['auth_check']);
1312         }
1313         if (!$this->_authselect)
1314             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1315                           E_USER_WARNING);
1316         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1317         if ($this->_auth_crypt_method == 'crypt') {
1318             $rs = $dbh->query(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1319             if ($rs->numRows())
1320                 return true;
1321         }
1322         else {
1323             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1324                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1325                               E_USER_WARNING);
1326             $this->_authcheck = str_replace('"$userid"','%s',
1327                                              $DBAuthParams['auth_user_exists']);
1328             $rs = $dbh->query(sprintf($this->_authcheck,$dbh->quote($this->_userid)));
1329             if ($rs->numRows())
1330                 return true;
1331         }
1332         // maybe the user is allowed to create himself. Generally not wanted in 
1333         // external databases, but maybe wanted for the wiki database, for performance 
1334         // reasons
1335         if (!$this->_authcreate and !empty($DBAuthParams['auth_create'])) {
1336             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1337                                               $DBAuthParams['auth_create']);
1338         }
1339         if ($this->_authcreate) return true;
1340
1341         return $this->_tryNextUser();
1342     }
1343  
1344     function checkPass($submitted_password) {
1345         global $DBAuthParams;
1346         $this->getAuthDbh();
1347         if (!$this->_authselect)
1348             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1349                           E_USER_WARNING);
1350
1351         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1352         $dbh = &$this->_auth_dbi;
1353         if ($this->_auth_crypt_method == 'crypt') {
1354             $stored_password = $dbh->getOne(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1355             $result = $this->_checkPass($submitted_password, $stored_password);
1356         } else {
1357             $okay = $dbh->getOne(sprintf($this->_authselect,
1358                                          $dbh->quote($submitted_password),
1359                                          $dbh->quote($this->_userid)));
1360             $result = !empty($okay);
1361         }
1362
1363         if ($result) {
1364             $this->_level = WIKIAUTH_USER;
1365             return $this->_level;
1366         } else {
1367             return $this->_tryNextPass($submitted_password);
1368         }
1369     }
1370
1371     function storePass($submitted_password) {
1372         global $DBAuthParams;
1373         $dbh = &$this->_auth_dbi;
1374         if (!empty($DBAuthParams['auth_update']) and !$this->_authupdate) {
1375             $this->_authupdate = str_replace(array('"$userid"','"$password"'),
1376                                              array('%s','%s'),
1377                                              $DBAuthParams['auth_update']);
1378         }
1379         if (!$this->_authupdate) {
1380             //CHECKME
1381             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1382                           E_USER_WARNING);
1383             return false;
1384         }
1385
1386         if ($this->_auth_crypt_method == 'crypt') {
1387             if (function_exists('crypt'))
1388                 $submitted_password = crypt($submitted_password);
1389         }
1390         $dbh->simpleQuery(sprintf($this->_authupdate,
1391                                   $dbh->quote($submitted_password),
1392                                   $dbh->quote($this->_userid)
1393                                   ));
1394     }
1395
1396 }
1397
1398 class _AdoDbPassUser
1399 extends _DbPassUser
1400 /**
1401  * ADODB methods
1402  * Simple sprintf, no prepare.
1403  *
1404  * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster 
1405  * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1406  *
1407  * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1408  *
1409  * @tables: user
1410  */
1411 {
1412     function _AdoDbPassUser($UserName='',$prefs=false) {
1413         if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1414             if ($prefs) $this->_prefs = $prefs;
1415             else _PassUser::_PassUser($UserName);
1416         }
1417         $this->_userid = $UserName;
1418         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1419         $this->getAuthDbh();
1420         // Don't prepare the configured auth statements anymore
1421         return $this;
1422     }
1423
1424     function getPreferences() {
1425         // override the generic slow method here for efficiency
1426         _AnonUser::getPreferences();
1427         //$this->getAuthDbh();
1428         if ((! $this->_prefs) and isset($this->_prefs->_select)) {
1429             $dbh = & $this->_auth_dbi;
1430             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
1431             if ($rs->EOF) {
1432                 $rs->Close();
1433             } else {
1434                 $prefs_blob = $rs->fields['pref_blob'];
1435                 $rs->Close();
1436                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1437                     $this->_prefs = new UserPreferences($restored_from_db);
1438                     return $this->_prefs;
1439                 }
1440             }
1441         }
1442         if ((! $this->_prefs) && $this->_HomePagehandle) {
1443             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1444                 $this->_prefs = new UserPreferences($restored_from_page);
1445                 return $this->_prefs;
1446             }
1447         }
1448         return $this->_prefs;
1449     }
1450
1451     function setPreferences($prefs, $id_only=false) {
1452         // Encode only the _prefs array of the UserPreference object
1453         if (!is_object($prefs)) {
1454             $prefs = new UserPreferences($prefs);
1455         }
1456         // if the prefs are changed
1457         if (_AnonUser::setPreferences($prefs, 1)) {
1458             global $request;
1459             $packed = $prefs->store();
1460             // $unpacked = $prefs->unpack($packed);
1461             
1462             if (isset($this->_prefs->_method))
1463                 $prefs->_method = $this->_prefs->_method;
1464             if (isset($this->_prefs->_select))
1465                 $prefs->_select = $this->_prefs->_select;
1466             if (isset($this->_prefs->_update))
1467                 $prefs->_update = $this->_prefs->_update;
1468             $this->_prefs = $prefs;
1469             $request->_prefs =& $this->_prefs; 
1470             $request->_user->_prefs =& $this->_prefs; 
1471             //$request->setSessionVar('wiki_prefs', $this->_prefs);
1472             //We don't store the dbi chain. DB connections don't survive sessions.
1473             $user = $request->_user;
1474             unset($user->_auth_dbi);
1475             $request->setSessionVar('wiki_user', $user);
1476             if (isset($this->_prefs->_update)) {
1477                 $this->getAuthDbh();
1478                 $dbh = &$this->_auth_dbi;
1479                 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1480                                                    $dbh->qstr($packed),$dbh->qstr($this->_userid)));
1481                 $db_result->Close();
1482             } else {
1483                 //store prefs in homepage, not in cookie
1484                 if ($this->_HomePagehandle and !$id_only)
1485                     $this->_HomePagehandle->set('pref', $packed);
1486             }
1487             return count($prefs->unpack($packed));
1488         }
1489         return 0;
1490     }
1491  
1492     function userExists() {
1493         global $DBAuthParams;
1494         if (!$this->_authselect and !empty($DBAuthParams['auth_check'])) {
1495             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1496                                               $DBAuthParams['auth_check']);
1497         }
1498         if (!$this->_authselect)
1499             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1500                           E_USER_WARNING);
1501         //$this->getAuthDbh();
1502         $dbh = &$this->_auth_dbi;
1503         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1504         if ($this->_auth_crypt_method == 'crypt') {
1505             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1506             if (!$rs->EOF) {
1507                 $rs->Close();
1508                 return true;
1509             } else {
1510                 $rs->Close();
1511             }
1512         }
1513         else {
1514             if (! $DBAuthParams['auth_user_exists'])
1515                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1516                               E_USER_WARNING);
1517             $this->_authcheck = str_replace('"$userid"','%s',
1518                                              $DBAuthParams['auth_user_exists']);
1519             $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1520             if (!$rs->EOF) {
1521                 $rs->Close();
1522                 return true;
1523             } else {
1524                 $rs->Close();
1525             }
1526         }
1527         // maybe the user is allowed to create himself. Generally not wanted in 
1528         // external databases, but maybe wanted for the wiki database, for performance 
1529         // reasons
1530         if (!$this->_authcreate and !empty($DBAuthParams['auth_create'])) {
1531             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1532                                               $DBAuthParams['auth_create']);
1533         }
1534         if ($this->_authcreate) return true;
1535         
1536         return $this->_tryNextUser();
1537     }
1538
1539     function checkPass($submitted_password) {
1540         global $DBAuthParams;
1541         if (!$this->_authselect and !empty($DBAuthParams['auth_check'])) {
1542             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1543                                               $DBAuthParams['auth_check']);
1544         }
1545         if (!isset($this->_authselect))
1546             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1547                           E_USER_WARNING);
1548         //$this->getAuthDbh();
1549         $dbh = &$this->_auth_dbi;
1550         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1551         if ($this->_auth_crypt_method == 'crypt') {
1552             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1553             if (!$rs->EOF) {
1554                 $stored_password = $rs->fields['password'];
1555                 $rs->Close();
1556                 $result = $this->_checkPass($submitted_password, $stored_password);
1557             } else {
1558                 $rs->Close();
1559                 $result = false;
1560             }
1561         }
1562         else {
1563             $rs = $dbh->Execute(sprintf($this->_authselect,
1564                                         $dbh->qstr($submitted_password),
1565                                         $dbh->qstr($this->_userid)));
1566             $okay = $rs->fields['ok'];
1567             $rs->Close();
1568             $result = !empty($okay);
1569         }
1570
1571         if ($result) { 
1572             $this->_level = WIKIAUTH_USER;
1573             return $this->_level;
1574         } else {
1575             return $this->_tryNextPass($submitted_password);
1576         }
1577     }
1578
1579     function storePass($submitted_password) {
1580         global $DBAuthParams;
1581         if (!isset($this->_authupdate) and !empty($DBAuthParams['auth_update'])) {
1582             $this->_authupdate = str_replace(array('"$userid"','"$password"'),array("%s","%s"),
1583                                               $DBAuthParams['auth_update']);
1584         }
1585         if (!isset($this->_authupdate)) {
1586             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1587                           E_USER_WARNING);
1588             return false;
1589         }
1590
1591         if ($this->_auth_crypt_method == 'crypt') {
1592             if (function_exists('crypt'))
1593                 $submitted_password = crypt($submitted_password);
1594         }
1595         $this->getAuthDbh();
1596         $dbh = &$this->_auth_dbi;
1597         $rs = $dbh->Execute(sprintf($this->_authupdate,
1598                                     $dbh->qstr($submitted_password),
1599                                     $dbh->qstr($this->_userid)
1600                                     ));
1601         $rs->Close();
1602     }
1603
1604 }
1605
1606 class _LDAPPassUser
1607 extends _PassUser
1608 /**
1609  * Define the vars LDAP_HOST and LDAP_BASE_DN in index.php
1610  *
1611  * Preferences are handled in _PassUser
1612  */
1613 {
1614     function checkPass($submitted_password) {
1615         $this->_authmethod = 'LDAP';
1616         $userid = $this->_userid;
1617         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1618             if (defined('LDAP_AUTH_USER'))
1619                 if (defined('LDAP_AUTH_PASSWORD'))
1620                     // Windows Active Directory Server is strict
1621                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1622                 else
1623                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1624             else
1625                 $r = @ldap_bind($ldap); // this is an anonymous bind
1626             if (!empty($LDAP_SET_OPTION)) {
1627                 foreach ($LDAP_SET_OPTION as $key => $value) {
1628                     ldap_set_option($ldap,$key,$value);
1629                 }
1630             }
1631             // Need to set the right root search information. see ../index.php
1632             $st_search = defined('LDAP_SEARCH_FIELD') 
1633                 ? LDAP_SEARCH_FIELD."=$userid"
1634                 : "uid=$userid";
1635             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1636             $info = ldap_get_entries($ldap, $sr); 
1637             // there may be more hits with this userid.
1638             // of course it would be better to narrow down the BASE_DN
1639             for ($i = 0; $i < $info["count"]; $i++) {
1640                 $dn = $info[$i]["dn"];
1641                 // The password is still plain text.
1642                 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
1643                     // ldap_bind will return TRUE if everything matches
1644                     ldap_close($ldap);
1645                     $this->_level = WIKIAUTH_USER;
1646                     return $this->_level;
1647                 }
1648             }
1649         } else {
1650             trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), 
1651                           E_USER_WARNING);
1652             //return false;
1653         }
1654
1655         return $this->_tryNextPass($submitted_password);
1656     }
1657
1658     function userExists() {
1659         $userid = $this->_userid;
1660
1661         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1662             if (defined('LDAP_AUTH_USER'))
1663                 if (defined('LDAP_AUTH_PASSWORD'))
1664                     // Windows Active Directory Server is strict
1665                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1666                 else
1667                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1668             else
1669                 $r = @ldap_bind($ldap); // this is an anonymous bind
1670             if (!empty($LDAP_SET_OPTION)) {
1671                 foreach ($LDAP_SET_OPTION as $key => $value) {
1672                     ldap_set_option($ldap,$key,$value);
1673                 }
1674             }
1675             // Need to set the right root search information. see ../index.php
1676             $st_search = defined('LDAP_SEARCH_FIELD') 
1677                 ? LDAP_SEARCH_FIELD."=$userid"
1678                 : "uid=$userid";
1679             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1680             $info = ldap_get_entries($ldap, $sr); 
1681
1682             if ($info["count"] > 0) {
1683                 ldap_close($ldap);
1684                 return true;
1685             }
1686         } else {
1687             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1688         }
1689
1690         return $this->_tryNextUser();
1691     }
1692
1693     function mayChangePass() {
1694         return false;
1695     }
1696
1697 }
1698
1699 class _IMAPPassUser
1700 extends _PassUser
1701 /**
1702  * Define the var IMAP_HOST in index.php
1703  *
1704  * Preferences are handled in _PassUser
1705  */
1706 {
1707     function checkPass($submitted_password) {
1708         $userid = $this->_userid;
1709         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1710                             $userid, $submitted_password, OP_HALFOPEN );
1711         if ($mbox) {
1712             imap_close($mbox);
1713             $this->_authmethod = 'IMAP';
1714             $this->_level = WIKIAUTH_USER;
1715             return $this->_level;
1716         } else {
1717             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1718         }
1719
1720         return $this->_tryNextPass($submitted_password);
1721     }
1722
1723     //CHECKME: this will not be okay for the auth policy strict
1724     function userExists() {
1725         if (checkPass($this->_prefs->get('passwd')))
1726             return true;
1727             
1728         return $this->_tryNextUser();
1729     }
1730
1731     function mayChangePass() {
1732         return false;
1733     }
1734
1735 }
1736
1737 class _FilePassUser
1738 extends _PassUser
1739 /**
1740  * Check users defined in a .htaccess style file
1741  * username:crypt\n...
1742  *
1743  * Preferences are handled in _PassUser
1744  */
1745 {
1746     var $_file, $_may_change;
1747
1748     // This can only be called from _PassUser, because the parent class 
1749     // sets the pref methods, before this class is initialized.
1750     function _FilePassUser($UserName='',$file='') {
1751         if (!$this->_prefs)
1752             _PassUser::_PassUser($UserName);
1753
1754         // read the .htaccess style file. We use our own copy of the standard pear class.
1755         require 'lib/pear/File_Passwd.php';
1756         // if passwords may be changed we have to lock them:
1757         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1758         if (empty($file) and defined('AUTH_USER_FILE'))
1759             $this->_file = File_Passwd(AUTH_USER_FILE, !empty($this->_may_change));
1760         elseif (!empty($file))
1761             $this->_file = File_Passwd($file, !empty($this->_may_change));
1762         else
1763             return false;
1764         return $this;
1765     }
1766  
1767     function mayChangePass() {
1768         return $this->_may_change;
1769     }
1770
1771     function userExists() {
1772         if (isset($this->_file->users[$this->_userid]))
1773             return true;
1774             
1775         return $this->_tryNextUser();
1776     }
1777
1778     function checkPass($submitted_password) {
1779         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1780             $this->_authmethod = 'File';
1781             $this->_level = WIKIAUTH_USER;
1782             return $this->_level;
1783         }
1784         
1785         return $this->_tryNextPass($submitted_password);
1786     }
1787
1788     function storePass($submitted_password) {
1789         if ($this->_may_change)
1790             return $this->_file->modUser($this->_userid,$submitted_password);
1791         else 
1792             return false;
1793     }
1794
1795 }
1796
1797 /**
1798  * Insert more auth classes here...
1799  * For example a customized db class for another db connection 
1800  * or a socket-based auth server
1801  *
1802  */
1803
1804
1805 /**
1806  * For security, this class should not be extended. Instead, extend
1807  * from _PassUser (think of this as unix "root").
1808  */
1809 class _AdminUser
1810 extends _PassUser
1811 {
1812
1813     function checkPass($submitted_password) {
1814         $stored_password = ADMIN_PASSWD;
1815         if ($this->_checkPass($submitted_password, $stored_password)) {
1816             $this->_level = WIKIAUTH_ADMIN;
1817             return $this->_level;
1818         } else {
1819             $this->_level = WIKIAUTH_ANON;
1820             return $this->_level;
1821         }
1822     }
1823
1824 }
1825
1826 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1827 /**
1828  * Various data classes for the preference types, 
1829  * to support get, set, sanify (range checking, ...)
1830  * update() will do the neccessary side-effects if a 
1831  * setting gets changed (theme, language, ...)
1832 */
1833
1834 class _UserPreference
1835 {
1836     var $default_value;
1837
1838     function _UserPreference ($default_value) {
1839         $this->default_value = $default_value;
1840     }
1841
1842     function sanify ($value) {
1843         return (string)$value;
1844     }
1845
1846     function get ($name) {
1847         if (isset($this->{$name}))
1848             return $this->{$name};
1849         else 
1850             return $this->default_value;
1851     }
1852
1853     function getraw ($name) {
1854         if (!empty($this->{$name}))
1855             return $this->{$name};
1856     }
1857
1858     // stores the value as $this->$name, and not as $this->value (clever?)
1859     function set ($name, $value) {
1860         if ($this->get($name) != $value) {
1861             $this->update($value);
1862         }
1863         if ($value != $this->default_value) {
1864             $this->{$name} = $value;
1865         }
1866         else 
1867             unset($this->{$name});
1868     }
1869
1870     // default: no side-effects 
1871     function update ($value) {
1872         ;
1873     }
1874 }
1875
1876 class _UserPreference_numeric
1877 extends _UserPreference
1878 {
1879     function _UserPreference_numeric ($default, $minval = false,
1880                                       $maxval = false) {
1881         $this->_UserPreference((double)$default);
1882         $this->_minval = (double)$minval;
1883         $this->_maxval = (double)$maxval;
1884     }
1885
1886     function sanify ($value) {
1887         $value = (double)$value;
1888         if ($this->_minval !== false && $value < $this->_minval)
1889             $value = $this->_minval;
1890         if ($this->_maxval !== false && $value > $this->_maxval)
1891             $value = $this->_maxval;
1892         return $value;
1893     }
1894 }
1895
1896 class _UserPreference_int
1897 extends _UserPreference_numeric
1898 {
1899     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1900         $this->_UserPreference_numeric((int)$default, (int)$minval,
1901                                        (int)$maxval);
1902     }
1903
1904     function sanify ($value) {
1905         return (int)parent::sanify((int)$value);
1906     }
1907 }
1908
1909 class _UserPreference_bool
1910 extends _UserPreference
1911 {
1912     function _UserPreference_bool ($default = false) {
1913         $this->_UserPreference((bool)$default);
1914     }
1915
1916     function sanify ($value) {
1917         if (is_array($value)) {
1918             /* This allows for constructs like:
1919              *
1920              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1921              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1922              *
1923              * (If the checkbox is not checked, only the hidden input
1924              * gets sent. If the checkbox is sent, both inputs get
1925              * sent.)
1926              */
1927             foreach ($value as $val) {
1928                 if ($val)
1929                     return true;
1930             }
1931             return false;
1932         }
1933         return (bool) $value;
1934     }
1935 }
1936
1937 class _UserPreference_language
1938 extends _UserPreference
1939 {
1940     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1941         $this->_UserPreference($default);
1942     }
1943
1944     // FIXME: check for valid locale
1945     function sanify ($value) {
1946         // Revert to DEFAULT_LANGUAGE if user does not specify
1947         // language in UserPreferences or chooses <system language>.
1948         if ($value == '' or empty($value))
1949             $value = DEFAULT_LANGUAGE;
1950
1951         return (string) $value;
1952     }
1953 }
1954
1955 class _UserPreference_theme
1956 extends _UserPreference
1957 {
1958     function _UserPreference_theme ($default = THEME) {
1959         $this->_UserPreference($default);
1960     }
1961
1962     function sanify ($value) {
1963         if (FindFile($this->_themefile($value)))
1964             return $value;
1965         return $this->default_value;
1966     }
1967
1968     function update ($newvalue) {
1969         global $Theme;
1970         if ($newvalue)
1971             include_once($this->_themefile($newvalue));
1972         if (empty($Theme))
1973             include_once($this->_themefile(THEME));
1974     }
1975
1976     function _themefile ($theme) {
1977         return "themes/$theme/themeinfo.php";
1978     }
1979 }
1980
1981 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1982
1983 /**
1984  * UserPreferences
1985  * 
1986  * This object holds the $request->_prefs subobjects.
1987  * A simple packed array of non-default values get's stored as cookie,
1988  * homepage, or database, which are converted to the array of 
1989  * ->_prefs objects.
1990  * We don't store the objects, because otherwise we will
1991  * not be able to upgrade any subobject. And it's a waste of space also.
1992  */
1993 class UserPreferences
1994 {
1995     function UserPreferences ($saved_prefs = false) {
1996         // userid stored too, to ensure the prefs are being loaded for
1997         // the correct (currently signing in) userid if stored in a
1998         // cookie.
1999         $this->_prefs
2000             = array(
2001                     'userid'        => new _UserPreference(''),
2002                     'passwd'        => new _UserPreference(''),
2003                     'autologin'     => new _UserPreference_bool(),
2004                     'email'         => new _UserPreference(''),
2005                     'emailVerified' => new _UserPreference_bool(),
2006                     'notifyPages'   => new _UserPreference(''),
2007                     'theme'         => new _UserPreference_theme(THEME),
2008                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
2009                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2010                                                                EDITWIDTH_MIN_COLS,
2011                                                                EDITWIDTH_MAX_COLS),
2012                     'noLinkIcons'   => new _UserPreference_bool(),
2013                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2014                                                                EDITHEIGHT_MIN_ROWS,
2015                                                                EDITHEIGHT_DEFAULT_ROWS),
2016                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2017                                                                    TIMEOFFSET_MIN_HOURS,
2018                                                                    TIMEOFFSET_MAX_HOURS),
2019                     'relativeDates' => new _UserPreference_bool()
2020                     );
2021
2022         if (is_array($saved_prefs)) {
2023             foreach ($saved_prefs as $name => $value)
2024                 $this->set($name, $value);
2025         }
2026     }
2027
2028     function _getPref ($name) {
2029         if (!isset($this->_prefs[$name])) {
2030             if ($name == 'passwd2') return false;
2031             trigger_error("$name: unknown preference", E_USER_NOTICE);
2032             return false;
2033         }
2034         return $this->_prefs[$name];
2035     }
2036     
2037     // get the value or default_value of the subobject
2038     function get ($name) {
2039         if ($_pref = $this->_getPref($name))
2040           return $_pref->get($name);
2041         else 
2042           return false;  
2043         /*      
2044         if (is_object($this->_prefs[$name]))
2045             return $this->_prefs[$name]->get($name);
2046         elseif (($value = $this->_getPref($name)) === false)
2047             return false;
2048         elseif (!isset($value))
2049             return $this->_prefs[$name]->default_value;
2050         else return $value;
2051         */
2052     }
2053
2054     // check and set the new value in the subobject
2055     function set ($name, $value) {
2056         $pref = $this->_getPref($name);
2057         if ($pref === false)
2058             return false;
2059
2060         /* do it here or outside? */
2061         if ($name == 'passwd' and 
2062             defined('PASSWORD_LENGTH_MINIMUM') and 
2063             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2064             //TODO: How to notify the user?
2065             return false;
2066         }
2067         if ($name == 'theme' and $value == '')
2068            return true;
2069         $newvalue = $pref->sanify($value);
2070         $pref->set($name,$newvalue);
2071         $this->_prefs[$name] = $pref;
2072         return true;
2073
2074         // don't set default values to save space (in cookies, db and
2075         // sesssion)
2076         /*
2077         if ($value == $pref->default_value)
2078             unset($this->_prefs[$name]);
2079         else
2080             $this->_prefs[$name] = $pref;
2081         */
2082     }
2083
2084     // for now convert just array of objects => array of values
2085     // Todo: the specialized subobjects must override this.
2086     function store() {
2087         $prefs = array();
2088         foreach ($this->_prefs as $name => $object) {
2089             if ($value = $object->getraw($name))
2090                 $prefs[] = array($name => $value);
2091         }
2092         return $this->pack($prefs);
2093     }
2094
2095     // packed string or array of values => array of values
2096     // Todo: the specialized subobjects must override this.
2097     function retrieve($packed) {
2098         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2099             $packed = unserialize($packed);
2100         if (!is_array($packed)) return false;
2101         $prefs = array();
2102         foreach ($packed as $name => $packed_pref) {
2103             if (substr($packed_pref, 0, 2) == "O:") {
2104                 //legacy: check if it's an old array of objects
2105                 // Looks like a serialized object. 
2106                 // This might fail if the object definition does not exist anymore.
2107                 // object with ->$name and ->default_value vars.
2108                 $pref = unserialize($packed_pref);
2109                 $prefs[$name] = $pref->get($name);
2110             } else {
2111                 $prefs[$name] = unserialize($packed_pref);
2112             }
2113         }
2114         return $prefs;
2115     }
2116
2117     /**
2118      * Check if the given prefs object is different from the current prefs object
2119      */
2120     function isChanged($other) {
2121         foreach ($this->_prefs as $type => $obj) {
2122             if ($obj->get($type) !== $other->get($type))
2123                 return true;
2124         }
2125         return false;
2126     }
2127
2128     // array of objects
2129     function getAll() {
2130         return $this->_prefs;
2131     }
2132
2133     function pack($nonpacked) {
2134         return serialize($nonpacked);
2135     }
2136
2137     function unpack($packed) {
2138         if (!$packed)
2139             return false;
2140         if (substr($packed, 0, 2) == "O:") {
2141             // Looks like a serialized object
2142             return unserialize($packed);
2143         }
2144         if (substr($packed, 0, 2) == "a:") {
2145             return unserialize($packed);
2146         }
2147         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2148         //E_USER_WARNING);
2149         return false;
2150     }
2151
2152     function hash () {
2153         return hash($this->_prefs);
2154     }
2155 }
2156
2157 class CookieUserPreferences
2158 extends UserPreferences
2159 {
2160     function CookieUserPreferences ($saved_prefs = false) {
2161         //_AnonUser::_AnonUser('',$saved_prefs);
2162         UserPreferences::UserPreferences($saved_prefs);
2163     }
2164 }
2165
2166 class PageUserPreferences
2167 extends UserPreferences
2168 {
2169     function PageUserPreferences ($saved_prefs = false) {
2170         UserPreferences::UserPreferences($saved_prefs);
2171     }
2172 }
2173
2174 class PearDbUserPreferences
2175 extends UserPreferences
2176 {
2177     function PearDbUserPreferences ($saved_prefs = false) {
2178         UserPreferences::UserPreferences($saved_prefs);
2179     }
2180 }
2181
2182 class AdoDbUserPreferences
2183 extends UserPreferences
2184 {
2185     function AdoDbUserPreferences ($saved_prefs = false) {
2186         UserPreferences::UserPreferences($saved_prefs);
2187     }
2188     function getPreferences() {
2189         // override the generic slow method here for efficiency
2190         _AnonUser::getPreferences();
2191         $this->getAuthDbh();
2192         if ((! $this->_prefs) and isset($this->_prefs->_select)) {
2193             $dbh = & $this->_auth_dbi;
2194             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
2195             if ($rs->EOF) {
2196                 $rs->Close();
2197             } else {
2198                 $prefs_blob = $rs->fields['pref_blob'];
2199                 $rs->Close();
2200                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2201                     $this->_prefs = new UserPreferences($restored_from_db);
2202                     return $this->_prefs;
2203                 }
2204             }
2205         }
2206         if ((! $this->_prefs) && $this->_HomePagehandle) {
2207             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2208                 $this->_prefs = new UserPreferences($restored_from_page);
2209                 return $this->_prefs;
2210             }
2211         }
2212         return $this->_prefs;
2213     }
2214 }
2215
2216
2217 // $Log: not supported by cvs2svn $
2218 // Revision 1.23  2004/02/27 13:21:17  rurban
2219 // several performance improvements, esp. with peardb
2220 // simplified loops
2221 // storepass seperated from prefs if defined so
2222 // stacked and strict still not working
2223 //
2224 // Revision 1.22  2004/02/27 05:15:40  rurban
2225 // more stability. detected by Micki
2226 //
2227 // Revision 1.21  2004/02/26 20:43:49  rurban
2228 // new HttpAuthPassUser class (forces http auth if in the auth loop)
2229 // fixed user upgrade: don't return _PassUser in the first hand.
2230 //
2231 // Revision 1.20  2004/02/26 01:29:11  rurban
2232 // important fixes: endless loops in certain cases. minor rewrite
2233 //
2234 // Revision 1.19  2004/02/25 17:15:17  rurban
2235 // improve stability
2236 //
2237 // Revision 1.18  2004/02/24 15:20:05  rurban
2238 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
2239 //
2240 // Revision 1.17  2004/02/17 12:16:42  rurban
2241 // started with changePass support. not yet used.
2242 //
2243 // Revision 1.16  2004/02/15 22:23:45  rurban
2244 // oops, fixed showstopper (endless recursion)
2245 //
2246 // Revision 1.15  2004/02/15 21:34:37  rurban
2247 // PageList enhanced and improved.
2248 // fixed new WikiAdmin... plugins
2249 // editpage, Theme with exp. htmlarea framework
2250 //   (htmlarea yet committed, this is really questionable)
2251 // WikiUser... code with better session handling for prefs
2252 // enhanced UserPreferences (again)
2253 // RecentChanges for show_deleted: how should pages be deleted then?
2254 //
2255 // Revision 1.14  2004/02/15 17:30:13  rurban
2256 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
2257 // fixed getPreferences() (esp. from sessions)
2258 // fixed setPreferences() (update and set),
2259 // fixed AdoDb DB statements,
2260 // update prefs only at UserPreferences POST (for testing)
2261 // unified db prefs methods (but in external pref classes yet)
2262 //
2263 // Revision 1.13  2004/02/09 03:58:12  rurban
2264 // for now default DB_SESSION to false
2265 // PagePerm:
2266 //   * not existing perms will now query the parent, and not
2267 //     return the default perm
2268 //   * added pagePermissions func which returns the object per page
2269 //   * added getAccessDescription
2270 // WikiUserNew:
2271 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
2272 //   * force init of authdbh in the 2 db classes
2273 // main:
2274 //   * fixed session handling (not triple auth request anymore)
2275 //   * don't store cookie prefs with sessions
2276 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
2277 //
2278 // Revision 1.12  2004/02/07 10:41:25  rurban
2279 // fixed auth from session (still double code but works)
2280 // fixed GroupDB
2281 // fixed DbPassUser upgrade and policy=old
2282 // added GroupLdap
2283 //
2284 // Revision 1.11  2004/02/03 09:45:39  rurban
2285 // LDAP cleanup, start of new Pref classes
2286 //
2287 // Revision 1.10  2004/02/01 09:14:11  rurban
2288 // Started with Group_Ldap (not yet ready)
2289 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
2290 // fixed some configurator vars
2291 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
2292 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
2293 // USE_DB_SESSION defaults to true on SQL
2294 // changed GROUP_METHOD definition to string, not constants
2295 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
2296 //   create users. (Not to be used with external databases generally, but
2297 //   with the default internal user table)
2298 //
2299 // fixed the IndexAsConfigProblem logic. this was flawed:
2300 //   scripts which are the same virtual path defined their own lib/main call
2301 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
2302 //
2303 // Revision 1.9  2004/01/30 19:57:58  rurban
2304 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
2305 //
2306 // Revision 1.8  2004/01/30 18:46:15  rurban
2307 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
2308 //
2309 // Revision 1.7  2004/01/27 23:23:39  rurban
2310 // renamed ->Username => _userid for consistency
2311 // renamed mayCheckPassword => mayCheckPass
2312 // fixed recursion problem in WikiUserNew
2313 // fixed bogo login (but not quite 100% ready yet, password storage)
2314 //
2315 // Revision 1.6  2004/01/26 09:17:49  rurban
2316 // * changed stored pref representation as before.
2317 //   the array of objects is 1) bigger and 2)
2318 //   less portable. If we would import packed pref
2319 //   objects and the object definition was changed, PHP would fail.
2320 //   This doesn't happen with an simple array of non-default values.
2321 // * use $prefs->retrieve and $prefs->store methods, where retrieve
2322 //   understands the interim format of array of objects also.
2323 // * simplified $prefs->get() and fixed $prefs->set()
2324 // * added $user->_userid and class '_WikiUser' portability functions
2325 // * fixed $user object ->_level upgrading, mostly using sessions.
2326 //   this fixes yesterdays problems with loosing authorization level.
2327 // * fixed WikiUserNew::checkPass to return the _level
2328 // * fixed WikiUserNew::isSignedIn
2329 // * added explodePageList to class PageList, support sortby arg
2330 // * fixed UserPreferences for WikiUserNew
2331 // * fixed WikiPlugin for empty defaults array
2332 // * UnfoldSubpages: added pagename arg, renamed pages arg,
2333 //   removed sort arg, support sortby arg
2334 //
2335 // Revision 1.5  2004/01/25 03:05:00  rurban
2336 // First working version, but has some problems with the current main loop.
2337 // Implemented new auth method dispatcher and policies, all the external
2338 // _PassUser classes (also for ADODB and Pear DB).
2339 // The two global funcs UserExists() and CheckPass() are probably not needed,
2340 // since the auth loop is done recursively inside the class code, upgrading
2341 // the user class within itself.
2342 // Note: When a higher user class is returned, this doesn't mean that the user
2343 // is authorized, $user->_level is still low, and only upgraded on successful
2344 // login.
2345 //
2346 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
2347 // Code Housecleaning: fixed syntax errors. (php -l *.php)
2348 //
2349 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
2350 // Finished off logic for determining user class, including
2351 // PassUser. Removed ability of BogoUser to save prefs into a page.
2352 //
2353 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
2354 // Added admin user, password user, and preference classes. Added
2355 // password checking functions for users and the admin. (Now the easy
2356 // parts are nearly done).
2357 //
2358 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
2359 // Complete rewrite of WikiUser.php.
2360 //
2361 // This should make it easier to hook in user permission groups etc. some
2362 // time in the future. Most importantly, to finally get UserPreferences
2363 // fully working properly for all classes of users: AnonUser, BogoUser,
2364 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
2365 // want a cookie or not, and to bring back optional AutoLogin with the
2366 // UserName stored in a cookie--something that was lost after PhpWiki had
2367 // dropped the default http auth login method.
2368 //
2369 // Added WikiUser classes which will (almost) work together with existing
2370 // UserPreferences class. Other parts of PhpWiki need to be updated yet
2371 // before this code can be hooked up.
2372 //
2373
2374 // Local Variables:
2375 // mode: php
2376 // tab-width: 8
2377 // c-basic-offset: 4
2378 // c-hanging-comment-ender-p: nil
2379 // indent-tabs-mode: nil
2380 // End:
2381 ?>