]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
important cookie fix by Konstantin Zadorozhny
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.30 2004-03-12 20:59:17 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         global $request;
546         // Allow for multiple wikis in same domain. Encode only the
547         // _prefs array of the UserPreference object. Ideally the
548         // prefs array should just be imploded into a single string or
549         // something so it is completely human readable by the end
550         // user. In that case stricter error checking will be needed
551         // when loading the cookie.
552         if (!is_object($prefs)) {
553             $prefs = new UserPreferences($prefs);
554         }
555         // check if different from the current prefs
556         $updated = $this->_prefs->isChanged($prefs);
557         if ($updated) {
558             if ($id_only) {
559                 $request->setCookieVar(WIKI_NAME, serialize(array('userid' => $prefs->get('userid'))),
560                                        COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
561             }
562         }
563         $packed = $prefs->store();
564         $unpacked = $prefs->unpack($packed);
565         if (count($unpacked)) {
566             global $request;
567             $this->_prefs = $prefs;
568             $request->_prefs =& $this->_prefs; 
569             $request->_user->_prefs =& $this->_prefs;
570             if (isset($request->_user->_auth_dbi)) {
571                 $user = $request->_user;
572                 unset($user->_auth_dbi);
573                 $request->setSessionVar('wiki_user', $user);
574             } else {
575               //$request->setSessionVar('wiki_prefs', $this->_prefs);
576               $request->setSessionVar('wiki_user', $request->_user);
577             }
578         }
579         return $updated;
580     }
581
582     function userExists() {
583         return true;
584     }
585
586     function checkPass($submitted_password) {
587         return false;
588         // this might happen on a old-style signin button.
589
590         // By definition, the _AnonUser does not HAVE a password
591         // (compared to _BogoUser, who has an EMPTY password).
592         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
593                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
594                       . "New subclasses of _WikiUser must override this function.");
595         return false;
596     }
597
598 }
599
600 /** 
601  * Helper class to finish the PassUser auth loop. 
602  * This is added automatically to USER_AUTH_ORDER.
603  */
604 class _ForbiddenUser
605 extends _AnonUser
606 {
607     var $_level = WIKIAUTH_FORBIDDEN;
608
609     function checkPass($submitted_password) {
610         return WIKIAUTH_FORBIDDEN;
611     }
612
613     function userExists() {
614         if ($this->_HomePagehandle) return true;
615         return false;
616     }
617 }
618 /** 
619  * The PassUser name gets created automatically. 
620  * That's why this class is empty, but must exist.
621  */
622 class _ForbiddenPassUser
623 extends _ForbiddenUser
624 {
625     function dummy() {
626         return;
627     }
628 }
629
630 /**
631  * Do NOT extend _BogoUser to other classes, for checkPass()
632  * security. (In case of defects in code logic of the new class!)
633  * The intermediate step between anon and passuser.
634  * We also have the _BogoLoginPassUser class with stricter 
635  * password checking, which fits into the auth loop.
636  * Note: This class is not called anymore by WikiUser()
637  */
638 class _BogoUser
639 extends _AnonUser
640 {
641     function userExists() {
642         if (isWikiWord($this->_userid)) {
643             $this->_level = WIKIAUTH_BOGO;
644             return true;
645         } else {
646             $this->_level = WIKIAUTH_ANON;
647             return false;
648         }
649     }
650
651     function checkPass($submitted_password) {
652         // By definition, BogoUser has an empty password.
653         $this->userExists();
654         return $this->_level;
655     }
656 }
657
658 class _PassUser
659 extends _AnonUser
660 /**
661  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
662  *
663  * The classes for all subsequent auth methods extend from this class. 
664  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
665  * the three auth method policies first-only, strict and stacked
666  * and the two methods for prefs: homepage or database, 
667  * if $DBAuthParams['pref_select'] is defined.
668  *
669  * Default is PersonalPage auth and prefs.
670  * 
671  * TODO: email verification
672  *
673  * @author: Reini Urban
674  * @tables: pref
675  */
676 {
677     var $_auth_dbi, $_prefs;
678     var $_current_method, $_current_index;
679
680     // check and prepare the auth and pref methods only once
681     function _PassUser($UserName='', $prefs=false) {
682         global $DBAuthParams, $DBParams;
683         if ($UserName) {
684             $this->_userid = $UserName;
685             if ($this->hasHomePage())
686                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
687         }
688         $this->_authmethod = substr(get_class($this),1,-8);
689         if (!$this->_prefs) {
690             if ($prefs) $this->_prefs = $prefs;
691             else $this->getPreferences();
692         }
693
694         // Check the configured Prefs methods
695         if ( !isset($this->_prefs->_select) and !empty($DBAuthParams['pref_select']) 
696              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
697             $this->_prefs->_method = $DBParams['dbtype'];
698             $this->getAuthDbh();
699             // preparate the SELECT statement
700             $this->_prefs->_select = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
701         //} else {
702         //    unset($this->_prefs->_select);
703         }
704         if (  !isset($this->_prefs->_update) and !empty($DBAuthParams['pref_update'])
705              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
706             $this->_prefs->_method = $DBParams['dbtype'];
707             $this->getAuthDbh();
708             // preparate the SELECT statement
709             $this->_prefs->_update = str_replace(array('"$userid"','"$pref_blob"'),
710                                                  array('%s','%s'),
711                                              $DBAuthParams['pref_update']);
712         }
713         
714         // Upgrade to the next parent _PassUser class. Avoid recursion.
715         if ( strtolower(get_class($this)) === '_passuser' ) {
716             //auth policy: Check the order of the configured auth methods
717             // 1. first-only: Upgrade the class here in the constructor
718             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as 
719             ///              in the previous PhpWiki releases (slow)
720             // 3. strict:    upgrade the class after checking the user existance in userExists()
721             // 4. stacked:   upgrade the class after the password verification in checkPass()
722             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
723             if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
724             if (defined('USER_AUTH_POLICY')) {
725                 // policy 1: only pre-define one method for all users
726                 if (USER_AUTH_POLICY === 'first-only') {
727                     if ($user = $this->nextClass())
728                         return $user;
729                     else 
730                         return $GLOBALS['ForbiddenUser'];
731                 }
732                 // use the default behaviour from the previous versions:
733                 elseif (USER_AUTH_POLICY === 'old') {
734                     // default: try to be smart
735                     if (!empty($GLOBALS['PHP_AUTH_USER'])) {
736                         $this = new _HttpAuthPassUser($UserName,$this->_prefs);
737                         return $this;
738                     } elseif (!empty($DBAuthParams['auth_check']) and 
739                               (!empty($DBAuthParams['auth_dsn']) or !empty($GLOBALS ['DBParams']['dsn']))) {
740                         $this = new _DbPassUser($UserName,$this->_prefs);
741                         return $this;
742                     } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
743                         $this = new _LDAPPassUser($UserName,$this->_prefs);
744                         return $this;
745                     } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
746                         $this = new _IMAPPassUser($UserName,$this->_prefs);
747                         return $this;
748                     } elseif (defined('AUTH_USER_FILE')) {
749                         $this = new _FilePassUser($UserName,$this->_prefs);
750                         return $this;
751                     } else {
752                         $this = new _PersonalPagePassUser($UserName,$this->_prefs);
753                         return $this;
754                     }
755                 }
756                 else 
757                     // else use the page methods defined in _PassUser.
758                     return $this;
759             }
760         }
761     }
762
763     function getAuthDbh () {
764         global $request, $DBParams, $DBAuthParams;
765
766         // session restauration doesn't re-connect to the database automatically, so dirty it here.
767         if (($DBParams['dbtype'] == 'SQL') and isset($this->_auth_dbi) and 
768              empty($this->_auth_dbi->connection))
769             unset($this->_auth_dbi);
770         if (($DBParams['dbtype'] == 'ADODB') and isset($this->_auth_dbi) and 
771              empty($this->_auth_dbi->_connectionID))
772             unset($this->_auth_dbi);
773
774         if (empty($this->_auth_dbi)) {
775             if (empty($DBAuthParams['auth_dsn'])) {
776                 if ($DBParams['dbtype'] == 'SQL' or $DBParams['dbtype'] == 'ADODB')
777                     $dbh = $request->getDbh(); // use phpwiki database 
778                 else 
779                     return false;
780             }
781             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
782                 $dbh = $request->getDbh(); // same phpwiki database 
783             else // use another external database handle. needs PHP >= 4.1
784                 $dbh = WikiDB::open($DBAuthParams);
785                 
786             $this->_auth_dbi =& $dbh->_backend->_dbh;    
787         }
788         return $this->_auth_dbi;
789     }
790
791     // not used anymore. have to do the prefix fixing somewhere else
792     function prepare ($stmt, $variables) {
793         global $DBParams, $request;
794         // preparate the SELECT statement, for ADODB and PearDB (MDB not)
795         $this->getAuthDbh();
796         $place = ($DBParams['dbtype'] == 'ADODB') ? '%s' : '?';
797         if (is_array($variables)) {
798             $new = array();
799             foreach ($variables as $v) { $new[] = $place; }
800         } else {
801             $new = $place;
802         }
803         // probably prefix table names if in same database
804         if (!empty($DBParams['prefix']) and 
805             $this->_auth_dbi === $request->_dbi->_backend->_dbh) {
806             if (!stristr($DBParams['prefix'],$stmt)) {
807                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
808                 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php: $stmt",
809                               E_USER_WARNING);
810                 $stmt = str_replace(array(" user "," pref "," member "),
811                                     array(" ".$prefix."user ",
812                                           " ".$prefix."prefs ",
813                                           " ".$prefix."member "),$stmt);
814             }
815         }
816         return $this->_auth_dbi->prepare(str_replace($variables,$new,$stmt));
817     }
818
819     function getPreferences() {
820         if (!empty($this->_prefs->_method)) {
821             if ($this->_prefs->_method == 'ADODB') {
822                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
823                 return _AdoDbPassUser::getPreferences();
824             } elseif ($this->_prefs->_method == 'SQL') {
825                 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
826                 return _PearDbPassUser::getPreferences();
827             }
828         }
829
830         // We don't necessarily have to read the cookie first. Since
831         // the user has a password, the prefs stored in the homepage
832         // cannot be arbitrarily altered by other Bogo users.
833         _AnonUser::getPreferences();
834         // User may have deleted cookie, retrieve from his
835         // PersonalPage if there is one.
836         if (! $this->_prefs && $this->_HomePagehandle) {
837             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
838                 $this->_prefs = new UserPreferences($restored_from_page);
839                 return $this->_prefs;
840             }
841         }
842         return $this->_prefs;
843     }
844
845     function setPreferences($prefs, $id_only=false) {
846         if (!empty($this->_prefs->_method)) {
847             if ($this->_prefs->_method == 'ADODB') {
848                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
849                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
850             }
851             elseif ($this->_prefs->_method == 'SQL') {
852                 _PearDbPassUser::_PearDbPassUser($this->_userid,$prefs);
853                 return _PearDbPassUser::setPreferences($prefs, $id_only);
854             }
855         }
856
857         if (!is_object($prefs)) {
858             $prefs = new UserPreferences($prefs);
859         }
860         _AnonUser::setPreferences($prefs, $id_only);
861         // Encode only the _prefs array of the UserPreference object
862         if ($this->_prefs->isChanged($prefs)) {
863             if ($this->_HomePagehandle and !$id_only)
864                 $this->_HomePagehandle->set('pref', $prefs->store());
865         }
866         return;
867     }
868
869     function mayChangePass() {
870         return true;
871     }
872
873     //The default method is getting the password from prefs. 
874     // child methods obtain $stored_password from external auth.
875     function userExists() {
876         //if ($this->_HomePagehandle) return true;
877         while ($user = $this->nextClass()) {
878               if ($user->userExists()) {
879                   $this = $user;
880                   return true;
881               }
882               $this = $user; // prevent endless loop. does this work on all PHP's?
883               // it just has to set the classname, what it correctly does.
884         }
885         return false;
886     }
887
888     //The default method is getting the password from prefs. 
889     // child methods obtain $stored_password from external auth.
890     function checkPass($submitted_password) {
891         $stored_password = $this->_prefs->get('passwd');
892         if ($this->_checkPass($submitted_password, $stored_password)) {
893             $this->_level = WIKIAUTH_USER;
894             return $this->_level;
895         } else {
896             return $this->_tryNextPass($submitted_password);
897         }
898     }
899
900     /**
901      * The basic password checker for all PassUser objects.
902      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
903      * Empty passwords are always false!
904      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
905      * @see UserPreferences::set
906      *
907      * DBPassUser password's have their own crypt definition.
908      * That's why DBPassUser::checkPass() doesn't call this method, if 
909      * the db password method is 'plain', which means that the DB SQL 
910      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
911      * don't store plain passwords in the DB.
912      * 
913      * TODO: remove crypt() function check from config.php:396 ??
914      */
915     function _checkPass($submitted_password, $stored_password) {
916         if(!empty($submitted_password)) {
917             if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
918                 // Todo. hmm...
919                 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."));
920             }
921             if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
922                 return false;
923             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
924                 // Verify against encrypted password.
925                 if (function_exists('crypt')) {
926                     if (crypt($submitted_password, $stored_password) == $stored_password )
927                         return true; // matches encrypted password
928                     else
929                         return false;
930                 }
931                 else {
932                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
933                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and probably change ADMIN_PASSWD."),
934                                   E_USER_WARNING);
935                     return false;
936                 }
937             }
938             else {
939                 // Verify against cleartext password.
940                 if ($submitted_password == $stored_password)
941                     return true;
942                 else {
943                     // Check whether we forgot to enable ENCRYPTED_PASSWD
944                     if (function_exists('crypt')) {
945                         if (crypt($submitted_password, $stored_password) == $stored_password) {
946                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
947                                           E_USER_WARNING);
948                             return true;
949                         }
950                     }
951                 }
952             }
953         }
954         return false;
955     }
956
957     /** The default method is storing the password in prefs. 
958      *  Child methods (DB,File) may store in external auth also, but this 
959      *  must be explicitly enabled.
960      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
961      */
962     function changePass($submitted_password) {
963         $stored_password = $this->_prefs->get('passwd');
964         // check if authenticated
965         if ($this->isAuthenticated() and $stored_password != $submitted_password) {
966             $this->_prefs->set('passwd',$submitted_password);
967             //update the storage (session, homepage, ...)
968             $this->SetPreferences($this->_prefs);
969             return true;
970         }
971         //Todo: return an error msg to the caller what failed? 
972         // same password or no privilege
973         return false;
974     }
975
976     function _tryNextPass($submitted_password) {
977         if (USER_AUTH_POLICY === 'strict') {
978             if ($user = $this->nextClass()) {
979                 if ($user->userExists()) {
980                     return $user->checkPass($submitted_password);
981                 }
982             }
983         }
984         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
985             if ($user = $this->nextClass())
986                 return $user->checkPass($submitted_password);
987         }
988         return $this->_level;
989     }
990
991     function _tryNextUser() {
992         if (USER_AUTH_POLICY === 'strict') {
993             while ($user = $this->nextClass()) {
994                 if ($user->userExists()) {
995                     $this = $user;
996                     return true;
997                 }
998                 $this = $user;
999             }
1000             /*
1001             if ($user = $this->nextClass())
1002                 return $user->userExists();
1003             */
1004         }
1005         return false;
1006     }
1007
1008 }
1009
1010 /** Without stored password. A _BogoLoginPassUser with password 
1011  *  is automatically upgraded to a PersonalPagePassUser.
1012  */
1013 class _BogoLoginPassUser
1014 extends _PassUser
1015 {
1016     var $_authmethod = 'BogoLogin';
1017     function userExists() {
1018         if (isWikiWord($this->_userid)) {
1019             $this->_level = WIKIAUTH_BOGO;
1020             return true;
1021         } else {
1022             $this->_level = WIKIAUTH_ANON;
1023             return false;
1024         }
1025     }
1026
1027     /** A BogoLoginUser requires no password at all
1028      *  But if there's one stored, we should prefer PersonalPage instead
1029      */
1030     function checkPass($submitted_password) {
1031         if ($this->_prefs->get('passwd')) {
1032             $user = new _PersonalPagePassUser($this->_userid);
1033             if ($user->checkPass($submitted_password)) {
1034                 $this = $user;
1035                 $this->_level = WIKIAUTH_USER;
1036                 return $this->_level;
1037             } else {
1038                 $this->_level = WIKIAUTH_ANON;
1039                 return $this->_level;
1040             }
1041         }
1042         $this->userExists();
1043         return $this->_level;
1044     }
1045 }
1046
1047
1048 /**
1049  * This class is only to simplify the auth method dispatcher.
1050  * It inherits almost all all methods from _PassUser.
1051  */
1052 class _PersonalPagePassUser
1053 extends _PassUser
1054 {
1055     var $_authmethod = 'PersonalPage';
1056
1057     function userExists() {
1058         return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1059     }
1060         
1061     /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1062      *  BUT if the user already has a homepage with an empty password 
1063      *  stored, allow login but warn him to change it.
1064      */
1065     function checkPass($submitted_password) {
1066         if ($this->userExists()) {
1067             $stored_password = $this->_prefs->get('passwd');
1068             if (empty($stored_password)) {
1069                 trigger_error(sprintf(
1070                 _("\nYou stored an empty password in your %s page.\n").
1071                 _("Your access permissions are only for a BogoUser.\n").
1072                 _("Please set your password in UserPreferences."),
1073                                         $this->_userid), E_USER_NOTICE);
1074                 $this->_level = WIKIAUTH_BOGO;
1075                 return $this->_level;
1076             }
1077             if ($this->_checkPass($submitted_password, $stored_password))
1078                 return ($this->_level = WIKIAUTH_USER);
1079             return _PassUser::checkPass($submitted_password);
1080         }
1081         return WIKIAUTH_ANON;
1082     }
1083 }
1084
1085 /**
1086  * We have two possibilities here.
1087  * 1) The webserver location is already HTTP protected (usually Basic). Then just 
1088  *    use the username and do nothing
1089  * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1090  *    by sending a 401 error and let the client display the login dialog.
1091  *    This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1092  *    since the other methods cannot be transparently called after this enforced 
1093  *    external dialog.
1094  *    Try the available auth methods (most likely Bogo) and sent this header back.
1095  *    header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1096  */
1097 class _HttpAuthPassUser
1098 extends _PassUser
1099 {
1100     function _HttpAuthPassUser($UserName='',$prefs=false) {
1101         if (!$this->_prefs) {
1102             if ($prefs) $this->_prefs = $prefs;
1103             else _PassUser::_PassUser($UserName);
1104         }
1105         $this->_authmethod = 'HttpAuth';
1106         if ($this->userExists())
1107             return $this;
1108         else 
1109             return $GLOBALS['ForbiddenUser'];
1110     }
1111
1112     //force http auth authorization
1113     function userExists() {
1114         // todo: older php's
1115         if (empty($_SERVER['PHP_AUTH_USER']) or 
1116             $_SERVER['PHP_AUTH_USER'] != $this->_userid) {
1117             header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1118             header('HTTP/1.0 401 Unauthorized'); 
1119             exit;
1120         }
1121         $this->_userid = $_SERVER['PHP_AUTH_USER'];
1122         $this->_level = WIKIAUTH_USER;
1123         return $this;
1124     }
1125         
1126     function checkPass($submitted_password) {
1127         return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1128     }
1129
1130     function mayChangePass() {
1131         return false;
1132     }
1133
1134     // hmm... either the server dialog or our own.
1135     function PrintLoginForm (&$request, $args, $fail_message = false,
1136                              $seperate_page = true) {
1137         header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1138         header('HTTP/1.0 401 Unauthorized'); 
1139         exit;
1140
1141         include_once('lib/Template.php');
1142         // Call update_locale in case the system's default language is not 'en'.
1143         // (We have no user pref for lang at this point yet, no one is logged in.)
1144         update_locale(DEFAULT_LANGUAGE);
1145         $userid = $this->_userid;
1146         $require_level = 0;
1147         extract($args); // fixme
1148
1149         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
1150
1151         $pagename = $request->getArg('pagename');
1152         $nocache = 1;
1153         $login = new Template('login', $request,
1154                               compact('pagename', 'userid', 'require_level',
1155                                       'fail_message', 'pass_required', 'nocache'));
1156         if ($seperate_page) {
1157             $top = new Template('html', $request,
1158                                 array('TITLE' => _("Sign In")));
1159             return $top->printExpansion($login);
1160         } else {
1161             return $login;
1162         }
1163     }
1164
1165 }
1166
1167
1168 /**
1169  * Baseclass for PearDB and ADODB PassUser's
1170  * Authenticate against a database, to be able to use shared users.
1171  *   internal: no different $DbAuthParams['dsn'] defined, or
1172  *   external: different $DbAuthParams['dsn']
1173  * The magic is done in the symbolic SQL statements in index.php, similar to
1174  * libnss-mysql.
1175  *
1176  * We support only the SQL and ADODB backends.
1177  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
1178  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
1179  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn']. 
1180  * (Not supported yet, since we require SQL. SQLite would make since when 
1181  * it will come to PHP)
1182  *
1183  * @tables: user, pref
1184  *
1185  * Preferences are handled in the parent class _PassUser, because the 
1186  * previous classes may also use DB pref_select and pref_update.
1187  *
1188  * Flat files auth is handled by the auth method "File".
1189  */
1190 class _DbPassUser
1191 extends _PassUser
1192 {
1193     var $_authselect, $_authupdate, $_authcreate;
1194
1195     // This can only be called from _PassUser, because the parent class 
1196     // sets the auth_dbi and pref methods, before this class is initialized.
1197     function _DbPassUser($UserName='',$prefs=false) {
1198         if (!$this->_prefs) {
1199             if ($prefs) $this->_prefs = $prefs;
1200             else _PassUser::_PassUser($UserName);
1201         }
1202         $this->_authmethod = 'Db';
1203         //$this->getAuthDbh();
1204         //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1205         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') {
1206             $this = new _AdoDbPassUser($UserName,$this->_prefs);
1207             return $this;
1208         }
1209         else {
1210             $this = new _PearDbPassUser($UserName,$this->_prefs);
1211             return $this;
1212         }
1213     }
1214
1215     function mayChangePass() {
1216         return !isset($this->_authupdate);
1217     }
1218
1219 }
1220
1221 class _PearDbPassUser
1222 extends _DbPassUser
1223 /**
1224  * Pear DB methods
1225  * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1226  * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1227  *
1228  * @tables: user
1229  * @tables: pref
1230  */
1231 {
1232     function _PearDbPassUser($UserName='',$prefs=false) {
1233         global $DBAuthParams;
1234         if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1235             if ($prefs) $this->_prefs = $prefs;
1236             else _PassUser::_PassUser($UserName);
1237         }
1238         $this->_userid = $UserName;
1239         // make use of session data. generally we only initialize this every time, 
1240         // but do auth checks only once
1241         $this->_auth_crypt_method = @$DBAuthParams['auth_crypt_method'];
1242         //$this->getAuthDbh();
1243         return $this;
1244     }
1245
1246     function getPreferences() {
1247         // override the generic slow method here for efficiency and not to 
1248         // clutter the homepage metadata with prefs.
1249         _AnonUser::getPreferences();
1250         $this->getAuthDbh();
1251         $dbh = &$this->_auth_dbi;
1252         if ((! $this->_prefs) and isset($this->_prefs->_select)) {
1253             $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1254             list($prefs_blob) = $db_result->fetchRow();
1255             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1256                 $this->_prefs = new UserPreferences($restored_from_db);
1257                 return $this->_prefs;
1258             }
1259         }
1260         if ((! $this->_prefs) && $this->_HomePagehandle) {
1261             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1262                 $this->_prefs = new UserPreferences($restored_from_page);
1263                 return $this->_prefs;
1264             }
1265         }
1266         return $this->_prefs;
1267     }
1268
1269     function setPreferences($prefs, $id_only=false) {
1270         // Encode only the _prefs array of the UserPreference object
1271         if (!is_object($prefs)) {
1272             $prefs = new UserPreferences($prefs);
1273         }
1274         // if the prefs are changed
1275         if (_AnonUser::setPreferences($prefs, 1)) {
1276             global $request;
1277             $packed = $prefs->store();
1278             // $unpacked = $prefs->unpack($packed);
1279             if (isset($this->_prefs->_method))
1280                 $prefs->_method = $this->_prefs->_method;
1281             if (isset($this->_prefs->_select))
1282                 $prefs->_select = $this->_prefs->_select;
1283             if (isset($this->_prefs->_update))
1284                 $prefs->_update = $this->_prefs->_update;
1285             $this->_prefs = $prefs;
1286             $request->_prefs =& $this->_prefs; 
1287             $request->_user->_prefs =& $this->_prefs; 
1288             //$request->setSessionVar('wiki_prefs', $this->_prefs);
1289             //We don't store the dbi chain. DB connections don't survive sessions.
1290             $user = $request->_user;
1291             unset($user->_auth_dbi);
1292             $request->setSessionVar('wiki_user', $user);
1293             if (isset($this->_prefs->_update)) {
1294                 $this->getAuthDbh();
1295                 $dbh = &$this->_auth_dbi;
1296                 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1297                                           $dbh->quote($packed),
1298                                           $dbh->quote($this->_userid)));
1299             } else {
1300                 //store prefs in homepage, not in cookie
1301                 if ($this->_HomePagehandle and !$id_only)
1302                     $this->_HomePagehandle->set('pref', $packed);
1303             }
1304             return count($prefs->unpack($packed));
1305         }
1306         return 0;
1307     }
1308
1309     function userExists() {
1310         global $DBAuthParams;
1311         $this->getAuthDbh();
1312         $dbh = &$this->_auth_dbi;
1313         // Prepare the configured auth statements
1314         if (!empty($DBAuthParams['auth_check']) and !$this->_authselect) {
1315             $this->_authselect = str_replace(array('"$userid"','"$password"'),
1316                                              array('%s','%s'),
1317                                              $DBAuthParams['auth_check']);
1318         }
1319         if (!$this->_authselect)
1320             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1321                           E_USER_WARNING);
1322         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1323         if ($this->_auth_crypt_method == 'crypt') {
1324             $rs = $dbh->query(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1325             if ($rs->numRows())
1326                 return true;
1327         }
1328         else {
1329             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1330                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1331                               E_USER_WARNING);
1332             $this->_authcheck = str_replace('"$userid"','%s',
1333                                              $DBAuthParams['auth_user_exists']);
1334             $rs = $dbh->query(sprintf($this->_authcheck,$dbh->quote($this->_userid)));
1335             if ($rs->numRows())
1336                 return true;
1337         }
1338         // maybe the user is allowed to create himself. Generally not wanted in 
1339         // external databases, but maybe wanted for the wiki database, for performance 
1340         // reasons
1341         if (!isset($this->_authcreate) and !empty($DBAuthParams['auth_create'])) {
1342             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1343                                               $DBAuthParams['auth_create']);
1344         }
1345         if ($this->_authcreate) return true;
1346
1347         return $this->_tryNextUser();
1348     }
1349  
1350     function checkPass($submitted_password) {
1351         global $DBAuthParams;
1352         $this->getAuthDbh();
1353         if (!$this->_authselect)
1354             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1355                           E_USER_WARNING);
1356
1357         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1358         $dbh = &$this->_auth_dbi;
1359         if ($this->_auth_crypt_method == 'crypt') {
1360             $stored_password = $dbh->getOne(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1361             $result = $this->_checkPass($submitted_password, $stored_password);
1362         } else {
1363             $okay = $dbh->getOne(sprintf($this->_authselect,
1364                                          $dbh->quote($submitted_password),
1365                                          $dbh->quote($this->_userid)));
1366             $result = !empty($okay);
1367         }
1368
1369         if ($result) {
1370             $this->_level = WIKIAUTH_USER;
1371             return $this->_level;
1372         } else {
1373             return $this->_tryNextPass($submitted_password);
1374         }
1375     }
1376
1377     function storePass($submitted_password) {
1378         global $DBAuthParams;
1379         $dbh = &$this->_auth_dbi;
1380         if (!empty($DBAuthParams['auth_update']) and !$this->_authupdate) {
1381             $this->_authupdate = str_replace(array('"$userid"','"$password"'),
1382                                              array('%s','%s'),
1383                                              $DBAuthParams['auth_update']);
1384         }
1385         if (!$this->_authupdate) {
1386             //CHECKME
1387             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1388                           E_USER_WARNING);
1389             return false;
1390         }
1391
1392         if ($this->_auth_crypt_method == 'crypt') {
1393             if (function_exists('crypt'))
1394                 $submitted_password = crypt($submitted_password);
1395         }
1396         $dbh->simpleQuery(sprintf($this->_authupdate,
1397                                   $dbh->quote($submitted_password),
1398                                   $dbh->quote($this->_userid)
1399                                   ));
1400     }
1401
1402 }
1403
1404 class _AdoDbPassUser
1405 extends _DbPassUser
1406 /**
1407  * ADODB methods
1408  * Simple sprintf, no prepare.
1409  *
1410  * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster 
1411  * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1412  *
1413  * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1414  *
1415  * @tables: user
1416  */
1417 {
1418     function _AdoDbPassUser($UserName='',$prefs=false) {
1419         if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1420             if ($prefs) $this->_prefs = $prefs;
1421             else _PassUser::_PassUser($UserName);
1422         }
1423         $this->_userid = $UserName;
1424         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1425         $this->getAuthDbh();
1426         // Don't prepare the configured auth statements anymore
1427         return $this;
1428     }
1429
1430     function getPreferences() {
1431         // override the generic slow method here for efficiency
1432         _AnonUser::getPreferences();
1433         //$this->getAuthDbh();
1434         if ((! $this->_prefs) and isset($this->_prefs->_select)) {
1435             $dbh = & $this->_auth_dbi;
1436             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
1437             if ($rs->EOF) {
1438                 $rs->Close();
1439             } else {
1440                 $prefs_blob = $rs->fields['pref_blob'];
1441                 $rs->Close();
1442                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1443                     $this->_prefs = new UserPreferences($restored_from_db);
1444                     return $this->_prefs;
1445                 }
1446             }
1447         }
1448         if ((! $this->_prefs) && $this->_HomePagehandle) {
1449             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1450                 $this->_prefs = new UserPreferences($restored_from_page);
1451                 return $this->_prefs;
1452             }
1453         }
1454         return $this->_prefs;
1455     }
1456
1457     function setPreferences($prefs, $id_only=false) {
1458         // Encode only the _prefs array of the UserPreference object
1459         if (!is_object($prefs)) {
1460             $prefs = new UserPreferences($prefs);
1461         }
1462         // if the prefs are changed
1463         if (_AnonUser::setPreferences($prefs, 1)) {
1464             global $request;
1465             $packed = $prefs->store();
1466             // $unpacked = $prefs->unpack($packed);
1467             
1468             if (isset($this->_prefs->_method))
1469                 $prefs->_method = $this->_prefs->_method;
1470             if (isset($this->_prefs->_select))
1471                 $prefs->_select = $this->_prefs->_select;
1472             if (isset($this->_prefs->_update))
1473                 $prefs->_update = $this->_prefs->_update;
1474             $this->_prefs = $prefs;
1475             $request->_prefs =& $this->_prefs; 
1476             $request->_user->_prefs =& $this->_prefs; 
1477             //$request->setSessionVar('wiki_prefs', $this->_prefs);
1478             //We don't store the dbi chain. DB connections don't survive sessions.
1479             $user = $request->_user;
1480             unset($user->_auth_dbi);
1481             $request->setSessionVar('wiki_user', $user);
1482             if (isset($this->_prefs->_update)) {
1483                 $this->getAuthDbh();
1484                 $dbh = &$this->_auth_dbi;
1485                 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1486                                                    $dbh->qstr($packed),
1487                                                    $dbh->qstr($this->_userid)));
1488                 $db_result->Close();
1489             } else {
1490                 //store prefs in homepage, not in cookie
1491                 if ($this->_HomePagehandle and !$id_only)
1492                     $this->_HomePagehandle->set('pref', $packed);
1493             }
1494             return count($prefs->unpack($packed));
1495         }
1496         return 0;
1497     }
1498  
1499     function userExists() {
1500         global $DBAuthParams;
1501         if (!$this->_authselect and !empty($DBAuthParams['auth_check'])) {
1502             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1503                                               $DBAuthParams['auth_check']);
1504         }
1505         if (!$this->_authselect)
1506             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1507                           E_USER_WARNING);
1508         //$this->getAuthDbh();
1509         $dbh = &$this->_auth_dbi;
1510         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1511         if ($this->_auth_crypt_method == 'crypt') {
1512             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1513             if (!$rs->EOF) {
1514                 $rs->Close();
1515                 return true;
1516             } else {
1517                 $rs->Close();
1518             }
1519         }
1520         else {
1521             if (! $DBAuthParams['auth_user_exists'])
1522                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1523                               E_USER_WARNING);
1524             $this->_authcheck = str_replace('"$userid"','%s',
1525                                              $DBAuthParams['auth_user_exists']);
1526             $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1527             if (!$rs->EOF) {
1528                 $rs->Close();
1529                 return true;
1530             } else {
1531                 $rs->Close();
1532             }
1533         }
1534         // maybe the user is allowed to create himself. Generally not wanted in 
1535         // external databases, but maybe wanted for the wiki database, for performance 
1536         // reasons
1537         if (!$this->_authcreate and !empty($DBAuthParams['auth_create'])) {
1538             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1539                                               $DBAuthParams['auth_create']);
1540         }
1541         if ($this->_authcreate) return true;
1542         
1543         return $this->_tryNextUser();
1544     }
1545
1546     function checkPass($submitted_password) {
1547         global $DBAuthParams;
1548         if (!$this->_authselect and !empty($DBAuthParams['auth_check'])) {
1549             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1550                                               $DBAuthParams['auth_check']);
1551         }
1552         if (!isset($this->_authselect))
1553             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1554                           E_USER_WARNING);
1555         //$this->getAuthDbh();
1556         $dbh = &$this->_auth_dbi;
1557         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1558         if ($this->_auth_crypt_method == 'crypt') {
1559             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1560             if (!$rs->EOF) {
1561                 $stored_password = $rs->fields['password'];
1562                 $rs->Close();
1563                 $result = $this->_checkPass($submitted_password, $stored_password);
1564             } else {
1565                 $rs->Close();
1566                 $result = false;
1567             }
1568         }
1569         else {
1570             $rs = $dbh->Execute(sprintf($this->_authselect,
1571                                         $dbh->qstr($submitted_password),
1572                                         $dbh->qstr($this->_userid)));
1573             $okay = $rs->fields['ok'];
1574             $rs->Close();
1575             $result = !empty($okay);
1576         }
1577
1578         if ($result) { 
1579             $this->_level = WIKIAUTH_USER;
1580             return $this->_level;
1581         } else {
1582             return $this->_tryNextPass($submitted_password);
1583         }
1584     }
1585
1586     function storePass($submitted_password) {
1587         global $DBAuthParams;
1588         if (!isset($this->_authupdate) and !empty($DBAuthParams['auth_update'])) {
1589             $this->_authupdate = str_replace(array('"$userid"','"$password"'),array("%s","%s"),
1590                                               $DBAuthParams['auth_update']);
1591         }
1592         if (!isset($this->_authupdate)) {
1593             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1594                           E_USER_WARNING);
1595             return false;
1596         }
1597
1598         if ($this->_auth_crypt_method == 'crypt') {
1599             if (function_exists('crypt'))
1600                 $submitted_password = crypt($submitted_password);
1601         }
1602         $this->getAuthDbh();
1603         $dbh = &$this->_auth_dbi;
1604         $rs = $dbh->Execute(sprintf($this->_authupdate,
1605                                     $dbh->qstr($submitted_password),
1606                                     $dbh->qstr($this->_userid)
1607                                     ));
1608         $rs->Close();
1609     }
1610
1611 }
1612
1613 class _LDAPPassUser
1614 extends _PassUser
1615 /**
1616  * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in index.php
1617  *
1618  * Preferences are handled in _PassUser
1619  */
1620 {
1621     function checkPass($submitted_password) {
1622         global $LDAP_SET_OPTION;
1623
1624         $this->_authmethod = 'LDAP';
1625         $userid = $this->_userid;
1626         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1627             if (defined('LDAP_AUTH_USER'))
1628                 if (defined('LDAP_AUTH_PASSWORD'))
1629                     // Windows Active Directory Server is strict
1630                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1631                 else
1632                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1633             else
1634                 $r = @ldap_bind($ldap); // this is an anonymous bind
1635             if (!empty($LDAP_SET_OPTION)) {
1636                 foreach ($LDAP_SET_OPTION as $key => $value) {
1637                     ldap_set_option($ldap,$key,$value);
1638                 }
1639             }
1640             // Need to set the right root search information. see ../index.php
1641             $st_search = defined('LDAP_SEARCH_FIELD') 
1642                 ? LDAP_SEARCH_FIELD."=$userid"
1643                 : "uid=$userid";
1644             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1645             $info = ldap_get_entries($ldap, $sr); 
1646             // there may be more hits with this userid.
1647             // of course it would be better to narrow down the BASE_DN
1648             for ($i = 0; $i < $info["count"]; $i++) {
1649                 $dn = $info[$i]["dn"];
1650                 // The password is still plain text.
1651                 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
1652                     // ldap_bind will return TRUE if everything matches
1653                     ldap_close($ldap);
1654                     $this->_level = WIKIAUTH_USER;
1655                     return $this->_level;
1656                 }
1657             }
1658         } else {
1659             trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), 
1660                           E_USER_WARNING);
1661             //return false;
1662         }
1663
1664         return $this->_tryNextPass($submitted_password);
1665     }
1666
1667     function userExists() {
1668         global $LDAP_SET_OPTION;
1669
1670         $userid = $this->_userid;
1671         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1672             if (defined('LDAP_AUTH_USER'))
1673                 if (defined('LDAP_AUTH_PASSWORD'))
1674                     // Windows Active Directory Server is strict
1675                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1676                 else
1677                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1678             else
1679                 $r = @ldap_bind($ldap); // this is an anonymous bind
1680             if (!empty($LDAP_SET_OPTION)) {
1681                 foreach ($LDAP_SET_OPTION as $key => $value) {
1682                     ldap_set_option($ldap,$key,$value);
1683                 }
1684             }
1685             // Need to set the right root search information. see ../index.php
1686             $st_search = defined('LDAP_SEARCH_FIELD') 
1687                 ? LDAP_SEARCH_FIELD."=$userid"
1688                 : "uid=$userid";
1689             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1690             $info = ldap_get_entries($ldap, $sr); 
1691
1692             if ($info["count"] > 0) {
1693                 ldap_close($ldap);
1694                 return true;
1695             }
1696         } else {
1697             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1698         }
1699
1700         return $this->_tryNextUser();
1701     }
1702
1703     function mayChangePass() {
1704         return false;
1705     }
1706
1707 }
1708
1709 class _IMAPPassUser
1710 extends _PassUser
1711 /**
1712  * Define the var IMAP_AUTH_HOST in index.php (with port probably)
1713  *
1714  * Preferences are handled in _PassUser
1715  */
1716 {
1717     function checkPass($submitted_password) {
1718         $userid = $this->_userid;
1719         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1720                             $userid, $submitted_password, OP_HALFOPEN );
1721         if ($mbox) {
1722             imap_close($mbox);
1723             $this->_authmethod = 'IMAP';
1724             $this->_level = WIKIAUTH_USER;
1725             return $this->_level;
1726         } else {
1727             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1728         }
1729
1730         return $this->_tryNextPass($submitted_password);
1731     }
1732
1733     //CHECKME: this will not be okay for the auth policy strict
1734     function userExists() {
1735         return true;
1736         if (checkPass($this->_prefs->get('passwd')))
1737             return true;
1738             
1739         return $this->_tryNextUser();
1740     }
1741
1742     function mayChangePass() {
1743         return false;
1744     }
1745 }
1746
1747
1748 class _POP3PassUser
1749 extends _IMAPPassUser {
1750 /**
1751  * Define the var POP3_AUTH_HOST in index.php
1752  * Preferences are handled in _PassUser
1753  */
1754     function checkPass($submitted_password) {
1755         $userid = $this->_userid;
1756         $pass = $submitted_password;
1757         $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost';
1758         $port = defined('POP3_AUTH_PORT') ? POP3_AUTH_PORT : 110;
1759         $retval = false;
1760         $fp = fsockopen($host, $port, $errno, $errstr, 10);
1761         if ($fp) {
1762             // Get welcome string
1763             $line = fgets($fp, 1024);
1764             if (! strncmp("+OK ", $line, 4)) {
1765                 // Send user name
1766                 fputs($fp, "user $user\n");
1767                 // Get response
1768                 $line = fgets($fp, 1024);
1769                 if (! strncmp("+OK ", $line, 4)) {
1770                     // Send password
1771                     fputs($fp, "pass $pass\n");
1772                     // Get response
1773                     $line = fgets($fp, 1024);
1774                     if (! strncmp("+OK ", $line, 4)) {
1775                         $retval = true;
1776                     }
1777                 }
1778             }
1779             // quit the connection
1780             fputs($fp, "quit\n");
1781             // Get the sayonara message
1782             $line = fgets($fp, 1024);
1783             fclose($fp);
1784         }
1785         $this->_authmethod = 'POP3';
1786         if ($retval) {
1787             $this->_level = WIKIAUTH_USER;
1788         } else {
1789             $this->_level = WIKIAUTH_ANON;
1790         }
1791         return $this->_level;
1792     }
1793 }
1794
1795 class _FilePassUser
1796 extends _PassUser
1797 /**
1798  * Check users defined in a .htaccess style file
1799  * username:crypt\n...
1800  *
1801  * Preferences are handled in _PassUser
1802  */
1803 {
1804     var $_file, $_may_change;
1805
1806     // This can only be called from _PassUser, because the parent class 
1807     // sets the pref methods, before this class is initialized.
1808     function _FilePassUser($UserName='',$file='') {
1809         if (!$this->_prefs)
1810             _PassUser::_PassUser($UserName);
1811
1812         // read the .htaccess style file. We use our own copy of the standard pear class.
1813         include_once 'lib/pear/File_Passwd.php';
1814         // if passwords may be changed we have to lock them:
1815         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1816         if (empty($file) and defined('AUTH_USER_FILE'))
1817             $this->_file = new File_Passwd(AUTH_USER_FILE, !empty($this->_may_change));
1818         elseif (!empty($file))
1819             $this->_file = new File_Passwd($file, !empty($this->_may_change));
1820         else
1821             return false;
1822         return $this;
1823     }
1824  
1825     function mayChangePass() {
1826         return $this->_may_change;
1827     }
1828
1829     function userExists() {
1830         if (isset($this->_file->users[$this->_userid]))
1831             return true;
1832             
1833         return $this->_tryNextUser();
1834     }
1835
1836     function checkPass($submitted_password) {
1837         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1838             $this->_authmethod = 'File';
1839             $this->_level = WIKIAUTH_USER;
1840             return $this->_level;
1841         }
1842         
1843         return $this->_tryNextPass($submitted_password);
1844     }
1845
1846     function storePass($submitted_password) {
1847         if ($this->_may_change)
1848             return $this->_file->modUser($this->_userid,$submitted_password);
1849         else 
1850             return false;
1851     }
1852
1853 }
1854
1855 /**
1856  * Insert more auth classes here...
1857  * For example a customized db class for another db connection 
1858  * or a socket-based auth server
1859  *
1860  */
1861
1862
1863 /**
1864  * For security, this class should not be extended. Instead, extend
1865  * from _PassUser (think of this as unix "root").
1866  */
1867 class _AdminUser
1868 extends _PassUser
1869 {
1870     function checkPass($submitted_password) {
1871         $stored_password = ADMIN_PASSWD;
1872         if ($this->_checkPass($submitted_password, $stored_password)) {
1873             $this->_level = WIKIAUTH_ADMIN;
1874             return $this->_level;
1875         } else {
1876             $this->_level = WIKIAUTH_ANON;
1877             return $this->_level;
1878         }
1879     }
1880
1881 }
1882
1883 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1884 /**
1885  * Various data classes for the preference types, 
1886  * to support get, set, sanify (range checking, ...)
1887  * update() will do the neccessary side-effects if a 
1888  * setting gets changed (theme, language, ...)
1889 */
1890
1891 class _UserPreference
1892 {
1893     var $default_value;
1894
1895     function _UserPreference ($default_value) {
1896         $this->default_value = $default_value;
1897     }
1898
1899     function sanify ($value) {
1900         return (string)$value;
1901     }
1902
1903     function get ($name) {
1904         if (isset($this->{$name}))
1905             return $this->{$name};
1906         else 
1907             return $this->default_value;
1908     }
1909
1910     function getraw ($name) {
1911         if (!empty($this->{$name}))
1912             return $this->{$name};
1913     }
1914
1915     // stores the value as $this->$name, and not as $this->value (clever?)
1916     function set ($name, $value) {
1917         if ($this->get($name) != $value) {
1918             $this->update($value);
1919         }
1920         if ($value != $this->default_value) {
1921             $this->{$name} = $value;
1922         }
1923         else 
1924             unset($this->{$name});
1925     }
1926
1927     // default: no side-effects 
1928     function update ($value) {
1929         ;
1930     }
1931 }
1932
1933 class _UserPreference_numeric
1934 extends _UserPreference
1935 {
1936     function _UserPreference_numeric ($default, $minval = false,
1937                                       $maxval = false) {
1938         $this->_UserPreference((double)$default);
1939         $this->_minval = (double)$minval;
1940         $this->_maxval = (double)$maxval;
1941     }
1942
1943     function sanify ($value) {
1944         $value = (double)$value;
1945         if ($this->_minval !== false && $value < $this->_minval)
1946             $value = $this->_minval;
1947         if ($this->_maxval !== false && $value > $this->_maxval)
1948             $value = $this->_maxval;
1949         return $value;
1950     }
1951 }
1952
1953 class _UserPreference_int
1954 extends _UserPreference_numeric
1955 {
1956     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1957         $this->_UserPreference_numeric((int)$default, (int)$minval,
1958                                        (int)$maxval);
1959     }
1960
1961     function sanify ($value) {
1962         return (int)parent::sanify((int)$value);
1963     }
1964 }
1965
1966 class _UserPreference_bool
1967 extends _UserPreference
1968 {
1969     function _UserPreference_bool ($default = false) {
1970         $this->_UserPreference((bool)$default);
1971     }
1972
1973     function sanify ($value) {
1974         if (is_array($value)) {
1975             /* This allows for constructs like:
1976              *
1977              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1978              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1979              *
1980              * (If the checkbox is not checked, only the hidden input
1981              * gets sent. If the checkbox is sent, both inputs get
1982              * sent.)
1983              */
1984             foreach ($value as $val) {
1985                 if ($val)
1986                     return true;
1987             }
1988             return false;
1989         }
1990         return (bool) $value;
1991     }
1992 }
1993
1994 class _UserPreference_language
1995 extends _UserPreference
1996 {
1997     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1998         $this->_UserPreference($default);
1999     }
2000
2001     // FIXME: check for valid locale
2002     function sanify ($value) {
2003         // Revert to DEFAULT_LANGUAGE if user does not specify
2004         // language in UserPreferences or chooses <system language>.
2005         if ($value == '' or empty($value))
2006             $value = DEFAULT_LANGUAGE;
2007
2008         return (string) $value;
2009     }
2010 }
2011
2012 class _UserPreference_theme
2013 extends _UserPreference
2014 {
2015     function _UserPreference_theme ($default = THEME) {
2016         $this->_UserPreference($default);
2017     }
2018
2019     function sanify ($value) {
2020         if (FindFile($this->_themefile($value)))
2021             return $value;
2022         return $this->default_value;
2023     }
2024
2025     function update ($newvalue) {
2026         global $Theme;
2027         if ($newvalue)
2028             include_once($this->_themefile($newvalue));
2029         if (empty($Theme))
2030             include_once($this->_themefile(THEME));
2031     }
2032
2033     function _themefile ($theme) {
2034         return "themes/$theme/themeinfo.php";
2035     }
2036 }
2037
2038 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2039
2040 /**
2041  * UserPreferences
2042  * 
2043  * This object holds the $request->_prefs subobjects.
2044  * A simple packed array of non-default values get's stored as cookie,
2045  * homepage, or database, which are converted to the array of 
2046  * ->_prefs objects.
2047  * We don't store the objects, because otherwise we will
2048  * not be able to upgrade any subobject. And it's a waste of space also.
2049  *
2050  */
2051 class UserPreferences
2052 {
2053     function UserPreferences ($saved_prefs = false) {
2054         // userid stored too, to ensure the prefs are being loaded for
2055         // the correct (currently signing in) userid if stored in a
2056         // cookie.
2057         $this->_prefs
2058             = array(
2059                     'userid'        => new _UserPreference(''),
2060                     'passwd'        => new _UserPreference(''),
2061                     'autologin'     => new _UserPreference_bool(),
2062                     'email'         => new _UserPreference(''),
2063                     'emailVerified' => new _UserPreference_bool(),
2064                     'notifyPages'   => new _UserPreference(''),
2065                     'theme'         => new _UserPreference_theme(THEME),
2066                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
2067                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2068                                                                EDITWIDTH_MIN_COLS,
2069                                                                EDITWIDTH_MAX_COLS),
2070                     'noLinkIcons'   => new _UserPreference_bool(),
2071                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2072                                                                EDITHEIGHT_MIN_ROWS,
2073                                                                EDITHEIGHT_DEFAULT_ROWS),
2074                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2075                                                                    TIMEOFFSET_MIN_HOURS,
2076                                                                    TIMEOFFSET_MAX_HOURS),
2077                     'relativeDates' => new _UserPreference_bool()
2078                     );
2079
2080         if (is_array($saved_prefs)) {
2081             foreach ($saved_prefs as $name => $value)
2082                 $this->set($name, $value);
2083         }
2084     }
2085
2086     function _getPref ($name) {
2087         if (!isset($this->_prefs[$name])) {
2088             if ($name == 'passwd2') return false;
2089             trigger_error("$name: unknown preference", E_USER_NOTICE);
2090             return false;
2091         }
2092         return $this->_prefs[$name];
2093     }
2094     
2095     // get the value or default_value of the subobject
2096     function get ($name) {
2097         if ($_pref = $this->_getPref($name))
2098           return $_pref->get($name);
2099         else 
2100           return false;  
2101         /*      
2102         if (is_object($this->_prefs[$name]))
2103             return $this->_prefs[$name]->get($name);
2104         elseif (($value = $this->_getPref($name)) === false)
2105             return false;
2106         elseif (!isset($value))
2107             return $this->_prefs[$name]->default_value;
2108         else return $value;
2109         */
2110     }
2111
2112     // check and set the new value in the subobject
2113     function set ($name, $value) {
2114         $pref = $this->_getPref($name);
2115         if ($pref === false)
2116             return false;
2117
2118         /* do it here or outside? */
2119         if ($name == 'passwd' and 
2120             defined('PASSWORD_LENGTH_MINIMUM') and 
2121             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2122             //TODO: How to notify the user?
2123             return false;
2124         }
2125         if ($name == 'theme' and $value == '')
2126            return true;
2127         $newvalue = $pref->sanify($value);
2128         $pref->set($name,$newvalue);
2129         $this->_prefs[$name] = $pref;
2130         return true;
2131
2132         // don't set default values to save space (in cookies, db and
2133         // sesssion)
2134         /*
2135         if ($value == $pref->default_value)
2136             unset($this->_prefs[$name]);
2137         else
2138             $this->_prefs[$name] = $pref;
2139         */
2140     }
2141
2142     // for now convert just array of objects => array of values
2143     // Todo: the specialized subobjects must override this.
2144     function store() {
2145         $prefs = array();
2146         foreach ($this->_prefs as $name => $object) {
2147             if ($value = $object->getraw($name))
2148                 $prefs[] = array($name => $value);
2149         }
2150         return $this->pack($prefs);
2151     }
2152
2153     // packed string or array of values => array of values
2154     // Todo: the specialized subobjects must override this.
2155     function retrieve($packed) {
2156         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2157             $packed = unserialize($packed);
2158         if (!is_array($packed)) return false;
2159         $prefs = array();
2160         foreach ($packed as $name => $packed_pref) {
2161             if (substr($packed_pref, 0, 2) == "O:") {
2162                 //legacy: check if it's an old array of objects
2163                 // Looks like a serialized object. 
2164                 // This might fail if the object definition does not exist anymore.
2165                 // object with ->$name and ->default_value vars.
2166                 $pref = unserialize($packed_pref);
2167                 $prefs[$name] = $pref->get($name);
2168             } else {
2169                 $prefs[$name] = unserialize($packed_pref);
2170             }
2171         }
2172         return $prefs;
2173     }
2174
2175     /**
2176      * Check if the given prefs object is different from the current prefs object
2177      */
2178     function isChanged($other) {
2179         foreach ($this->_prefs as $type => $obj) {
2180             if ($obj->get($type) !== $other->get($type))
2181                 return true;
2182         }
2183         return false;
2184     }
2185
2186     // array of objects
2187     function getAll() {
2188         return $this->_prefs;
2189     }
2190
2191     function pack($nonpacked) {
2192         return serialize($nonpacked);
2193     }
2194
2195     function unpack($packed) {
2196         if (!$packed)
2197             return false;
2198         //$packed = base64_decode($packed);
2199         if (substr($packed, 0, 2) == "O:") {
2200             // Looks like a serialized object
2201             return unserialize($packed);
2202         }
2203         if (substr($packed, 0, 2) == "a:") {
2204             return unserialize($packed);
2205         }
2206         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2207         //E_USER_WARNING);
2208         return false;
2209     }
2210
2211     function hash () {
2212         return hash($this->_prefs);
2213     }
2214 }
2215
2216 class CookieUserPreferences
2217 extends UserPreferences
2218 {
2219     function CookieUserPreferences ($saved_prefs = false) {
2220         //_AnonUser::_AnonUser('',$saved_prefs);
2221         UserPreferences::UserPreferences($saved_prefs);
2222     }
2223 }
2224
2225 class PageUserPreferences
2226 extends UserPreferences
2227 {
2228     function PageUserPreferences ($saved_prefs = false) {
2229         UserPreferences::UserPreferences($saved_prefs);
2230     }
2231 }
2232
2233 class PearDbUserPreferences
2234 extends UserPreferences
2235 {
2236     function PearDbUserPreferences ($saved_prefs = false) {
2237         UserPreferences::UserPreferences($saved_prefs);
2238     }
2239 }
2240
2241 class AdoDbUserPreferences
2242 extends UserPreferences
2243 {
2244     function AdoDbUserPreferences ($saved_prefs = false) {
2245         UserPreferences::UserPreferences($saved_prefs);
2246     }
2247     function getPreferences() {
2248         // override the generic slow method here for efficiency
2249         _AnonUser::getPreferences();
2250         $this->getAuthDbh();
2251         if ((! $this->_prefs) and isset($this->_prefs->_select)) {
2252             $dbh = & $this->_auth_dbi;
2253             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
2254             if ($rs->EOF) {
2255                 $rs->Close();
2256             } else {
2257                 $prefs_blob = $rs->fields['pref_blob'];
2258                 $rs->Close();
2259                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2260                     $this->_prefs = new UserPreferences($restored_from_db);
2261                     return $this->_prefs;
2262                 }
2263             }
2264         }
2265         if ((! $this->_prefs) && $this->_HomePagehandle) {
2266             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2267                 $this->_prefs = new UserPreferences($restored_from_page);
2268                 return $this->_prefs;
2269             }
2270         }
2271         return $this->_prefs;
2272     }
2273 }
2274
2275
2276 // $Log: not supported by cvs2svn $
2277 // Revision 1.29  2004/03/11 13:30:47  rurban
2278 // fixed File Auth for user and group
2279 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
2280 //
2281 // Revision 1.28  2004/03/08 18:17:09  rurban
2282 // added more WikiGroup::getMembersOf methods, esp. for special groups
2283 // fixed $LDAP_SET_OPTIONS
2284 // fixed _AuthInfo group methods
2285 //
2286 // Revision 1.27  2004/03/01 09:35:13  rurban
2287 // fixed DbPassuser pref init; lost userid
2288 //
2289 // Revision 1.26  2004/02/29 04:10:56  rurban
2290 // new POP3 auth (thanks to BiloBilo: pentothal at despammed dot com)
2291 // fixed syntax error in index.php
2292 //
2293 // Revision 1.25  2004/02/28 22:25:07  rurban
2294 // First PagePerm implementation:
2295 //
2296 // $Theme->setAnonEditUnknownLinks(false);
2297 //
2298 // Layout improvement with dangling links for mostly closed wiki's:
2299 // If false, only users with edit permissions will be presented the
2300 // special wikiunknown class with "?" and Tooltip.
2301 // If true (default), any user will see the ?, but will be presented
2302 // the PrintLoginForm on a click.
2303 //
2304 // Revision 1.24  2004/02/28 21:14:08  rurban
2305 // generally more PHPDOC docs
2306 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2307 // fxied WikiUserNew pref handling: empty theme not stored, save only
2308 //   changed prefs, sql prefs improved, fixed password update,
2309 //   removed REPLACE sql (dangerous)
2310 // moved gettext init after the locale was guessed
2311 // + some minor changes
2312 //
2313 // Revision 1.23  2004/02/27 13:21:17  rurban
2314 // several performance improvements, esp. with peardb
2315 // simplified loops
2316 // storepass seperated from prefs if defined so
2317 // stacked and strict still not working
2318 //
2319 // Revision 1.22  2004/02/27 05:15:40  rurban
2320 // more stability. detected by Micki
2321 //
2322 // Revision 1.21  2004/02/26 20:43:49  rurban
2323 // new HttpAuthPassUser class (forces http auth if in the auth loop)
2324 // fixed user upgrade: don't return _PassUser in the first hand.
2325 //
2326 // Revision 1.20  2004/02/26 01:29:11  rurban
2327 // important fixes: endless loops in certain cases. minor rewrite
2328 //
2329 // Revision 1.19  2004/02/25 17:15:17  rurban
2330 // improve stability
2331 //
2332 // Revision 1.18  2004/02/24 15:20:05  rurban
2333 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
2334 //
2335 // Revision 1.17  2004/02/17 12:16:42  rurban
2336 // started with changePass support. not yet used.
2337 //
2338 // Revision 1.16  2004/02/15 22:23:45  rurban
2339 // oops, fixed showstopper (endless recursion)
2340 //
2341 // Revision 1.15  2004/02/15 21:34:37  rurban
2342 // PageList enhanced and improved.
2343 // fixed new WikiAdmin... plugins
2344 // editpage, Theme with exp. htmlarea framework
2345 //   (htmlarea yet committed, this is really questionable)
2346 // WikiUser... code with better session handling for prefs
2347 // enhanced UserPreferences (again)
2348 // RecentChanges for show_deleted: how should pages be deleted then?
2349 //
2350 // Revision 1.14  2004/02/15 17:30:13  rurban
2351 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
2352 // fixed getPreferences() (esp. from sessions)
2353 // fixed setPreferences() (update and set),
2354 // fixed AdoDb DB statements,
2355 // update prefs only at UserPreferences POST (for testing)
2356 // unified db prefs methods (but in external pref classes yet)
2357 //
2358 // Revision 1.13  2004/02/09 03:58:12  rurban
2359 // for now default DB_SESSION to false
2360 // PagePerm:
2361 //   * not existing perms will now query the parent, and not
2362 //     return the default perm
2363 //   * added pagePermissions func which returns the object per page
2364 //   * added getAccessDescription
2365 // WikiUserNew:
2366 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
2367 //   * force init of authdbh in the 2 db classes
2368 // main:
2369 //   * fixed session handling (not triple auth request anymore)
2370 //   * don't store cookie prefs with sessions
2371 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
2372 //
2373 // Revision 1.12  2004/02/07 10:41:25  rurban
2374 // fixed auth from session (still double code but works)
2375 // fixed GroupDB
2376 // fixed DbPassUser upgrade and policy=old
2377 // added GroupLdap
2378 //
2379 // Revision 1.11  2004/02/03 09:45:39  rurban
2380 // LDAP cleanup, start of new Pref classes
2381 //
2382 // Revision 1.10  2004/02/01 09:14:11  rurban
2383 // Started with Group_Ldap (not yet ready)
2384 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
2385 // fixed some configurator vars
2386 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
2387 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
2388 // USE_DB_SESSION defaults to true on SQL
2389 // changed GROUP_METHOD definition to string, not constants
2390 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
2391 //   create users. (Not to be used with external databases generally, but
2392 //   with the default internal user table)
2393 //
2394 // fixed the IndexAsConfigProblem logic. this was flawed:
2395 //   scripts which are the same virtual path defined their own lib/main call
2396 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
2397 //
2398 // Revision 1.9  2004/01/30 19:57:58  rurban
2399 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
2400 //
2401 // Revision 1.8  2004/01/30 18:46:15  rurban
2402 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
2403 //
2404 // Revision 1.7  2004/01/27 23:23:39  rurban
2405 // renamed ->Username => _userid for consistency
2406 // renamed mayCheckPassword => mayCheckPass
2407 // fixed recursion problem in WikiUserNew
2408 // fixed bogo login (but not quite 100% ready yet, password storage)
2409 //
2410 // Revision 1.6  2004/01/26 09:17:49  rurban
2411 // * changed stored pref representation as before.
2412 //   the array of objects is 1) bigger and 2)
2413 //   less portable. If we would import packed pref
2414 //   objects and the object definition was changed, PHP would fail.
2415 //   This doesn't happen with an simple array of non-default values.
2416 // * use $prefs->retrieve and $prefs->store methods, where retrieve
2417 //   understands the interim format of array of objects also.
2418 // * simplified $prefs->get() and fixed $prefs->set()
2419 // * added $user->_userid and class '_WikiUser' portability functions
2420 // * fixed $user object ->_level upgrading, mostly using sessions.
2421 //   this fixes yesterdays problems with loosing authorization level.
2422 // * fixed WikiUserNew::checkPass to return the _level
2423 // * fixed WikiUserNew::isSignedIn
2424 // * added explodePageList to class PageList, support sortby arg
2425 // * fixed UserPreferences for WikiUserNew
2426 // * fixed WikiPlugin for empty defaults array
2427 // * UnfoldSubpages: added pagename arg, renamed pages arg,
2428 //   removed sort arg, support sortby arg
2429 //
2430 // Revision 1.5  2004/01/25 03:05:00  rurban
2431 // First working version, but has some problems with the current main loop.
2432 // Implemented new auth method dispatcher and policies, all the external
2433 // _PassUser classes (also for ADODB and Pear DB).
2434 // The two global funcs UserExists() and CheckPass() are probably not needed,
2435 // since the auth loop is done recursively inside the class code, upgrading
2436 // the user class within itself.
2437 // Note: When a higher user class is returned, this doesn't mean that the user
2438 // is authorized, $user->_level is still low, and only upgraded on successful
2439 // login.
2440 //
2441 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
2442 // Code Housecleaning: fixed syntax errors. (php -l *.php)
2443 //
2444 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
2445 // Finished off logic for determining user class, including
2446 // PassUser. Removed ability of BogoUser to save prefs into a page.
2447 //
2448 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
2449 // Added admin user, password user, and preference classes. Added
2450 // password checking functions for users and the admin. (Now the easy
2451 // parts are nearly done).
2452 //
2453 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
2454 // Complete rewrite of WikiUser.php.
2455 //
2456 // This should make it easier to hook in user permission groups etc. some
2457 // time in the future. Most importantly, to finally get UserPreferences
2458 // fully working properly for all classes of users: AnonUser, BogoUser,
2459 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
2460 // want a cookie or not, and to bring back optional AutoLogin with the
2461 // UserName stored in a cookie--something that was lost after PhpWiki had
2462 // dropped the default http auth login method.
2463 //
2464 // Added WikiUser classes which will (almost) work together with existing
2465 // UserPreferences class. Other parts of PhpWiki need to be updated yet
2466 // before this code can be hooked up.
2467 //
2468
2469 // Local Variables:
2470 // mode: php
2471 // tab-width: 8
2472 // c-basic-offset: 4
2473 // c-hanging-comment-ender-p: nil
2474 // indent-tabs-mode: nil
2475 // End:
2476 ?>