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