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