]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
Prevent from some PHP5 warnings (ref args, no :: object init)
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.57 2004-04-19 18:27:45 rurban Exp $');
3 /* Copyright (C) 2004 $ThePhpWikiProgrammingTeam
4  *
5  * This file is part of PhpWiki.
6  * 
7  * PhpWiki is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  * 
12  * PhpWiki is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with PhpWiki; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21 /**
22  * This is a complete OOP rewrite of the old WikiUser code with various
23  * configurable external authentication methods.
24  *
25  * There's only one entry point, the function WikiUser which returns 
26  * a WikiUser object, which contains the user's preferences.
27  * This object might get upgraded during the login step and later also.
28  * There exist three preferences storage methods: cookie, homepage and db,
29  * and multiple password checking methods.
30  * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if 
31  * ALLOW_USER_PASSWORDS is defined.
32  *
33  * Each user object must define the two preferences methods 
34  *  getPreferences(), setPreferences(), 
35  * and the following 1-4 auth methods
36  *  checkPass()  must be defined by all classes,
37  *  userExists() only if USER_AUTH_POLICY'=='strict' 
38  *  mayChangePass()  only if the password is storable.
39  *  storePass()  only if the password is storable.
40  *
41  * WikiUser() given no name, returns an _AnonUser (anonymous user)
42  * object, who may or may not have a cookie. 
43  * However, if the there's a cookie with the userid or a session, 
44  * the user is upgraded to the matching user object.
45  * Given a user name, returns a _BogoUser object, who may or may not 
46  * have a cookie and/or PersonalPage, one of the various _PassUser objects 
47  * or an _AdminUser object.
48  * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might 
49  * have stored a password or not. If so, his account is secure, if not
50  * anybody can use it, because the username is visible e.g. in RecentChanges.
51  *
52  * Takes care of passwords, all preference loading/storing in the
53  * user's page and any cookies. lib/main.php will query the user object to
54  * verify the password as appropriate.
55  *
56  * @author: Reini Urban (the tricky parts), 
57  *          Carsten Klapp (started rolling the ball)
58  *
59  * Random architectural notes, sorted by date:
60  * 2004-01-25 rurban
61  * Test it by defining ENABLE_USER_NEW in index.php
62  * 1) Now a ForbiddenUser is returned instead of false.
63  * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, 
64  *    but may browse. Now with ALLOW_ANON_USER = false he may not browse, 
65  *    which is needed to disable browse PagePermissions.
66  *    I added now ALLOW_ANON_EDIT = true to makes things clear. 
67  *    (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
68  * 2004-02-27 rurban:
69  * 3) Removed pear prepare. Performance hog, and using integers as 
70  *    handler doesn't help. Do simple sprintf as with adodb. And a prepare
71  *    in the object init is no advantage, because in the init loop a lot of 
72  *    objects are tried, but not used.
73  * 4) Already gotten prefs are passed to the next object to avoid 
74  *    duplicate getPreferences() calls.
75  * 2004-03-18 rurban
76  * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
77  *    So we cannot just discrimate with 
78  *      if (!check_php_version(5))
79  *          $this = $user;
80  *    A /php5-patch.php is provided, which patches the src automatically 
81  *    for php4 and php5. Default is php4.
82  * 2004-03-24 rurban
83  * 6) enforced new cookie policy: prefs don't get stored in cookies
84  *    anymore, only in homepage and/or database, but always in the 
85  *    current session. old pref cookies will get deleted.
86  * 2004-04-04 rurban
87  * 7) Certain themes should be able to extend the predefined list 
88  *    of preferences. Display/editing is done in the theme specific userprefs.tmpl,
89  *    but storage must be extended to the Get/SetPreferences methods.
90  *    <theme>/themeinfo.php must provide CustomUserPreferences:
91  *      A list of name => _UserPreference class pairs.
92  */
93
94 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
95 define('WIKIAUTH_ANON', 0);       // Not signed in.
96 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
97 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
98 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
99
100 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
101 if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
102
103 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
104 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
105 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
106
107 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
108 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
109 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
110
111 define('TIMEOFFSET_MIN_HOURS', -26);
112 define('TIMEOFFSET_MAX_HOURS',  26);
113 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
114
115 /**
116  * There are be the following constants in index.php to 
117  * establish login parameters:
118  *
119  * ALLOW_ANON_USER         default true
120  * ALLOW_ANON_EDIT         default true
121  * ALLOW_BOGO_LOGIN        default true
122  * ALLOW_USER_PASSWORDS    default true
123  * PASSWORD_LENGTH_MINIMUM default 6 ?
124  *
125  * To require user passwords for editing:
126  * ALLOW_ANON_USER  = true
127  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
128  * ALLOW_BOGO_LOGIN = false
129  * ALLOW_USER_PASSWORDS = true
130  *
131  * To establish a COMPLETELY private wiki, such as an internal
132  * corporate one:
133  * ALLOW_ANON_USER = false
134  * (and probably require user passwords as described above). In this
135  * case the user will be prompted to login immediately upon accessing
136  * any page.
137  *
138  * There are other possible combinations, but the typical wiki (such
139  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four 
140  * enabled.
141  *
142  */
143
144 // The last object in the row is the bad guy...
145 if (!is_array($USER_AUTH_ORDER))
146     $USER_AUTH_ORDER = array("Forbidden");
147 else
148     $USER_AUTH_ORDER[] = "Forbidden";
149
150 // Local convenience functions.
151 function _isAnonUserAllowed() {
152     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
153 }
154 function _isBogoUserAllowed() {
155     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
156 }
157 function _isUserPasswordsAllowed() {
158     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
159 }
160
161 // Possibly upgrade userobject functions.
162 function _determineAdminUserOrOtherUser($UserName) {
163     // Sanity check. User name is a condition of the definition of the
164     // _AdminUser, _BogoUser and _passuser.
165     if (!$UserName)
166         return $GLOBALS['ForbiddenUser'];
167
168     if ($UserName == ADMIN_USER)
169         return new _AdminUser($UserName);
170     else
171         return _determineBogoUserOrPassUser($UserName);
172 }
173
174 function _determineBogoUserOrPassUser($UserName) {
175     global $ForbiddenUser;
176
177     // Sanity check. User name is a condition of the definition of
178     // _BogoUser and _PassUser.
179     if (!$UserName)
180         return $ForbiddenUser;
181
182     // Check for password and possibly upgrade user object.
183     // $_BogoUser = new _BogoUser($UserName);
184     if (_isBogoUserAllowed()) {
185         $_BogoUser = new _BogoLoginPassUser($UserName);
186         if ($_BogoUser->userExists())
187             return $_BogoUser;
188     }
189     if (_isUserPasswordsAllowed()) {
190         // PassUsers override BogoUsers if a password is stored
191         if (isset($_BogoUser) and $_BogoUser->_prefs->get('passwd'))
192             return new _PassUser($UserName,$_BogoUser->_prefs);
193         else { 
194             $_PassUser = new _PassUser($UserName,isset($_BogoUser) ? $_BogoUser->_prefs : false);
195             if ($_PassUser->userExists())
196                 return $_PassUser;
197         }
198     }
199     // No Bogo- or PassUser exists, or
200     // passwords are not allowed, and bogo is disallowed too.
201     // (Only the admin can sign in).
202     return $ForbiddenUser;
203 }
204
205 /**
206  * Primary WikiUser function, called by lib/main.php.
207  * 
208  * This determines the user's type and returns an appropriate user
209  * object. lib/main.php then querys the resultant object for password
210  * validity as necessary.
211  *
212  * If an _AnonUser object is returned, the user may only browse pages
213  * (and save prefs in a cookie).
214  *
215  * To disable access but provide prefs the global $ForbiddenUser class 
216  * is returned. (was previously false)
217  * 
218  */
219 function WikiUser ($UserName = '') {
220     global $ForbiddenUser;
221
222     //Maybe: Check sessionvar for username & save username into
223     //sessionvar (may be more appropriate to do this in lib/main.php).
224     if ($UserName) {
225         $ForbiddenUser = new _ForbiddenUser($UserName);
226         // Found a user name.
227         return _determineAdminUserOrOtherUser($UserName);
228     }
229     elseif (!empty($_SESSION['userid'])) {
230         // Found a user name.
231         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
232         return _determineAdminUserOrOtherUser($_SESSION['userid']);
233     }
234     else {
235         // Check for autologin pref in cookie and possibly upgrade
236         // user object to another type.
237         $_AnonUser = new _AnonUser();
238         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
239             // Found a user name.
240             $ForbiddenUser = new _ForbiddenUser($UserName);
241             return _determineAdminUserOrOtherUser($UserName);
242         }
243         else {
244             $ForbiddenUser = new _ForbiddenUser();
245             if (_isAnonUserAllowed())
246                 return $_AnonUser;
247             return $ForbiddenUser; // User must sign in to browse pages.
248         }
249         return $ForbiddenUser;     // User must sign in with a password.
250     }
251     /*
252     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
253                   . "Unexpectedly, an appropriate user class could not be determined.");
254     return $ForbiddenUser; // Failsafe.
255     */
256 }
257
258 /**
259  * WikiUser.php use the name 'WikiUser'
260  */
261 function WikiUserClassname() {
262     return '_WikiUser';
263 }
264
265
266 /**
267  * Upgrade olduser by copying properties from user to olduser.
268  * We are not sure yet, for which php's a simple $this = $user works reliably,
269  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
270  * that's why try it the hard way.
271  */
272 function UpgradeUser ($olduser, $user) {
273     if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
274         // populate the upgraded class $olduser with the values from the new user object
275         //only _auth_level, _current_method, _current_index,
276         if (!empty($user->_level) and 
277             $user->_level > $olduser->_level)
278             $olduser->_level = $user->_level;
279         if (!empty($user->_current_index) and
280             $user->_current_index > $olduser->_current_index) {
281             $olduser->_current_index = $user->_current_index;
282             $olduser->_current_method = $user->_current_method;
283         }
284         if (!empty($user->_authmethod))
285             $olduser->_authmethod = $user->_authmethod;
286         /*
287         foreach (get_object_vars($user) as $k => $v) {
288             if (!empty($v)) $olduser->$k = $v;  
289         }
290         */
291         $olduser->hasHomePage(); // revive db handle, because these don't survive sessions
292         //$GLOBALS['request']->_user = $olduser;
293         return $olduser;
294     } else {
295         return false;
296     }
297 }
298
299 /**
300  * Probably not needed, since we use the various user objects methods so far.
301  * Anyway, here it is, looping through all available objects.
302  */
303 function UserExists ($UserName) {
304     global $request;
305     if (!($user = $request->getUser()))
306         $user = WikiUser($UserName);
307     if (!$user) 
308         return false;
309     if ($user->userExists($UserName)) {
310         $request->_user = $user;
311         return true;
312     }
313     if (isa($user,'_BogoUser'))
314         $user = new _PassUser($UserName,$user->_prefs);
315     $class = $user->nextClass();
316     if ($user = new $class($UserName,$user->_prefs)) {
317         return $user->userExists($UserName);
318     }
319     $request->_user = $GLOBALS['ForbiddenUser'];
320     return false;
321 }
322
323 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
324
325 /** 
326  * Base WikiUser class.
327  */
328 class _WikiUser
329 {
330      var $_userid = '';
331      var $_level = WIKIAUTH_FORBIDDEN;
332      var $_prefs = false;
333      var $_HomePagehandle = false;
334
335     // constructor
336     function _WikiUser($UserName='', $prefs=false) {
337
338         $this->_userid = $UserName;
339         $this->_HomePagehandle = false;
340         if ($UserName) {
341             $this->hasHomePage();
342         }
343         $this->_level = WIKIAUTH_FORBIDDEN;
344         if (empty($this->_prefs)) {
345             if ($prefs) $this->_prefs = $prefs;
346             else $this->getPreferences();
347         }
348     }
349
350     function UserName() {
351         if (!empty($this->_userid))
352             return $this->_userid;
353     }
354
355     function getPreferences() {
356         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
357                       . "New subclasses of _WikiUser must override this function.");
358         return false;
359     }
360
361     function setPreferences($prefs, $id_only) {
362         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
363                       . "New subclasses of _WikiUser must override this function.");
364         return false;
365     }
366
367     function userExists() {
368         return $this->hasHomePage();
369     }
370
371     function checkPass($submitted_password) {
372         // By definition, an undefined user class cannot sign in.
373         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
374                       . "New subclasses of _WikiUser must override this function.");
375         return false;
376     }
377
378     // returns page_handle to user's home page or false if none
379     function hasHomePage() {
380         if ($this->_userid) {
381             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
382                 return $this->_HomePagehandle->exists();
383             }
384             else {
385                 // check db again (maybe someone else created it since
386                 // we logged in.)
387                 global $request;
388                 $this->_HomePagehandle = $request->getPage($this->_userid);
389                 return $this->_HomePagehandle->exists();
390             }
391         }
392         // nope
393         return false;
394     }
395
396     // innocent helper: case-insensitive position in _auth_methods
397     function array_position ($string, $array) {
398         $string = strtolower($string);
399         for ($found = 0; $found < count($array); $found++) {
400             if (strtolower($array[$found]) == $string)
401                 return $found;
402         }
403         return false;
404     }
405
406     function nextAuthMethodIndex() {
407         if (empty($this->_auth_methods)) 
408             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
409         if (empty($this->_current_index)) {
410             if (get_class($this) != '_passuser') {
411                 $this->_current_method = substr(get_class($this),1,-8);
412                 $this->_current_index = $this->array_position($this->_current_method,
413                                                               $this->_auth_methods);
414             } else {
415                 $this->_current_index = -1;
416             }
417         }
418         $this->_current_index++;
419         if ($this->_current_index >= count($this->_auth_methods))
420             return false;
421         $this->_current_method = $this->_auth_methods[$this->_current_index];
422         return $this->_current_index;
423     }
424
425     function AuthMethod($index = false) {
426         return $this->_auth_methods[ $index === false ? 0 : $index];
427     }
428
429     // upgrade the user object
430     function nextClass() {
431         if (($next = $this->nextAuthMethodIndex()) !== false) {
432             $method = $this->AuthMethod($next);
433             return "_".$method."PassUser";
434             /*          
435             if ($user = new $class($this->_userid)) {
436                 // prevent from endless recursion.
437                 //$user->_current_method = $this->_current_method;
438                 //$user->_current_index = $this->_current_index;
439                 $user = UpgradeUser($user, $this);
440             }
441             return $user;
442             */
443         }
444         return "_ForbiddenPassUser";
445     }
446
447     //Fixme: for _HttpAuthPassUser
448     function PrintLoginForm (&$request, $args, $fail_message = false,
449                              $seperate_page = true) {
450         include_once('lib/Template.php');
451         // Call update_locale in case the system's default language is not 'en'.
452         // (We have no user pref for lang at this point yet, no one is logged in.)
453         update_locale(DEFAULT_LANGUAGE);
454         $userid = $this->_userid;
455         $require_level = 0;
456         extract($args); // fixme
457
458         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
459
460         $pagename = $request->getArg('pagename');
461         $nocache = 1;
462         $login = new Template('login', $request,
463                               compact('pagename', 'userid', 'require_level',
464                                       'fail_message', 'pass_required', 'nocache'));
465         if ($seperate_page) {
466             $top = new Template('html', $request,
467                                 array('TITLE' => _("Sign In")));
468             return $top->printExpansion($login);
469         } else {
470             return $login;
471         }
472     }
473
474     /** Signed in but probably not password checked.
475      */
476     function isSignedIn() {
477         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
478     }
479
480     /** This is password checked for sure.
481      */
482     function isAuthenticated () {
483         //return isa($this,'_PassUser');
484         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
485         return $this->_level >= WIKIAUTH_BOGO; // hmm.
486     }
487
488     function isAdmin () {
489         return $this->_level == WIKIAUTH_ADMIN;
490     }
491
492     /** Name or IP for a signed user. UserName could come from a cookie e.g.
493      */
494     function getId () {
495         return ( $this->UserName()
496                  ? $this->UserName()
497                  : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
498     }
499
500     /** Name for an authenticated user. No IP here.
501      */
502     function getAuthenticatedId() {
503         return ( $this->isAuthenticated()
504                  ? $this->_userid
505                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
506     }
507
508     function hasAuthority ($require_level) {
509         return $this->_level >= $require_level;
510     }
511
512     /**
513      * Called on an auth_args POST request, such as login, logout or signin.
514      */
515     function AuthCheck ($postargs) {
516         // Normalize args, and extract.
517         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
518                       'cancel');
519         foreach ($keys as $key)
520             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
521         extract($args);
522         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
523
524         if ($logout) { // Log out
525             $GLOBALS['request']->_user = new _AnonUser();
526             return $GLOBALS['request']->_user; 
527         } elseif ($cancel)
528             return false;        // User hit cancel button.
529         elseif (!$login && !$userid)
530             return false;       // Nothing to do?
531
532         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
533         if (!$authlevel)
534             return _("Invalid password or userid.");
535         elseif ($authlevel < $require_level)
536             return _("Insufficient permissions.");
537
538         // Successful login.
539         //$user = $GLOBALS['request']->_user;
540         if (!empty($this->_current_method) and 
541             strtolower(get_class($this)) == '_passuser') 
542         {
543             // upgrade class
544             $class = "_" . $this->_current_method . "PassUser";
545             $user = new $class($userid,$this->_prefs);
546             /*PHP5 patch*/$this = $user;
547             $this->_level = $authlevel;
548             return $user;
549         }
550         $this->_userid = $userid;
551         $this->_level = $authlevel;
552         return $this;
553     }
554
555 }
556
557 /**
558  * Not authenticated in user, but he may be signed in. Basicly with view access only.
559  * prefs are stored in cookies, but only the userid.
560  */
561 class _AnonUser
562 extends _WikiUser
563 {
564     var $_level = WIKIAUTH_ANON;        // var in php-5.0.0RC1 deprecated
565
566     /** Anon only gets to load and save prefs in a cookie, that's it.
567      */
568     function getPreferences() {
569         global $request;
570
571         if (empty($this->_prefs))
572             $this->_prefs = new UserPreferences;
573         $UserName = $this->UserName();
574
575         // Try to read deprecated 1.3.x style cookies
576         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
577             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
578                 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.") 
579                               . "\n"
580                               . sprintf("%s='%s'", WIKI_NAME, $cookie)
581                               . "\n"
582                               . _("Default preferences will be used."),
583                               E_USER_NOTICE);
584             }
585             /**
586              * Only set if it matches the UserName who is
587              * signing in or if this really is an Anon login (no
588              * username). (Remember, _BogoUser and higher inherit this
589              * function too!).
590              */
591             if (! $UserName || $UserName == @$unboxedcookie['userid']) {
592                 $updated = $this->_prefs->updatePrefs($unboxedcookie);
593                 //$this->_prefs = new UserPreferences($unboxedcookie);
594                 $UserName = @$unboxedcookie['userid'];
595                 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
596                     $this->_userid = $UserName;
597                 else 
598                     $UserName = false;    
599             }
600             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
601             $request->deleteCookieVar(WIKI_NAME);
602         }
603         // Try to read deprecated 1.3.4 style cookies
604         if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
605             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
606                 if (! $UserName || $UserName == $unboxedcookie['userid']) {
607                     $updated = $this->_prefs->updatePrefs($unboxedcookie);
608                     //$this->_prefs = new UserPreferences($unboxedcookie);
609                     $UserName = $unboxedcookie['userid'];
610                     if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
611                         $this->_userid = $UserName;
612                     else 
613                         $UserName = false;    
614                 }
615                 $request->deleteCookieVar("WIKI_PREF2");
616             }
617         }
618         if (! $UserName ) {
619             // Try reading userid from old PhpWiki cookie formats:
620             if ($cookie = $request->cookies->get_old('WIKI_ID')) {
621                 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
622                     $UserName = $cookie;
623                 elseif (is_array($cookie) and !empty($cookie['userid']))
624                     $UserName = $cookie['userid'];
625             }
626             if (! $UserName )
627                 $request->deleteCookieVar("WIKI_ID");
628             else
629                 $this->_userid = $UserName;
630         }
631
632         // initializeTheme() needs at least an empty object
633         /*
634          if (empty($this->_prefs))
635             $this->_prefs = new UserPreferences;
636         */
637         return $this->_prefs;
638     }
639
640     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
641      *
642      * Allow for multiple wikis in same domain. Encode only the
643      * _prefs array of the UserPreference object. Ideally the
644      * prefs array should just be imploded into a single string or
645      * something so it is completely human readable by the end
646      * user. In that case stricter error checking will be needed
647      * when loading the cookie.
648      */
649     function setPreferences($prefs, $id_only=false) {
650         if (!is_object($prefs)) {
651             if (is_object($this->_prefs)) {
652                 $updated = $this->_prefs->updatePrefs($prefs);
653                 $prefs =& $this->_prefs;
654             } else {
655                 // update the prefs values from scratch. This could leed to unnecessary
656                 // side-effects: duplicate emailVerified, ...
657                 $this->_prefs = new UserPreferences($prefs);
658                 $updated = true;
659             }
660         } else {
661             if (!isset($this->_prefs))
662                 $this->_prefs =& $prefs;
663             else
664                 $updated = $this->_prefs->isChanged($prefs);
665         }
666         if ($updated) {
667             if ($id_only) {
668                 global $request;
669                 // new 1.3.8 policy: no array cookies, only plain userid string as in 
670                 // the pre 1.3.x versions.
671                 // prefs should be stored besides the session in the homepagehandle or in a db.
672                 $request->setCookieVar('WIKI_ID', $this->_userid,
673                                        COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
674                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
675                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
676             }
677         }
678         $packed = $prefs->store();
679         $unpacked = $prefs->unpack($packed);
680         if (count($unpacked)) {
681             foreach (array('_method','_select','_update') as $param) {
682                 if (!empty($this->_prefs->{$param}))
683                     $prefs->{$param} = $this->_prefs->{$param};
684             }
685             $this->_prefs = $prefs;
686             //FIXME! The following must be done in $request->_setUser(), not here,
687             // to be able to iterate over multiple users, without tampering the current user.
688             if (0) {
689                 global $request;
690                 $request->_prefs =& $this->_prefs; 
691                 $request->_user->_prefs =& $this->_prefs;
692                 if (isset($request->_user->_auth_dbi)) {
693                     $user = $request->_user;
694                     unset($user->_auth_dbi);
695                     $request->setSessionVar('wiki_user', $user);
696                 } else {
697                     //$request->setSessionVar('wiki_prefs', $this->_prefs);
698                     $request->setSessionVar('wiki_user', $request->_user);
699                 }
700             }
701         }
702         return $updated;
703     }
704
705     function userExists() {
706         return true;
707     }
708
709     function checkPass($submitted_password) {
710         return false;
711         // this might happen on a old-style signin button.
712
713         // By definition, the _AnonUser does not HAVE a password
714         // (compared to _BogoUser, who has an EMPTY password).
715         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
716                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
717                       . "New subclasses of _WikiUser must override this function.");
718         return false;
719     }
720
721 }
722
723 /** 
724  * Helper class to finish the PassUser auth loop. 
725  * This is added automatically to USER_AUTH_ORDER.
726  */
727 class _ForbiddenUser
728 extends _AnonUser
729 {
730     var $_level = WIKIAUTH_FORBIDDEN;
731
732     function checkPass($submitted_password) {
733         return WIKIAUTH_FORBIDDEN;
734     }
735
736     function userExists() {
737         if ($this->_HomePagehandle) return true;
738         return false;
739     }
740 }
741 /** 
742  * The PassUser name gets created automatically. 
743  * That's why this class is empty, but must exist.
744  */
745 class _ForbiddenPassUser
746 extends _ForbiddenUser
747 {
748     function dummy() {
749         return;
750     }
751 }
752
753 /**
754  * Do NOT extend _BogoUser to other classes, for checkPass()
755  * security. (In case of defects in code logic of the new class!)
756  * The intermediate step between anon and passuser.
757  * We also have the _BogoLoginPassUser class with stricter 
758  * password checking, which fits into the auth loop.
759  * Note: This class is not called anymore by WikiUser()
760  */
761 class _BogoUser
762 extends _AnonUser
763 {
764     function userExists() {
765         if (isWikiWord($this->_userid)) {
766             $this->_level = WIKIAUTH_BOGO;
767             return true;
768         } else {
769             $this->_level = WIKIAUTH_ANON;
770             return false;
771         }
772     }
773
774     function checkPass($submitted_password) {
775         // By definition, BogoUser has an empty password.
776         $this->userExists();
777         return $this->_level;
778     }
779 }
780
781 class _PassUser
782 extends _AnonUser
783 /**
784  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
785  *
786  * The classes for all subsequent auth methods extend from this class. 
787  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
788  * the three auth method policies first-only, strict and stacked
789  * and the two methods for prefs: homepage or database, 
790  * if $DBAuthParams['pref_select'] is defined.
791  *
792  * Default is PersonalPage auth and prefs.
793  * 
794  * TODO: email verification
795  *
796  * @author: Reini Urban
797  * @tables: pref
798  */
799 {
800     var $_auth_dbi, $_prefs;
801     var $_current_method, $_current_index;
802
803     // check and prepare the auth and pref methods only once
804     function _PassUser($UserName='', $prefs=false) {
805         global $DBAuthParams, $DBParams;
806         if ($UserName) {
807             $this->_userid = $UserName;
808             if ($this->hasHomePage())
809                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
810         }
811         $this->_authmethod = substr(get_class($this),1,-8);
812         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
813         if (! $this->_prefs) {
814             if ($prefs) $this->_prefs = $prefs;
815             else $this->getPreferences();
816         }
817
818         // Check the configured Prefs methods
819         if ( !isset($this->_prefs->_select) and !empty($DBAuthParams['pref_select']) 
820              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
821             $this->_prefs->_method = $DBParams['dbtype'];
822             // preparate the SELECT statement
823             $this->_prefs->_select = $this->prepare($DBAuthParams['pref_select'], 
824                                                     '"$userid"');
825         //} else {
826         //    unset($this->_prefs->_select);
827         } else {
828             $this->_prefs->_method = 'HomePage';
829         }
830         if (  !isset($this->_prefs->_update) and !empty($DBAuthParams['pref_update'])
831              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
832             $this->_prefs->_method = $DBParams['dbtype'];
833             // preparate the SELECT statement
834             $this->_prefs->_update = $this->prepare($DBAuthParams['pref_update'], 
835                                                     array('"$userid"','"$pref_blob"'));
836         }
837         
838         // Upgrade to the next parent _PassUser class. Avoid recursion.
839         if ( strtolower(get_class($this)) === '_passuser' ) {
840             //auth policy: Check the order of the configured auth methods
841             // 1. first-only: Upgrade the class here in the constructor
842             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as 
843             ///              in the previous PhpWiki releases (slow)
844             // 3. strict:    upgrade the class after checking the user existance in userExists()
845             // 4. stacked:   upgrade the class after the password verification in checkPass()
846             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
847             if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
848             if (defined('USER_AUTH_POLICY')) {
849                 // policy 1: only pre-define one method for all users
850                 if (USER_AUTH_POLICY === 'first-only') {
851                     $class = $this->nextClass();
852                     return new $class($UserName,$this->_prefs);
853                 }
854                 // use the default behaviour from the previous versions:
855                 elseif (USER_AUTH_POLICY === 'old') {
856                     // default: try to be smart
857                     // On php5 we can directly return and upgrade the Object,
858                     // before we have to upgrade it manually.
859                     if (!empty($GLOBALS['PHP_AUTH_USER'])) {
860                         if (check_php_version(5))
861                             return new _HttpAuthPassUser($UserName,$this->_prefs);
862                         else {
863                             $user = new _HttpAuthPassUser($UserName,$this->_prefs);
864                             //todo: with php5 comment the following line.
865                             /*PHP5 patch*/$this = $user;
866                             return $user;
867                         }
868                     } elseif (!empty($DBAuthParams['auth_check']) and 
869                               (!empty($DBAuthParams['auth_dsn']) or !empty($GLOBALS ['DBParams']['dsn']))) {
870                         if (check_php_version(5))
871                             return new _DbPassUser($UserName,$this->_prefs);
872                         else {
873                             $user = new _DbPassUser($UserName,$this->_prefs);
874                             //todo: with php5 comment the following line.
875                             /*PHP5 patch*/$this = $user;
876                             return $user;
877                         }
878                     } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
879                         if (check_php_version(5))
880                             return new _LDAPPassUser($UserName,$this->_prefs);
881                         else {
882                             $user = new _LDAPPassUser($UserName,$this->_prefs);
883                             //todo: with php5 comment the following line.
884                             /*PHP5 patch*/$this = $user;
885                             return $user;
886                         }
887                     } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
888                         if (check_php_version(5))
889                             return new _IMAPPassUser($UserName,$this->_prefs);
890                         else {
891                             $user = new _IMAPPassUser($UserName,$this->_prefs);
892                             //todo: with php5 comment the following line.
893                             /*PHP5 patch*/$this = $user;
894                             return $user;
895                         }
896                     } elseif (defined('AUTH_USER_FILE')) {
897                         if (check_php_version(5))
898                             return new _FilePassUser($UserName,$this->_prefs);
899                         else {
900                             $user = new _FilePassUser($UserName,$this->_prefs);
901                             //todo: with php5 comment the following line.
902                             /*PHP5 patch*/$this = $user;
903                             return $user;
904                         }
905                     } else {
906                         if (check_php_version(5))
907                             return new _PersonalPagePassUser($UserName,$this->_prefs);
908                         else {
909                             $user = new _PersonalPagePassUser($UserName,$this->_prefs);
910                             //todo: with php5 comment the following line.
911                             /*PHP5 patch*/$this = $user;
912                             return $user;
913                         }
914                     }
915                 }
916                 else 
917                     // else use the page methods defined in _PassUser.
918                     return $this;
919             }
920         }
921     }
922
923     function getAuthDbh () {
924         global $request, $DBParams, $DBAuthParams;
925
926         // session restauration doesn't re-connect to the database automatically, 
927         // so dirty it here.
928         if (($DBParams['dbtype'] == 'SQL') and isset($this->_auth_dbi) and 
929              empty($this->_auth_dbi->connection))
930             unset($this->_auth_dbi);
931         if (($DBParams['dbtype'] == 'ADODB') and isset($this->_auth_dbi) and 
932              empty($this->_auth_dbi->_connectionID))
933             unset($this->_auth_dbi);
934
935         if (empty($this->_auth_dbi)) {
936             if ($DBParams['dbtype'] != 'SQL' and $DBParams['dbtype'] != 'ADODB')
937                 return false;
938             if (empty($DBAuthParams))
939                 return false;
940             if (empty($DBAuthParams['auth_dsn'])) {
941                 $dbh = $request->getDbh(); // use phpwiki database 
942             } elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn']) {
943                 $dbh = $request->getDbh(); // same phpwiki database 
944             } else { // use another external database handle. needs PHP >= 4.1
945                 $local_params = array_merge($DBParams,$DBAuthParams);
946                 $local_params['dsn'] = $local_params['auth_dsn'];
947                 $dbh = WikiDB::open($local_params);
948             }       
949             $this->_auth_dbi =& $dbh->_backend->_dbh;    
950         }
951         return $this->_auth_dbi;
952     }
953
954     // TODO: use it again for the auth and member tables
955     function prepare ($stmt, $variables) {
956         global $DBParams, $request;
957         $this->getAuthDbh();
958         // '"$userid"' => '%s'
959         if (is_array($variables)) {
960             $new = array();
961             foreach ($variables as $v) { $new[] = '%s'; }
962         } else {
963             $new = '%s';
964         }
965         // probably prefix table names if in same database
966         if (!empty($DBParams['prefix']) and 
967             isset($this->_auth_dbi) and isset($request->_dbi->_backend->_dbh) and 
968             $DBParams['dsn'] == $GLOBALS['DBAuthParams']['auth_dsn'])
969         {
970             $prefix = $DBParams['prefix'];
971             if (!stristr($stmt, $prefix)) {
972                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
973                 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php:\n  $stmt",
974                               E_USER_WARNING);
975                 $stmt = str_replace(array(" user "," pref "," member "),
976                                     array(" ".$prefix."user ",
977                                           " ".$prefix."prefs ",
978                                           " ".$prefix."member "),$stmt);
979             }
980         }
981         // preparate the SELECT statement, for ADODB and PearDB (MDB not)
982         // simple sprintf-style.
983         return str_replace($variables,$new,$stmt);
984     }
985
986     function getPreferences() {
987         if (!empty($this->_prefs->_method)) {
988             if ($this->_prefs->_method == 'ADODB') {
989                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
990                 return _AdoDbPassUser::getPreferences();
991             } elseif ($this->_prefs->_method == 'SQL') {
992                 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
993                 return _PearDbPassUser::getPreferences();
994             }
995         }
996
997         // We don't necessarily have to read the cookie first. Since
998         // the user has a password, the prefs stored in the homepage
999         // cannot be arbitrarily altered by other Bogo users.
1000         _AnonUser::getPreferences();
1001         // User may have deleted cookie, retrieve from his
1002         // PersonalPage if there is one.
1003         if ($this->_HomePagehandle) {
1004             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1005                 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1006                 //$this->_prefs = new UserPreferences($restored_from_page);
1007                 return $this->_prefs;
1008             }
1009         }
1010         return $this->_prefs;
1011     }
1012
1013     function setPreferences($prefs, $id_only=false) {
1014         if (!empty($this->_prefs->_method)) {
1015             if ($this->_prefs->_method == 'ADODB') {
1016                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
1017                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1018             }
1019             elseif ($this->_prefs->_method == 'SQL') {
1020                 _PearDbPassUser::_PearDbPassUser($this->_userid,$prefs);
1021                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1022             }
1023         }
1024         if (_AnonUser::setPreferences($prefs, $id_only)) {
1025             // Encode only the _prefs array of the UserPreference object
1026             if ($this->_HomePagehandle and !$id_only) {
1027                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1028             }
1029         }
1030         return;
1031     }
1032
1033     function mayChangePass() {
1034         return true;
1035     }
1036
1037     //The default method is getting the password from prefs. 
1038     // child methods obtain $stored_password from external auth.
1039     function userExists() {
1040         //if ($this->_HomePagehandle) return true;
1041         $class = $this->nextClass();
1042         while ($user = new $class($this->_userid,$this->_prefs)) {
1043             //todo: with php5 comment the following line:
1044             /*PHP5 patch*/$this = $user;
1045             //UpgradeUser($this,$user);
1046             if ($user->userExists()) {
1047                 return true;
1048             }
1049             // prevent endless loop. does this work on all PHP's?
1050             // it just has to set the classname, what it correctly does.
1051             $class = $user->nextClass();
1052             if ($class == "_ForbiddenPassUser")
1053                 return false;
1054         }
1055         return false;
1056     }
1057
1058     //The default method is getting the password from prefs. 
1059     // child methods obtain $stored_password from external auth.
1060     function checkPass($submitted_password) {
1061         $stored_password = $this->_prefs->get('passwd');
1062         if ($this->_checkPass($submitted_password, $stored_password)) {
1063             $this->_level = WIKIAUTH_USER;
1064             return $this->_level;
1065         } else {
1066             return $this->_tryNextPass($submitted_password);
1067         }
1068     }
1069
1070     /**
1071      * The basic password checker for all PassUser objects.
1072      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1073      * Empty passwords are always false!
1074      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1075      * @see UserPreferences::set
1076      *
1077      * DBPassUser password's have their own crypt definition.
1078      * That's why DBPassUser::checkPass() doesn't call this method, if 
1079      * the db password method is 'plain', which means that the DB SQL 
1080      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
1081      * don't store plain passwords in the DB.
1082      * 
1083      * TODO: remove crypt() function check from config.php:396 ??
1084      */
1085     function _checkPass($submitted_password, $stored_password) {
1086         if(!empty($submitted_password)) {
1087             if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1088                 // Todo. hmm...
1089                 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."));
1090                 return false;
1091             }
1092             if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
1093                 return false;
1094             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
1095                 // Verify against encrypted password.
1096                 if (function_exists('crypt')) {
1097                     if (crypt($submitted_password, $stored_password) == $stored_password )
1098                         return true; // matches encrypted password
1099                     else
1100                         return false;
1101                 }
1102                 else {
1103                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1104                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and probably change ADMIN_PASSWD."),
1105                                   E_USER_WARNING);
1106                     return false;
1107                 }
1108             }
1109             else {
1110                 // Verify against cleartext password.
1111                 if ($submitted_password == $stored_password)
1112                     return true;
1113                 else {
1114                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1115                     if (function_exists('crypt')) {
1116                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1117                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
1118                                           E_USER_WARNING);
1119                             return true;
1120                         }
1121                     }
1122                 }
1123             }
1124         }
1125         return false;
1126     }
1127
1128     /** The default method is storing the password in prefs. 
1129      *  Child methods (DB,File) may store in external auth also, but this 
1130      *  must be explicitly enabled.
1131      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1132      */
1133     function changePass($submitted_password) {
1134         $stored_password = $this->_prefs->get('passwd');
1135         // check if authenticated
1136         if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1137             $this->_prefs->set('passwd',$submitted_password);
1138             //update the storage (session, homepage, ...)
1139             $this->SetPreferences($this->_prefs);
1140             return true;
1141         }
1142         //Todo: return an error msg to the caller what failed? 
1143         // same password or no privilege
1144         return false;
1145     }
1146
1147     function _tryNextPass($submitted_password) {
1148         if (USER_AUTH_POLICY === 'strict') {
1149                 $class = $this->nextClass();
1150             if ($user = new $class($this->_userid,$this->_prefs)) {
1151                 if ($user->userExists()) {
1152                     return $user->checkPass($submitted_password);
1153                 }
1154             }
1155         }
1156         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1157                 $class = $this->nextClass();
1158             if ($user = new $class($this->_userid,$this->_prefs))
1159                 return $user->checkPass($submitted_password);
1160         }
1161         return $this->_level;
1162     }
1163
1164     function _tryNextUser() {
1165         if (USER_AUTH_POLICY === 'strict') {
1166                 $class = $this->nextClass();
1167             while ($user = new $class($this->_userid,$this->_prefs)) {
1168                 //todo: with php5 comment the following line:
1169                 /*PHP5 patch*/$this = $user;
1170                 //$user = UpgradeUser($this, $user);
1171                 if ($user->userExists()) {
1172                     return true;
1173                 }
1174                 $class = $this->nextClass();
1175             }
1176         }
1177         return false;
1178     }
1179
1180 }
1181
1182 /** Without stored password. A _BogoLoginPassUser with password 
1183  *  is automatically upgraded to a PersonalPagePassUser.
1184  */
1185 class _BogoLoginPassUser
1186 extends _PassUser
1187 {
1188     var $_authmethod = 'BogoLogin';
1189     function userExists() {
1190         if (isWikiWord($this->_userid)) {
1191             $this->_level = WIKIAUTH_BOGO;
1192             return true;
1193         } else {
1194             $this->_level = WIKIAUTH_ANON;
1195             return false;
1196         }
1197     }
1198
1199     /** A BogoLoginUser requires no password at all
1200      *  But if there's one stored, we should prefer PersonalPage instead
1201      */
1202     function checkPass($submitted_password) {
1203         if ($this->_prefs->get('passwd')) {
1204             $user = new _PersonalPagePassUser($this->_userid);
1205             if ($user->checkPass($submitted_password)) {
1206                 //todo: with php5 comment the following line:
1207                 /*PHP5 patch*/$this = $user;
1208                 $user = UpgradeUser($this, $user);
1209                 $this->_level = WIKIAUTH_USER;
1210                 return $this->_level;
1211             } else {
1212                 $this->_level = WIKIAUTH_ANON;
1213                 return $this->_level;
1214             }
1215         }
1216         $this->userExists();
1217         return $this->_level;
1218     }
1219 }
1220
1221
1222 /**
1223  * This class is only to simplify the auth method dispatcher.
1224  * It inherits almost all all methods from _PassUser.
1225  */
1226 class _PersonalPagePassUser
1227 extends _PassUser
1228 {
1229     var $_authmethod = 'PersonalPage';
1230
1231     function userExists() {
1232         return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1233     }
1234
1235     /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1236      *  BUT if the user already has a homepage with an empty password 
1237      *  stored, allow login but warn him to change it.
1238      */
1239     function checkPass($submitted_password) {
1240         if ($this->userExists()) {
1241             $stored_password = $this->_prefs->get('passwd');
1242             if (empty($stored_password)) {
1243                 trigger_error(sprintf(
1244                 _("\nYou stored an empty password in your '%s' page.\n").
1245                 _("Your access permissions are only for a BogoUser.\n").
1246                 _("Please set your password in UserPreferences."),
1247                                         $this->_userid), E_USER_NOTICE);
1248                 $this->_level = WIKIAUTH_BOGO;
1249                 return $this->_level;
1250             }
1251             if ($this->_checkPass($submitted_password, $stored_password))
1252                 return ($this->_level = WIKIAUTH_USER);
1253             return _PassUser::checkPass($submitted_password);
1254         }
1255         return WIKIAUTH_ANON;
1256     }
1257 }
1258
1259 /**
1260  * We have two possibilities here.
1261  * 1) The webserver location is already HTTP protected (usually Basic). Then just 
1262  *    use the username and do nothing
1263  * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1264  *    by sending a 401 error and let the client display the login dialog.
1265  *    This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1266  *    since the other methods cannot be transparently called after this enforced 
1267  *    external dialog.
1268  *    Try the available auth methods (most likely Bogo) and sent this header back.
1269  *    header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1270  */
1271 class _HttpAuthPassUser
1272 extends _PassUser
1273 {
1274     function _HttpAuthPassUser($UserName='',$prefs=false) {
1275         if ($prefs) $this->_prefs = $prefs;
1276         if (!isset($this->_prefs->_method))
1277            _PassUser::_PassUser($UserName);
1278         if ($UserName) $this->_userid = $UserName;
1279         $this->_authmethod = 'HttpAuth';
1280         if ($this->userExists())
1281             return $this;
1282         else 
1283             return $GLOBALS['ForbiddenUser'];
1284     }
1285
1286     function _http_username() {
1287         if (!empty($_SERVER['PHP_AUTH_USER']))
1288             return $_SERVER['PHP_AUTH_USER'];
1289         if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']))
1290             return $GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER'];
1291         if (!empty($GLOBALS['REMOTE_USER']))
1292             return $GLOBALS['REMOTE_USER'];
1293         if (!empty($GLOBALS['HTTP_SERVER_VARS']['REMOTE_USER']))
1294             return $GLOBALS['HTTP_SERVER_VARS']['REMOTE_USER'];
1295         if (!empty($GLOBALS['HTTP_ENV_VARS']['REMOTE_USER']))
1296             return $GLOBALS['HTTP_ENV_VARS']['REMOTE_USER'];
1297         return '';
1298     }
1299     
1300     //force http auth authorization
1301     function userExists() {
1302         // todo: older php's
1303         $username = $this->_http_username();
1304         if (empty($username) or $username != $this->_userid) {
1305             header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1306             header('HTTP/1.0 401 Unauthorized'); 
1307             exit;
1308         }
1309         $this->_userid = $username;
1310         $this->_level = WIKIAUTH_USER;
1311         return $this;
1312     }
1313         
1314     function checkPass($submitted_password) {
1315         return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1316     }
1317
1318     function mayChangePass() {
1319         return false;
1320     }
1321
1322     // hmm... either the server dialog or our own.
1323     function PrintLoginForm (&$request, $args, $fail_message = false,
1324                              $seperate_page = true) {
1325         header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1326         header('HTTP/1.0 401 Unauthorized'); 
1327         exit;
1328
1329         include_once('lib/Template.php');
1330         // Call update_locale in case the system's default language is not 'en'.
1331         // (We have no user pref for lang at this point yet, no one is logged in.)
1332         update_locale(DEFAULT_LANGUAGE);
1333         $userid = $this->_userid;
1334         $require_level = 0;
1335         extract($args); // fixme
1336
1337         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
1338
1339         $pagename = $request->getArg('pagename');
1340         $nocache = 1;
1341         $login = new Template('login', $request,
1342                               compact('pagename', 'userid', 'require_level',
1343                                       'fail_message', 'pass_required', 'nocache'));
1344         if ($seperate_page) {
1345             $top = new Template('html', $request,
1346                                 array('TITLE' => _("Sign In")));
1347             return $top->printExpansion($login);
1348         } else {
1349             return $login;
1350         }
1351     }
1352
1353 }
1354
1355 /** 
1356  * Support reuse of existing user session from another application.
1357  * You have to define which session variable holds the userid, and 
1358  * at what level is that user then. 1: BogoUser, 2: PassUser
1359  *   define('AUTH_SESS_USER','userid');
1360  *   define('AUTH_SESS_LEVEL',2);
1361  */
1362 class _SessionPassUser
1363 extends _PassUser
1364 {
1365     function _SessionPassUser($UserName='',$prefs=false) {
1366         if ($prefs) $this->_prefs = $prefs;
1367         if (!defined("AUTH_SESS_USER") or !defined("AUTH_SESS_LEVEL")) {
1368             trigger_error(
1369                 "AUTH_SESS_USER or AUTH_SESS_LEVEL is not defined for the SessionPassUser method",
1370                 E_USER_ERROR);
1371             exit;
1372         }
1373         $sess =& $GLOBALS['HTTP_SESSION_VARS'];
1374         // FIXME: user hash: "[user][userid]" or object "user->id"
1375         $this->_userid = $sess[AUTH_SESS_USER];
1376         if (!isset($this->_prefs->_method))
1377            _PassUser::_PassUser($this->_userid);
1378         $this->_level = AUTH_SESS_LEVEL;
1379         $this->_authmethod = 'Session';
1380     }
1381     function userExists() {
1382         return !empty($this->_userid);
1383     }
1384     function checkPass($submitted_password) {
1385         return $this->userExists() and $this->_level;
1386     }
1387     function mayChangePass() {
1388         return false;
1389     }
1390 }
1391
1392 /**
1393  * Baseclass for PearDB and ADODB PassUser's
1394  * Authenticate against a database, to be able to use shared users.
1395  *   internal: no different $DbAuthParams['dsn'] defined, or
1396  *   external: different $DbAuthParams['dsn']
1397  * The magic is done in the symbolic SQL statements in index.php, similar to
1398  * libnss-mysql.
1399  *
1400  * We support only the SQL and ADODB backends.
1401  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
1402  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
1403  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn']. 
1404  * (Not supported yet, since we require SQL. SQLite would make since when 
1405  * it will come to PHP)
1406  *
1407  * @tables: user, pref
1408  *
1409  * Preferences are handled in the parent class _PassUser, because the 
1410  * previous classes may also use DB pref_select and pref_update.
1411  *
1412  * Flat files auth is handled by the auth method "File".
1413  */
1414 class _DbPassUser
1415 extends _PassUser
1416 {
1417     var $_authselect, $_authupdate, $_authcreate;
1418
1419     // This can only be called from _PassUser, because the parent class 
1420     // sets the auth_dbi and pref methods, before this class is initialized.
1421     function _DbPassUser($UserName='',$prefs=false) {
1422         if (!$this->_prefs) {
1423             if ($prefs) $this->_prefs = $prefs;
1424         }
1425         if (!isset($this->_prefs->_method))
1426            _PassUser::_PassUser($UserName);
1427         $this->_authmethod = 'Db';
1428         //$this->getAuthDbh();
1429         //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1430         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') {
1431             if (check_php_version(5))
1432                 return new _AdoDbPassUser($UserName,$this->_prefs);
1433             else {
1434                 $user = new _AdoDbPassUser($UserName,$this->_prefs);
1435                 //todo: with php5 comment the following line:
1436                 /*PHP5 patch*/$this = $user;
1437                 return $user;
1438             }
1439         }
1440         elseif ($GLOBALS['DBParams']['dbtype'] == 'SQL') {
1441             if (check_php_version(5))
1442                 return new _PearDbPassUser($UserName,$this->_prefs);
1443             else {
1444                 $user = new _PearDbPassUser($UserName,$this->_prefs);
1445                 //todo: with php5 comment the following line:
1446                 /*PHP5 patch*/$this = $user;
1447                 return $user;
1448             }
1449         }
1450         return false;
1451     }
1452
1453     function mayChangePass() {
1454         return !isset($this->_authupdate);
1455     }
1456
1457 }
1458
1459 class _PearDbPassUser
1460 extends _DbPassUser
1461 /**
1462  * Pear DB methods
1463  * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1464  * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1465  *
1466  * @tables: user
1467  * @tables: pref
1468  */
1469 {
1470     var $_authmethod = 'PearDb';
1471     function _PearDbPassUser($UserName='',$prefs=false) {
1472         global $DBAuthParams;
1473         if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1474             if ($prefs) $this->_prefs = $prefs;
1475         }
1476         if (!isset($this->_prefs->_method))
1477             _PassUser::_PassUser($UserName);
1478         $this->_userid = $UserName;
1479         // make use of session data. generally we only initialize this every time, 
1480         // but do auth checks only once
1481         $this->_auth_crypt_method = @$DBAuthParams['auth_crypt_method'];
1482         //$this->getAuthDbh();
1483         return $this;
1484     }
1485
1486     function getPreferences() {
1487         // override the generic slow method here for efficiency and not to 
1488         // clutter the homepage metadata with prefs.
1489         _AnonUser::getPreferences();
1490         $this->getAuthDbh();
1491         if (isset($this->_prefs->_select)) {
1492             $dbh = &$this->_auth_dbi;
1493             $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1494             // patched by frederik@pandora.be
1495             $prefs = $db_result->fetchRow();
1496             $prefs_blob = $prefs["prefs"]; 
1497             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1498                 $updated = $this->_prefs->updatePrefs($restored_from_db);
1499                 //$this->_prefs = new UserPreferences($restored_from_db);
1500                 return $this->_prefs;
1501             }
1502         }
1503         if ($this->_HomePagehandle) {
1504             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1505                 $updated = $this->_prefs->updatePrefs($restored_from_page);
1506                 //$this->_prefs = new UserPreferences($restored_from_page);
1507                 return $this->_prefs;
1508             }
1509         }
1510         return $this->_prefs;
1511     }
1512
1513     function setPreferences($prefs, $id_only=false) {
1514         // if the prefs are changed
1515         if (_AnonUser::setPreferences($prefs, 1)) {
1516             //global $request;
1517             //$user = $request->_user;
1518             //unset($user->_auth_dbi);
1519             // this must be done in $request->_setUser, not here!
1520             //$request->setSessionVar('wiki_user', $user);
1521             $this->getAuthDbh();
1522             $packed = $this->_prefs->store();
1523             if (!$id_only and isset($this->_prefs->_update)) {
1524                 $dbh = &$this->_auth_dbi;
1525                 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1526                                           $dbh->quote($packed),
1527                                           $dbh->quote($this->_userid)));
1528             } else {
1529                 //store prefs in homepage, not in cookie
1530                 if ($this->_HomePagehandle and !$id_only)
1531                     $this->_HomePagehandle->set('pref', $packed);
1532             }
1533             return count($this->_prefs->unpack($packed));
1534         }
1535         return 0;
1536     }
1537
1538     function userExists() {
1539         global $DBAuthParams;
1540         $this->getAuthDbh();
1541         $dbh = &$this->_auth_dbi;
1542         if (!$dbh) { // needed?
1543             return $this->_tryNextUser();
1544         }
1545         // Prepare the configured auth statements
1546         if (!empty($DBAuthParams['auth_check']) and empty($this->_authselect)) {
1547             $this->_authselect = str_replace(array('"$userid"','"$password"'),
1548                                              array('%s','%s'),
1549                                              $DBAuthParams['auth_check']);
1550         }
1551         if (empty($this->_authselect))
1552             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1553                           E_USER_WARNING);
1554         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1555         if ($this->_auth_crypt_method == 'crypt') {
1556             $rs = $dbh->query(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1557             if ($rs->numRows())
1558                 return true;
1559         }
1560         else {
1561             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1562                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1563                               E_USER_WARNING);
1564             $this->_authcheck = str_replace('"$userid"','%s',
1565                                              $DBAuthParams['auth_user_exists']);
1566             $rs = $dbh->query(sprintf($this->_authcheck,$dbh->quote($this->_userid)));
1567             if ($rs->numRows())
1568                 return true;
1569         }
1570         // maybe the user is allowed to create himself. Generally not wanted in 
1571         // external databases, but maybe wanted for the wiki database, for performance 
1572         // reasons
1573         if (empty($this->_authcreate) and !empty($DBAuthParams['auth_create'])) {
1574             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1575                                               $DBAuthParams['auth_create']);
1576         }
1577         if (!empty($this->_authcreate)) {
1578             $dbh->simpleQuery(sprintf($this->_authcreate,
1579                                       $dbh->quote($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1580                                       $dbh->quote($this->_userid)
1581                                       ));
1582             return true;
1583         }
1584         return $this->_tryNextUser();
1585     }
1586  
1587     function checkPass($submitted_password) {
1588         global $DBAuthParams;
1589         $this->getAuthDbh();
1590         if (!$this->_auth_dbi) {  // needed?
1591             return $this->_tryNextPass($submitted_password);
1592         }
1593         if (!isset($this->_authselect))
1594             $this->userExists();
1595         if (!isset($this->_authselect))
1596             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1597                           E_USER_WARNING);
1598
1599         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1600         $dbh = &$this->_auth_dbi;
1601         if ($this->_auth_crypt_method == 'crypt') {
1602             $stored_password = $dbh->getOne(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1603             $result = $this->_checkPass($submitted_password, $stored_password);
1604         } else {
1605             $okay = $dbh->getOne(sprintf($this->_authselect,
1606                                          $dbh->quote($submitted_password),
1607                                          $dbh->quote($this->_userid)));
1608             $result = !empty($okay);
1609         }
1610
1611         if ($result) {
1612             $this->_level = WIKIAUTH_USER;
1613             return $this->_level;
1614         } else {
1615             return $this->_tryNextPass($submitted_password);
1616         }
1617     }
1618
1619     function mayChangePass() {
1620         global $DBAuthParams;
1621         return !empty($DBAuthParams['auth_update']);
1622     }
1623
1624     function storePass($submitted_password) {
1625         global $DBAuthParams;
1626         $dbh = &$this->_auth_dbi;
1627         if (!empty($DBAuthParams['auth_update']) and empty($this->_authupdate)) {
1628             $this->_authupdate = str_replace(array('"$userid"','"$password"'),
1629                                              array('%s','%s'),
1630                                              $DBAuthParams['auth_update']);
1631         }
1632         if (empty($this->_authupdate)) {
1633             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1634                           E_USER_WARNING);
1635             return false;
1636         }
1637
1638         if ($this->_auth_crypt_method == 'crypt') {
1639             if (function_exists('crypt'))
1640                 $submitted_password = crypt($submitted_password);
1641         }
1642         $dbh->simpleQuery(sprintf($this->_authupdate,
1643                                   $dbh->quote($submitted_password),
1644                                   $dbh->quote($this->_userid)
1645                                   ));
1646     }
1647
1648 }
1649
1650 class _AdoDbPassUser
1651 extends _DbPassUser
1652 /**
1653  * ADODB methods
1654  * Simple sprintf, no prepare.
1655  *
1656  * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster 
1657  * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1658  *
1659  * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1660  *
1661  * @tables: user
1662  */
1663 {
1664     var $_authmethod = 'AdoDb';
1665     function _AdoDbPassUser($UserName='',$prefs=false) {
1666         if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1667             if ($prefs) $this->_prefs = $prefs;
1668             if (!isset($this->_prefs->_method))
1669               _PassUser::_PassUser($UserName);
1670         }
1671         $this->_userid = $UserName;
1672         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1673         $this->getAuthDbh();
1674         // Don't prepare the configured auth statements anymore
1675         return $this;
1676     }
1677
1678     function getPreferences() {
1679         // override the generic slow method here for efficiency
1680         _AnonUser::getPreferences();
1681         $this->getAuthDbh();
1682         if (isset($this->_prefs->_select)) {
1683             $dbh = & $this->_auth_dbi;
1684             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
1685             if ($rs->EOF) {
1686                 $rs->Close();
1687             } else {
1688                 $prefs_blob = $rs->fields['prefs'];
1689                 $rs->Close();
1690                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1691                     $updated = $this->_prefs->updatePrefs($restored_from_db);
1692                     //$this->_prefs = new UserPreferences($restored_from_db);
1693                     return $this->_prefs;
1694                 }
1695             }
1696         }
1697         if ($this->_HomePagehandle) {
1698             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1699                 $updated = $this->_prefs->updatePrefs($restored_from_page);
1700                 //$this->_prefs = new UserPreferences($restored_from_page);
1701                 return $this->_prefs;
1702             }
1703         }
1704         return $this->_prefs;
1705     }
1706
1707     function setPreferences($prefs, $id_only=false) {
1708         // if the prefs are changed
1709         if (_AnonUser::setPreferences($prefs, 1)) {
1710             global $request;
1711             $packed = $this->_prefs->store();
1712             //$user = $request->_user;
1713             //unset($user->_auth_dbi);
1714             if (!$id_only and isset($this->_prefs->_update)) {
1715                 $this->getAuthDbh();
1716                 $dbh = &$this->_auth_dbi;
1717                 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1718                                                    $dbh->qstr($packed),
1719                                                    $dbh->qstr($this->_userid)));
1720                 $db_result->Close();
1721             } else {
1722                 //store prefs in homepage, not in cookie
1723                 if ($this->_HomePagehandle and !$id_only)
1724                     $this->_HomePagehandle->set('pref', $packed);
1725             }
1726             return count($this->_prefs->unpack($packed));
1727         }
1728         return 0;
1729     }
1730  
1731     function userExists() {
1732         global $DBAuthParams;
1733         if (empty($this->_authselect) and !empty($DBAuthParams['auth_check'])) {
1734             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1735                                               $DBAuthParams['auth_check']);
1736         }
1737         if (empty($this->_authselect))
1738             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1739                           E_USER_WARNING);
1740         //$this->getAuthDbh();
1741         $dbh = &$this->_auth_dbi;
1742         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1743         if ($this->_auth_crypt_method == 'crypt') {
1744             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1745             if (!$rs->EOF) {
1746                 $rs->Close();
1747                 return true;
1748             } else {
1749                 $rs->Close();
1750             }
1751         }
1752         else {
1753             if (! $DBAuthParams['auth_user_exists'])
1754                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1755                               E_USER_WARNING);
1756             $this->_authcheck = str_replace('"$userid"','%s',
1757                                              $DBAuthParams['auth_user_exists']);
1758             $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1759             if (!$rs->EOF) {
1760                 $rs->Close();
1761                 return true;
1762             } else {
1763                 $rs->Close();
1764             }
1765         }
1766         // maybe the user is allowed to create himself. Generally not wanted in 
1767         // external databases, but maybe wanted for the wiki database, for performance 
1768         // reasons
1769         if (!$this->_authcreate and !empty($DBAuthParams['auth_create'])) {
1770             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1771                                               $DBAuthParams['auth_create']);
1772         }
1773         if (!empty($this->_authcreate)) {
1774             $dbh->Execute(sprintf($this->_authcreate,
1775                                   $dbh->qstr($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1776                                   $dbh->qstr($this->_userid)));
1777             return true;
1778         }
1779         
1780         return $this->_tryNextUser();
1781     }
1782
1783     function checkPass($submitted_password) {
1784         global $DBAuthParams;
1785         if (empty($this->_authselect) and !empty($DBAuthParams['auth_check'])) {
1786             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1787                                               $DBAuthParams['auth_check']);
1788         }
1789         if (!isset($this->_authselect))
1790             $this->userExists();
1791         if (!isset($this->_authselect))
1792             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1793                           E_USER_WARNING);
1794         //$this->getAuthDbh();
1795         $dbh = &$this->_auth_dbi;
1796         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1797         if ($this->_auth_crypt_method == 'crypt') {
1798             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1799             if (!$rs->EOF) {
1800                 $stored_password = $rs->fields['password'];
1801                 $rs->Close();
1802                 $result = $this->_checkPass($submitted_password, $stored_password);
1803             } else {
1804                 $rs->Close();
1805                 $result = false;
1806             }
1807         }
1808         else {
1809             $rs = $dbh->Execute(sprintf($this->_authselect,
1810                                         $dbh->qstr($submitted_password),
1811                                         $dbh->qstr($this->_userid)));
1812             $okay = $rs->fields['ok'];
1813             $rs->Close();
1814             $result = !empty($okay);
1815         }
1816
1817         if ($result) { 
1818             $this->_level = WIKIAUTH_USER;
1819             return $this->_level;
1820         } else {
1821             return $this->_tryNextPass($submitted_password);
1822         }
1823     }
1824
1825     function mayChangePass() {
1826         global $DBAuthParams;
1827         return !empty($DBAuthParams['auth_update']);
1828     }
1829
1830     function storePass($submitted_password) {
1831         global $DBAuthParams;
1832         if (!isset($this->_authupdate) and !empty($DBAuthParams['auth_update'])) {
1833             $this->_authupdate = str_replace(array('"$userid"','"$password"'),array("%s","%s"),
1834                                               $DBAuthParams['auth_update']);
1835         }
1836         if (!isset($this->_authupdate)) {
1837             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1838                           E_USER_WARNING);
1839             return false;
1840         }
1841
1842         if ($this->_auth_crypt_method == 'crypt') {
1843             if (function_exists('crypt'))
1844                 $submitted_password = crypt($submitted_password);
1845         }
1846         $this->getAuthDbh();
1847         $dbh = &$this->_auth_dbi;
1848         $rs = $dbh->Execute(sprintf($this->_authupdate,
1849                                     $dbh->qstr($submitted_password),
1850                                     $dbh->qstr($this->_userid)
1851                                     ));
1852         $rs->Close();
1853         return $rs;
1854     }
1855
1856 }
1857
1858 class _LDAPPassUser
1859 extends _PassUser
1860 /**
1861  * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in index.php
1862  *
1863  * Preferences are handled in _PassUser
1864  */
1865 {
1866     function checkPass($submitted_password) {
1867         global $LDAP_SET_OPTION;
1868
1869         $this->_authmethod = 'LDAP';
1870         $userid = $this->_userid;
1871         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1872             if (defined('LDAP_AUTH_USER'))
1873                 if (defined('LDAP_AUTH_PASSWORD'))
1874                     // Windows Active Directory Server is strict
1875                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1876                 else
1877                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1878             else
1879                 $r = @ldap_bind($ldap); // this is an anonymous bind
1880             if (!empty($LDAP_SET_OPTION)) {
1881                 foreach ($LDAP_SET_OPTION as $key => $value) {
1882                     ldap_set_option($ldap,$key,$value);
1883                 }
1884             }
1885             // Need to set the right root search information. see ../index.php
1886             $st_search = defined('LDAP_SEARCH_FIELD') 
1887                 ? LDAP_SEARCH_FIELD."=$userid"
1888                 : "uid=$userid";
1889             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1890             $info = ldap_get_entries($ldap, $sr); 
1891             // there may be more hits with this userid.
1892             // of course it would be better to narrow down the BASE_DN
1893             for ($i = 0; $i < $info["count"]; $i++) {
1894                 $dn = $info[$i]["dn"];
1895                 // The password is still plain text.
1896                 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
1897                     // ldap_bind will return TRUE if everything matches
1898                     ldap_close($ldap);
1899                     $this->_level = WIKIAUTH_USER;
1900                     return $this->_level;
1901                 }
1902             }
1903         } else {
1904             trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), 
1905                           E_USER_WARNING);
1906             //return false;
1907         }
1908
1909         return $this->_tryNextPass($submitted_password);
1910     }
1911
1912     function userExists() {
1913         global $LDAP_SET_OPTION;
1914
1915         $userid = $this->_userid;
1916         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1917             if (defined('LDAP_AUTH_USER'))
1918                 if (defined('LDAP_AUTH_PASSWORD'))
1919                     // Windows Active Directory Server is strict
1920                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1921                 else
1922                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1923             else
1924                 $r = @ldap_bind($ldap); // this is an anonymous bind
1925             if (!empty($LDAP_SET_OPTION)) {
1926                 foreach ($LDAP_SET_OPTION as $key => $value) {
1927                     ldap_set_option($ldap,$key,$value);
1928                 }
1929             }
1930             // Need to set the right root search information. see ../index.php
1931             $st_search = defined('LDAP_SEARCH_FIELD') 
1932                 ? LDAP_SEARCH_FIELD."=$userid"
1933                 : "uid=$userid";
1934             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1935             $info = ldap_get_entries($ldap, $sr); 
1936
1937             if ($info["count"] > 0) {
1938                 ldap_close($ldap);
1939                 return true;
1940             }
1941         } else {
1942             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1943         }
1944
1945         return $this->_tryNextUser();
1946     }
1947
1948     function mayChangePass() {
1949         return false;
1950     }
1951
1952 }
1953
1954 class _IMAPPassUser
1955 extends _PassUser
1956 /**
1957  * Define the var IMAP_AUTH_HOST in index.php (with port probably)
1958  *
1959  * Preferences are handled in _PassUser
1960  */
1961 {
1962     function checkPass($submitted_password) {
1963         $userid = $this->_userid;
1964         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1965                             $userid, $submitted_password, OP_HALFOPEN );
1966         if ($mbox) {
1967             imap_close($mbox);
1968             $this->_authmethod = 'IMAP';
1969             $this->_level = WIKIAUTH_USER;
1970             return $this->_level;
1971         } else {
1972             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1973         }
1974
1975         return $this->_tryNextPass($submitted_password);
1976     }
1977
1978     //CHECKME: this will not be okay for the auth policy strict
1979     function userExists() {
1980         return true;
1981         if (checkPass($this->_prefs->get('passwd')))
1982             return true;
1983             
1984         return $this->_tryNextUser();
1985     }
1986
1987     function mayChangePass() {
1988         return false;
1989     }
1990 }
1991
1992
1993 class _POP3PassUser
1994 extends _IMAPPassUser {
1995 /**
1996  * Define the var POP3_AUTH_HOST in index.php
1997  * Preferences are handled in _PassUser
1998  */
1999     function checkPass($submitted_password) {
2000         $userid = $this->_userid;
2001         $pass = $submitted_password;
2002         $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost';
2003         $port = defined('POP3_AUTH_PORT') ? POP3_AUTH_PORT : 110;
2004         $retval = false;
2005         $fp = fsockopen($host, $port, $errno, $errstr, 10);
2006         if ($fp) {
2007             // Get welcome string
2008             $line = fgets($fp, 1024);
2009             if (! strncmp("+OK ", $line, 4)) {
2010                 // Send user name
2011                 fputs($fp, "user $user\n");
2012                 // Get response
2013                 $line = fgets($fp, 1024);
2014                 if (! strncmp("+OK ", $line, 4)) {
2015                     // Send password
2016                     fputs($fp, "pass $pass\n");
2017                     // Get response
2018                     $line = fgets($fp, 1024);
2019                     if (! strncmp("+OK ", $line, 4)) {
2020                         $retval = true;
2021                     }
2022                 }
2023             }
2024             // quit the connection
2025             fputs($fp, "quit\n");
2026             // Get the sayonara message
2027             $line = fgets($fp, 1024);
2028             fclose($fp);
2029         }
2030         $this->_authmethod = 'POP3';
2031         if ($retval) {
2032             $this->_level = WIKIAUTH_USER;
2033         } else {
2034             $this->_level = WIKIAUTH_ANON;
2035         }
2036         return $this->_level;
2037     }
2038 }
2039
2040 class _FilePassUser
2041 extends _PassUser
2042 /**
2043  * Check users defined in a .htaccess style file
2044  * username:crypt\n...
2045  *
2046  * Preferences are handled in _PassUser
2047  */
2048 {
2049     var $_file, $_may_change;
2050
2051     // This can only be called from _PassUser, because the parent class 
2052     // sets the pref methods, before this class is initialized.
2053     function _FilePassUser($UserName='',$prefs=false,$file='') {
2054         if (!$this->_prefs and isa($this,"_FilePassUser")) {
2055             if ($prefs) $this->_prefs = $prefs;
2056             if (!isset($this->_prefs->_method))
2057               _PassUser::_PassUser($UserName);
2058         }
2059
2060         $this->_userid = $UserName;
2061         // read the .htaccess style file. We use our own copy of the standard pear class.
2062         include_once 'lib/pear/File_Passwd.php';
2063         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
2064         if (empty($file) and defined('AUTH_USER_FILE'))
2065             $file = AUTH_USER_FILE;
2066         // if passwords may be changed we have to lock them:
2067         if ($this->_may_change) {
2068             $lock = true;
2069             $lockfile = $file . ".lock";
2070         } else {
2071             $lock = false;
2072             $lockfile = false;
2073         }
2074         // "__PHP_Incomplete_Class"
2075         if (!empty($file) or empty($this->_file) or !isa($this->_file,"File_Passwd"))
2076             $this->_file = new File_Passwd($file, $lock, $lockfile);
2077         else
2078             return false;
2079         return $this;
2080     }
2081  
2082     function mayChangePass() {
2083         return $this->_may_change;
2084     }
2085
2086     function userExists() {
2087         $this->_authmethod = 'File';
2088         if (isset($this->_file->users[$this->_userid]))
2089             return true;
2090             
2091         return $this->_tryNextUser();
2092     }
2093
2094     function checkPass($submitted_password) {
2095         include_once 'lib/pear/File_Passwd.php';
2096         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
2097             $this->_authmethod = 'File';
2098             $this->_level = WIKIAUTH_USER;
2099             return $this->_level;
2100         }
2101         
2102         return $this->_tryNextPass($submitted_password);
2103     }
2104
2105     function storePass($submitted_password) {
2106         if ($this->_may_change) {
2107             if ($this->_file->modUser($this->_userid,$submitted_password)) {
2108                 $this->_file->close();
2109                 $this->_file = new File_Passwd($this->_file->_filename, true, $this->_file->lockfile);
2110                 return true;
2111             }
2112         }
2113         return false;
2114     }
2115
2116 }
2117
2118 /**
2119  * Insert more auth classes here...
2120  * For example a customized db class for another db connection 
2121  * or a socket-based auth server
2122  *
2123  */
2124
2125
2126 /**
2127  * For security, this class should not be extended. Instead, extend
2128  * from _PassUser (think of this as unix "root").
2129  */
2130 class _AdminUser
2131 extends _PassUser
2132 {
2133     function mayChangePass() {
2134         return false;
2135     }
2136     function checkPass($submitted_password) {
2137         $stored_password = ADMIN_PASSWD;
2138         if ($this->_checkPass($submitted_password, $stored_password)) {
2139             $this->_level = WIKIAUTH_ADMIN;
2140             return $this->_level;
2141         } else {
2142             $this->_level = WIKIAUTH_ANON;
2143             return $this->_level;
2144         }
2145     }
2146     function storePass($submitted_password) {
2147         return false;
2148     }
2149 }
2150
2151 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2152 /**
2153  * Various data classes for the preference types, 
2154  * to support get, set, sanify (range checking, ...)
2155  * update() will do the neccessary side-effects if a 
2156  * setting gets changed (theme, language, ...)
2157 */
2158
2159 class _UserPreference
2160 {
2161     var $default_value;
2162
2163     function _UserPreference ($default_value) {
2164         $this->default_value = $default_value;
2165     }
2166
2167     function sanify ($value) {
2168         return (string)$value;
2169     }
2170
2171     function get ($name) {
2172         if (isset($this->{$name}))
2173             return $this->{$name};
2174         else 
2175             return $this->default_value;
2176     }
2177
2178     function getraw ($name) {
2179         if (!empty($this->{$name}))
2180             return $this->{$name};
2181     }
2182
2183     // stores the value as $this->$name, and not as $this->value (clever?)
2184     function set ($name, $value) {
2185         if ($this->get($name) != $value) {
2186             $this->update($value);
2187         }
2188         if ($value != $this->default_value) {
2189             $this->{$name} = $value;
2190         }
2191         else 
2192             unset($this->{$name});
2193     }
2194
2195     // default: no side-effects 
2196     function update ($value) {
2197         ;
2198     }
2199 }
2200
2201 class _UserPreference_numeric
2202 extends _UserPreference
2203 {
2204     function _UserPreference_numeric ($default, $minval = false,
2205                                       $maxval = false) {
2206         $this->_UserPreference((double)$default);
2207         $this->_minval = (double)$minval;
2208         $this->_maxval = (double)$maxval;
2209     }
2210
2211     function sanify ($value) {
2212         $value = (double)$value;
2213         if ($this->_minval !== false && $value < $this->_minval)
2214             $value = $this->_minval;
2215         if ($this->_maxval !== false && $value > $this->_maxval)
2216             $value = $this->_maxval;
2217         return $value;
2218     }
2219 }
2220
2221 class _UserPreference_int
2222 extends _UserPreference_numeric
2223 {
2224     function _UserPreference_int ($default, $minval = false, $maxval = false) {
2225         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
2226     }
2227
2228     function sanify ($value) {
2229         return (int)parent::sanify((int)$value);
2230     }
2231 }
2232
2233 class _UserPreference_bool
2234 extends _UserPreference
2235 {
2236     function _UserPreference_bool ($default = false) {
2237         $this->_UserPreference((bool)$default);
2238     }
2239
2240     function sanify ($value) {
2241         if (is_array($value)) {
2242             /* This allows for constructs like:
2243              *
2244              *   <input type="hidden" name="pref[boolPref][]" value="0" />
2245              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
2246              *
2247              * (If the checkbox is not checked, only the hidden input
2248              * gets sent. If the checkbox is sent, both inputs get
2249              * sent.)
2250              */
2251             foreach ($value as $val) {
2252                 if ($val)
2253                     return true;
2254             }
2255             return false;
2256         }
2257         return (bool) $value;
2258     }
2259 }
2260
2261 class _UserPreference_language
2262 extends _UserPreference
2263 {
2264     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
2265         $this->_UserPreference($default);
2266     }
2267
2268     // FIXME: check for valid locale
2269     function sanify ($value) {
2270         // Revert to DEFAULT_LANGUAGE if user does not specify
2271         // language in UserPreferences or chooses <system language>.
2272         if ($value == '' or empty($value))
2273             $value = DEFAULT_LANGUAGE;
2274
2275         return (string) $value;
2276     }
2277     
2278     function update ($newvalue) {
2279         if (! $this->_init ) {
2280             // invalidate etag to force fresh output
2281             $GLOBALS['request']->setValidators(array('%mtime' => false));
2282             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
2283         }
2284     }
2285 }
2286
2287 class _UserPreference_theme
2288 extends _UserPreference
2289 {
2290     function _UserPreference_theme ($default = THEME) {
2291         $this->_UserPreference($default);
2292     }
2293
2294     function sanify ($value) {
2295         if (!empty($value) and FindFile($this->_themefile($value)))
2296             return $value;
2297         return $this->default_value;
2298     }
2299
2300     function update ($newvalue) {
2301         global $Theme;
2302         // invalidate etag to force fresh output
2303         if (! $this->_init )
2304             $GLOBALS['request']->setValidators(array('%mtime' => false));
2305         if ($newvalue)
2306             include_once($this->_themefile($newvalue));
2307         if (empty($Theme))
2308             include_once($this->_themefile(THEME));
2309     }
2310
2311     function _themefile ($theme) {
2312         return "themes/$theme/themeinfo.php";
2313     }
2314 }
2315
2316 class _UserPreference_notify
2317 extends _UserPreference
2318 {
2319     function sanify ($value) {
2320         if (!empty($value))
2321             return $value;
2322         else
2323             return $this->default_value;
2324     }
2325
2326     /** update to global user prefs: side-effect on set notify changes
2327      * use a global_data notify hash:
2328      * notify = array('pagematch' => array(userid => ('email' => mail, 
2329      *                                                'verified' => 0|1),
2330      *                                     ...),
2331      *                ...);
2332      */
2333     function update ($value) {
2334         if (!empty($this->_init)) return;
2335         $dbh = $GLOBALS['request']->getDbh();
2336         $notify = $dbh->get('notify');
2337         if (empty($notify))
2338             $data = array();
2339         else 
2340             $data = & $notify;
2341         // expand to existing pages only or store matches?
2342         // for now we store (glob-style) matches which is easier for the user
2343         $pages = $this->_page_split($value);
2344         // Limitation: only current user.
2345         $user = $GLOBALS['request']->getUser();
2346         if (!$user or !method_exists($user,'UserName')) return;
2347         // This fails with php5 and a WIKI_ID cookie:
2348         $userid = $user->UserName();
2349         $email  = $user->_prefs->get('email');
2350         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
2351         // check existing notify hash and possibly delete pages for email
2352         if (!empty($data)) {
2353             foreach ($data as $page => $users) {
2354                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
2355                     unset($data[$page][$userid]);
2356                 }
2357                 if (count($data[$page]) == 0)
2358                     unset($data[$page]);
2359             }
2360         }
2361         // add the new pages
2362         if (!empty($pages)) {
2363             foreach ($pages as $page) {
2364                 if (!isset($data[$page]))
2365                     $data[$page] = array();
2366                 if (!isset($data[$page][$userid])) {
2367                     // should we really store the verification notice here or 
2368                     // check it dynamically at every page->save?
2369                     if ($verified) {
2370                         $data[$page][$userid] = array('email' => $email,
2371                                                       'verified' => $verified);
2372                     } else {
2373                         $data[$page][$userid] = array('email' => $email);
2374                     }
2375                 }
2376             }
2377         }
2378         // store users changes
2379         $dbh->set('notify',$data);
2380     }
2381
2382     /** split the user-given comma or whitespace delimited pagenames
2383      *  to array
2384      */
2385     function _page_split($value) {
2386         return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
2387     }
2388 }
2389
2390 class _UserPreference_email
2391 extends _UserPreference
2392 {
2393     function sanify ($value) {
2394         // check for valid email address
2395         if ($this->get('email') == $value and $this->getraw('emailVerified'))
2396             return $value;
2397         list($ok,$msg) = ValidateMail($value,'noconnect');
2398         if ($ok) {
2399             return $value;
2400         } else {
2401             trigger_error($msg, E_USER_WARNING);
2402             return $this->default_value;
2403         }
2404     }
2405     
2406     /** Side-effect on email changes:
2407      * Send a verification mail or for now just a notification email.
2408      * For true verification (value = 2), we'd need a mailserver hook.
2409      */
2410     function update ($value) {
2411         if (!empty($this->_init)) return;
2412         $verified = $this->getraw('emailVerified');
2413         if (!empty($value) and !$verified) {
2414             list($ok,$msg) = ValidateMail($value);
2415             if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
2416                      sprintf(_("Welcome to %s!\nYou email account is verified and\nwill be used to send pagechange notifications.\nSee %s"),
2417                              WIKI_NAME, WikiUrl($GLOBALS['request']->getArg('pagename'),'',true))))
2418                 $this->set('emailVerified',1);
2419         }
2420     }
2421 }
2422
2423 /** Check for valid email address
2424     fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
2425  */
2426 function ValidateMail($email, $noconnect=false) {
2427     $HTTP_HOST = $_SERVER['HTTP_HOST'];
2428     $result = array();
2429     // well, technically ".a.a.@host.com" is also valid
2430     if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
2431         $result[0] = false;
2432         $result[1] = "$email is not properly formatted";
2433         return $result;
2434     }
2435     if ($noconnect)
2436       return array(true,"$email is properly formatted");
2437
2438     list ( $Username, $Domain ) = split ("@",$email);
2439     //Todo: getmxrr workaround on windows or manual input field to verify it manually
2440     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. 
2441         $ConnectAddress = $MXHost[0];
2442     } else {
2443         $ConnectAddress = $Domain;
2444     }
2445     $Connect = fsockopen ( $ConnectAddress, 25 );
2446     if ($Connect) {
2447         if (ereg("^220", $Out = fgets($Connect, 1024))) {
2448             fputs ($Connect, "HELO $HTTP_HOST\r\n");
2449             $Out = fgets ( $Connect, 1024 );
2450             fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
2451             $From = fgets ( $Connect, 1024 );
2452             fputs ($Connect, "RCPT TO: <".$email.">\r\n");
2453             $To = fgets ($Connect, 1024);
2454             fputs ($Connect, "QUIT\r\n");
2455             fclose($Connect);
2456             if (!ereg ("^250", $From)) {
2457                 $result[0]=false;
2458                 $result[1]="Server rejected address: ". $From;
2459                 return $result;
2460             }
2461             if (!ereg ( "^250", $To )) {
2462                 $result[0]=false;
2463                 $result[1]="Server rejected address: ". $To;
2464                 return $result;
2465             }
2466         } else {
2467             $result[0] = false;
2468             $result[1] = "No response from server";
2469             return $result;
2470           }
2471     }  else {
2472         $result[0]=false;
2473         $result[1]="Can not connect E-Mail server.";
2474         return $result;
2475     }
2476     $result[0]=true;
2477     $result[1]="$email appears to be valid.";
2478     return $result;
2479 } // end of function 
2480
2481 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2482
2483 /**
2484  * UserPreferences
2485  * 
2486  * This object holds the $request->_prefs subobjects.
2487  * A simple packed array of non-default values get's stored as cookie,
2488  * homepage, or database, which are converted to the array of 
2489  * ->_prefs objects.
2490  * We don't store the objects, because otherwise we will
2491  * not be able to upgrade any subobject. And it's a waste of space also.
2492  *
2493  */
2494 class UserPreferences
2495 {
2496     function UserPreferences($saved_prefs = false) {
2497         // userid stored too, to ensure the prefs are being loaded for
2498         // the correct (currently signing in) userid if stored in a
2499         // cookie.
2500         // Update: for db prefs we disallow passwd. 
2501         // userid is needed for pref reflexion. current pref must know its username, 
2502         // if some app needs prefs from different users, different from current user.
2503         $this->_prefs
2504             = array(
2505                     'userid'        => new _UserPreference(''),
2506                     'passwd'        => new _UserPreference(''),
2507                     'autologin'     => new _UserPreference_bool(),
2508                     //'emailVerified' => new _UserPreference_emailVerified(), 
2509                     //fixed: store emailVerified as email parameter, 1.3.8
2510                     'email'         => new _UserPreference_email(''),
2511                     'notifyPages'   => new _UserPreference_notify(''), // 1.3.8
2512                     'theme'         => new _UserPreference_theme(THEME),
2513                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
2514                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2515                                                                EDITWIDTH_MIN_COLS,
2516                                                                EDITWIDTH_MAX_COLS),
2517                     'noLinkIcons'   => new _UserPreference_bool(),    // 1.3.8 
2518                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2519                                                                EDITHEIGHT_MIN_ROWS,
2520                                                                EDITHEIGHT_DEFAULT_ROWS),
2521                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2522                                                                    TIMEOFFSET_MIN_HOURS,
2523                                                                    TIMEOFFSET_MAX_HOURS),
2524                     'relativeDates' => new _UserPreference_bool(),
2525                     'googleLink'    => new _UserPreference_bool(), // 1.3.10
2526                     );
2527         // add custom theme-specific pref types:
2528         // FIXME: on theme changes the wiki_user session pref object will fail. 
2529         // We will silently ignore this.
2530         if (!empty($customUserPreferenceColumns))
2531             $this->_prefs = array_merge($this->_prefs,$customUserPreferenceColumns);
2532
2533         if (isset($this->_method) and $this->_method == 'SQL') {
2534             //unset($this->_prefs['userid']);
2535             unset($this->_prefs['passwd']);
2536         }
2537
2538         if (is_array($saved_prefs)) {
2539             foreach ($saved_prefs as $name => $value)
2540                 $this->set($name, $value);
2541         }
2542     }
2543
2544     function _getPref($name) {
2545         if ($name == 'emailVerified')
2546             $name = 'email';
2547         if (!isset($this->_prefs[$name])) {
2548             if ($name == 'passwd2') return false;
2549             trigger_error("$name: unknown preference", E_USER_NOTICE);
2550             return false;
2551         }
2552         return $this->_prefs[$name];
2553     }
2554     
2555     // get the value or default_value of the subobject
2556     function get($name) {
2557         if ($_pref = $this->_getPref($name))
2558             if ($name == 'emailVerified')
2559                 return $_pref->getraw($name);
2560             else
2561                 return $_pref->get($name);
2562         else
2563             return false;  
2564     }
2565
2566     // check and set the new value in the subobject
2567     function set($name, $value) {
2568         $pref = $this->_getPref($name);
2569         if ($pref === false)
2570             return false;
2571
2572         /* do it here or outside? */
2573         if ($name == 'passwd' and 
2574             defined('PASSWORD_LENGTH_MINIMUM') and 
2575             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2576             //TODO: How to notify the user?
2577             return false;
2578         }
2579         /*
2580         if ($name == 'theme' and $value == '')
2581            return true;
2582         */
2583         if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
2584             if ($name == 'emailVerified') $newvalue = $value;
2585             else $newvalue = $pref->sanify($value);
2586             $pref->set($name,$newvalue);
2587         }
2588         $this->_prefs[$name] =& $pref;
2589         return true;
2590     }
2591     /**
2592      * use init to avoid update on set
2593      */
2594     function updatePrefs($prefs, $init = false) {
2595         $count = 0;
2596         if ($init) $this->_init = $init;
2597         if (is_object($prefs)) {
2598             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2599             $obj->_init = $init;
2600             if ($obj->get($type) !== $prefs->get($type)) {
2601                 $obj->set($type,$prefs->get($type));
2602                 $count++;
2603             }
2604             foreach (array_keys($this->_prefs) as $type) {
2605                 $obj =& $this->_prefs[$type];
2606                 $obj->_init = $init;
2607                 if ($this->_prefs[$type]->get($type) !== $prefs->get($type)) {
2608                     $this->_prefs[$type]->set($type,$prefs->get($type));
2609                     $count++;
2610                 }
2611             }
2612         } elseif (is_array($prefs)) {
2613             //unset($this->_prefs['userid']);
2614             if (isset($this->_method) and $this->_method == 'SQL') {
2615                 unset($this->_prefs['passwd']);
2616             }
2617             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2618             $obj->_init = $init;
2619             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2620                 $obj->set($type,$prefs[$type]);
2621                 $count++;
2622             }
2623             foreach (array_keys($this->_prefs) as $type) {
2624                 $obj =& $this->_prefs[$type];
2625                 $obj->_init = $init;
2626                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2627                     $obj->set($type,$prefs[$type]);
2628                     $count++;
2629                 }
2630             }
2631         }
2632         return $count;
2633     }
2634
2635     // for now convert just array of objects => array of values
2636     // Todo: the specialized subobjects must override this.
2637     function store() {
2638         $prefs = array();
2639         foreach ($this->_prefs as $name => $object) {
2640             if ($value = $object->getraw($name))
2641                 $prefs[$name] = $value;
2642             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2643                 $prefs['emailVerified'] = $value;
2644         }
2645         return $this->pack($prefs);
2646     }
2647
2648     // packed string or array of values => array of values
2649     // Todo: the specialized subobjects must override this.
2650     function retrieve($packed) {
2651         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2652             $packed = unserialize($packed);
2653         if (!is_array($packed)) return false;
2654         $prefs = array();
2655         foreach ($packed as $name => $packed_pref) {
2656             if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2657                 //legacy: check if it's an old array of objects
2658                 // Looks like a serialized object. 
2659                 // This might fail if the object definition does not exist anymore.
2660                 // object with ->$name and ->default_value vars.
2661                 $pref =  @unserialize($packed_pref);
2662                 if (empty($pref))
2663                     $pref = @unserialize(base64_decode($packed_pref));
2664                 $prefs[$name] = $pref->get($name);
2665             // fix old-style prefs
2666             } elseif (is_numeric($name) and is_array($packed_pref)) {
2667                 if (count($packed_pref) == 1) {
2668                     list($name,$value) = each($packed_pref);
2669                     $prefs[$name] = $value;
2670                 }
2671             } else {
2672                 $prefs[$name] = @unserialize($packed_pref);
2673                 if (empty($prefs[$name]))
2674                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
2675                 // patched by frederik@pandora.be
2676                 if (empty($prefs[$name]))
2677                     $prefs[$name] = $packed_pref;
2678             }
2679         }
2680         return $prefs;
2681     }
2682
2683     /**
2684      * Check if the given prefs object is different from the current prefs object
2685      */
2686     function isChanged($other) {
2687         foreach ($this->_prefs as $type => $obj) {
2688             if ($obj->get($type) !== $other->get($type))
2689                 return true;
2690         }
2691         return false;
2692     }
2693
2694     // array of objects
2695     function getAll() {
2696         return $this->_prefs;
2697     }
2698
2699     function pack($nonpacked) {
2700         return serialize($nonpacked);
2701     }
2702
2703     function unpack($packed) {
2704         if (!$packed)
2705             return false;
2706         //$packed = base64_decode($packed);
2707         if (substr($packed, 0, 2) == "O:") {
2708             // Looks like a serialized object
2709             return unserialize($packed);
2710         }
2711         if (substr($packed, 0, 2) == "a:") {
2712             return unserialize($packed);
2713         }
2714         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2715         //E_USER_WARNING);
2716         return false;
2717     }
2718
2719     function hash () {
2720         return hash($this->_prefs);
2721     }
2722 }
2723
2724 /** TODO: new pref storage classes
2725  *  These are currently user specific and should be rewritten to be pref specific.
2726  *  i.e. $this == $user->_prefs
2727  */
2728 class CookieUserPreferences
2729 extends UserPreferences
2730 {
2731     function CookieUserPreferences ($saved_prefs = false) {
2732         //_AnonUser::_AnonUser('',$saved_prefs);
2733         UserPreferences::UserPreferences($saved_prefs);
2734     }
2735 }
2736
2737 class PageUserPreferences
2738 extends UserPreferences
2739 {
2740     function PageUserPreferences ($saved_prefs = false) {
2741         UserPreferences::UserPreferences($saved_prefs);
2742     }
2743 }
2744
2745 class PearDbUserPreferences
2746 extends UserPreferences
2747 {
2748     function PearDbUserPreferences ($saved_prefs = false) {
2749         UserPreferences::UserPreferences($saved_prefs);
2750     }
2751 }
2752
2753 class AdoDbUserPreferences
2754 extends UserPreferences
2755 {
2756     function AdoDbUserPreferences ($saved_prefs = false) {
2757         UserPreferences::UserPreferences($saved_prefs);
2758     }
2759     function getPreferences() {
2760         // override the generic slow method here for efficiency
2761         _AnonUser::getPreferences();
2762         $this->getAuthDbh();
2763         if (isset($this->_select)) {
2764             $dbh = & $this->_auth_dbi;
2765             $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2766             if ($rs->EOF) {
2767                 $rs->Close();
2768             } else {
2769                 $prefs_blob = $rs->fields['pref_blob'];
2770                 $rs->Close();
2771                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2772                     $updated = $this->_prefs->updatePrefs($restored_from_db);
2773                     //$this->_prefs = new UserPreferences($restored_from_db);
2774                     return $this->_prefs;
2775                 }
2776             }
2777         }
2778         if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2779             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2780                 $updated = $this->_prefs->updatePrefs($restored_from_page);
2781                 //$this->_prefs = new UserPreferences($restored_from_page);
2782                 return $this->_prefs;
2783             }
2784         }
2785         return $this->_prefs;
2786     }
2787 }
2788
2789
2790 // $Log: not supported by cvs2svn $
2791 // Revision 1.56  2004/04/19 09:13:24  rurban
2792 // new pref: googleLink
2793 //
2794 // Revision 1.54  2004/04/18 00:24:45  rurban
2795 // re-use our simple prepare: just for table prefix warnings
2796 //
2797 // Revision 1.53  2004/04/12 18:29:15  rurban
2798 // exp. Session auth for already authenticated users from another app
2799 //
2800 // Revision 1.52  2004/04/12 13:04:50  rurban
2801 // added auth_create: self-registering Db users
2802 // fixed IMAP auth
2803 // removed rating recommendations
2804 // ziplib reformatting
2805 //
2806 // Revision 1.51  2004/04/11 10:42:02  rurban
2807 // pgsrc/CreatePagePlugin
2808 //
2809 // Revision 1.50  2004/04/10 05:34:35  rurban
2810 // sf bug#830912
2811 //
2812 // Revision 1.49  2004/04/07 23:13:18  rurban
2813 // fixed pear/File_Passwd for Windows
2814 // fixed FilePassUser sessions (filehandle revive) and password update
2815 //
2816 // Revision 1.48  2004/04/06 20:00:10  rurban
2817 // Cleanup of special PageList column types
2818 // Added support of plugin and theme specific Pagelist Types
2819 // Added support for theme specific UserPreferences
2820 // Added session support for ip-based throttling
2821 //   sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
2822 // Enhanced postgres schema
2823 // Added DB_Session_dba support
2824 //
2825 // Revision 1.47  2004/04/02 15:06:55  rurban
2826 // fixed a nasty ADODB_mysql session update bug
2827 // improved UserPreferences layout (tabled hints)
2828 // fixed UserPreferences auth handling
2829 // improved auth stability
2830 // improved old cookie handling: fixed deletion of old cookies with paths
2831 //
2832 // Revision 1.46  2004/04/01 06:29:51  rurban
2833 // better wording
2834 // RateIt also for ADODB
2835 //
2836 // Revision 1.45  2004/03/30 02:14:03  rurban
2837 // fixed yet another Prefs bug
2838 // added generic PearDb_iter
2839 // $request->appendValidators no so strict as before
2840 // added some box plugin methods
2841 // PageList commalist for condensed output
2842 //
2843 // Revision 1.44  2004/03/27 22:01:03  rurban
2844 // two catches by Konstantin Zadorozhny
2845 //
2846 // Revision 1.43  2004/03/27 19:40:09  rurban
2847 // init fix and validator reset
2848 //
2849 // Revision 1.40  2004/03/25 22:54:31  rurban
2850 // fixed HttpAuth
2851 //
2852 // Revision 1.38  2004/03/25 17:37:36  rurban
2853 // helper to patch to and from php5 (workaround for stricter parser, no macros in php)
2854 //
2855 // Revision 1.37  2004/03/25 17:00:31  rurban
2856 // more code to convert old-style pref array to new hash
2857 //
2858 // Revision 1.36  2004/03/24 19:39:02  rurban
2859 // php5 workaround code (plus some interim debugging code in XmlElement)
2860 //   php5 doesn't work yet with the current XmlElement class constructors,
2861 //   WikiUserNew does work better than php4.
2862 // rewrote WikiUserNew user upgrading to ease php5 update
2863 // fixed pref handling in WikiUserNew
2864 // added Email Notification
2865 // added simple Email verification
2866 // removed emailVerify userpref subclass: just a email property
2867 // changed pref binary storage layout: numarray => hash of non default values
2868 // print optimize message only if really done.
2869 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2870 //   prefs should be stored in db or homepage, besides the current session.
2871 //
2872 // Revision 1.35  2004/03/18 22:18:31  rurban
2873 // workaround for php5 object upgrading problem
2874 //
2875 // Revision 1.34  2004/03/18 21:41:09  rurban
2876 // fixed sqlite support
2877 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2878 //
2879 // Revision 1.33  2004/03/16 15:42:04  rurban
2880 // more fixes for undefined property warnings
2881 //
2882 // Revision 1.32  2004/03/14 16:30:52  rurban
2883 // db-handle session revivification, dba fixes
2884 //
2885 // Revision 1.31  2004/03/12 23:20:58  rurban
2886 // pref fixes (base64)
2887 //
2888 // Revision 1.30  2004/03/12 20:59:17  rurban
2889 // important cookie fix by Konstantin Zadorozhny
2890 // new editpage feature: JS_SEARCHREPLACE
2891 //
2892 // Revision 1.29  2004/03/11 13:30:47  rurban
2893 // fixed File Auth for user and group
2894 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
2895 //
2896 // Revision 1.28  2004/03/08 18:17:09  rurban
2897 // added more WikiGroup::getMembersOf methods, esp. for special groups
2898 // fixed $LDAP_SET_OPTIONS
2899 // fixed _AuthInfo group methods
2900 //
2901 // Revision 1.27  2004/03/01 09:35:13  rurban
2902 // fixed DbPassuser pref init; lost userid
2903 //
2904 // Revision 1.26  2004/02/29 04:10:56  rurban
2905 // new POP3 auth (thanks to BiloBilo: pentothal at despammed dot com)
2906 // fixed syntax error in index.php
2907 //
2908 // Revision 1.25  2004/02/28 22:25:07  rurban
2909 // First PagePerm implementation:
2910 //
2911 // $Theme->setAnonEditUnknownLinks(false);
2912 //
2913 // Layout improvement with dangling links for mostly closed wiki's:
2914 // If false, only users with edit permissions will be presented the
2915 // special wikiunknown class with "?" and Tooltip.
2916 // If true (default), any user will see the ?, but will be presented
2917 // the PrintLoginForm on a click.
2918 //
2919 // Revision 1.24  2004/02/28 21:14:08  rurban
2920 // generally more PHPDOC docs
2921 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2922 // fxied WikiUserNew pref handling: empty theme not stored, save only
2923 //   changed prefs, sql prefs improved, fixed password update,
2924 //   removed REPLACE sql (dangerous)
2925 // moved gettext init after the locale was guessed
2926 // + some minor changes
2927 //
2928 // Revision 1.23  2004/02/27 13:21:17  rurban
2929 // several performance improvements, esp. with peardb
2930 // simplified loops
2931 // storepass seperated from prefs if defined so
2932 // stacked and strict still not working
2933 //
2934 // Revision 1.22  2004/02/27 05:15:40  rurban
2935 // more stability. detected by Micki
2936 //
2937 // Revision 1.21  2004/02/26 20:43:49  rurban
2938 // new HttpAuthPassUser class (forces http auth if in the auth loop)
2939 // fixed user upgrade: don't return _PassUser in the first hand.
2940 //
2941 // Revision 1.20  2004/02/26 01:29:11  rurban
2942 // important fixes: endless loops in certain cases. minor rewrite
2943 //
2944 // Revision 1.19  2004/02/25 17:15:17  rurban
2945 // improve stability
2946 //
2947 // Revision 1.18  2004/02/24 15:20:05  rurban
2948 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
2949 //
2950 // Revision 1.17  2004/02/17 12:16:42  rurban
2951 // started with changePass support. not yet used.
2952 //
2953 // Revision 1.16  2004/02/15 22:23:45  rurban
2954 // oops, fixed showstopper (endless recursion)
2955 //
2956 // Revision 1.15  2004/02/15 21:34:37  rurban
2957 // PageList enhanced and improved.
2958 // fixed new WikiAdmin... plugins
2959 // editpage, Theme with exp. htmlarea framework
2960 //   (htmlarea yet committed, this is really questionable)
2961 // WikiUser... code with better session handling for prefs
2962 // enhanced UserPreferences (again)
2963 // RecentChanges for show_deleted: how should pages be deleted then?
2964 //
2965 // Revision 1.14  2004/02/15 17:30:13  rurban
2966 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
2967 // fixed getPreferences() (esp. from sessions)
2968 // fixed setPreferences() (update and set),
2969 // fixed AdoDb DB statements,
2970 // update prefs only at UserPreferences POST (for testing)
2971 // unified db prefs methods (but in external pref classes yet)
2972 //
2973 // Revision 1.13  2004/02/09 03:58:12  rurban
2974 // for now default DB_SESSION to false
2975 // PagePerm:
2976 //   * not existing perms will now query the parent, and not
2977 //     return the default perm
2978 //   * added pagePermissions func which returns the object per page
2979 //   * added getAccessDescription
2980 // WikiUserNew:
2981 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
2982 //   * force init of authdbh in the 2 db classes
2983 // main:
2984 //   * fixed session handling (not triple auth request anymore)
2985 //   * don't store cookie prefs with sessions
2986 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
2987 //
2988 // Revision 1.12  2004/02/07 10:41:25  rurban
2989 // fixed auth from session (still double code but works)
2990 // fixed GroupDB
2991 // fixed DbPassUser upgrade and policy=old
2992 // added GroupLdap
2993 //
2994 // Revision 1.11  2004/02/03 09:45:39  rurban
2995 // LDAP cleanup, start of new Pref classes
2996 //
2997 // Revision 1.10  2004/02/01 09:14:11  rurban
2998 // Started with Group_Ldap (not yet ready)
2999 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
3000 // fixed some configurator vars
3001 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
3002 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
3003 // USE_DB_SESSION defaults to true on SQL
3004 // changed GROUP_METHOD definition to string, not constants
3005 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
3006 //   create users. (Not to be used with external databases generally, but
3007 //   with the default internal user table)
3008 //
3009 // fixed the IndexAsConfigProblem logic. this was flawed:
3010 //   scripts which are the same virtual path defined their own lib/main call
3011 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
3012 //
3013 // Revision 1.9  2004/01/30 19:57:58  rurban
3014 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
3015 //
3016 // Revision 1.8  2004/01/30 18:46:15  rurban
3017 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
3018 //
3019 // Revision 1.7  2004/01/27 23:23:39  rurban
3020 // renamed ->Username => _userid for consistency
3021 // renamed mayCheckPassword => mayCheckPass
3022 // fixed recursion problem in WikiUserNew
3023 // fixed bogo login (but not quite 100% ready yet, password storage)
3024 //
3025 // Revision 1.6  2004/01/26 09:17:49  rurban
3026 // * changed stored pref representation as before.
3027 //   the array of objects is 1) bigger and 2)
3028 //   less portable. If we would import packed pref
3029 //   objects and the object definition was changed, PHP would fail.
3030 //   This doesn't happen with an simple array of non-default values.
3031 // * use $prefs->retrieve and $prefs->store methods, where retrieve
3032 //   understands the interim format of array of objects also.
3033 // * simplified $prefs->get() and fixed $prefs->set()
3034 // * added $user->_userid and class '_WikiUser' portability functions
3035 // * fixed $user object ->_level upgrading, mostly using sessions.
3036 //   this fixes yesterdays problems with loosing authorization level.
3037 // * fixed WikiUserNew::checkPass to return the _level
3038 // * fixed WikiUserNew::isSignedIn
3039 // * added explodePageList to class PageList, support sortby arg
3040 // * fixed UserPreferences for WikiUserNew
3041 // * fixed WikiPlugin for empty defaults array
3042 // * UnfoldSubpages: added pagename arg, renamed pages arg,
3043 //   removed sort arg, support sortby arg
3044 //
3045 // Revision 1.5  2004/01/25 03:05:00  rurban
3046 // First working version, but has some problems with the current main loop.
3047 // Implemented new auth method dispatcher and policies, all the external
3048 // _PassUser classes (also for ADODB and Pear DB).
3049 // The two global funcs UserExists() and CheckPass() are probably not needed,
3050 // since the auth loop is done recursively inside the class code, upgrading
3051 // the user class within itself.
3052 // Note: When a higher user class is returned, this doesn't mean that the user
3053 // is authorized, $user->_level is still low, and only upgraded on successful
3054 // login.
3055 //
3056 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
3057 // Code Housecleaning: fixed syntax errors. (php -l *.php)
3058 //
3059 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
3060 // Finished off logic for determining user class, including
3061 // PassUser. Removed ability of BogoUser to save prefs into a page.
3062 //
3063 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
3064 // Added admin user, password user, and preference classes. Added
3065 // password checking functions for users and the admin. (Now the easy
3066 // parts are nearly done).
3067 //
3068 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
3069 // Complete rewrite of WikiUser.php.
3070 //
3071 // This should make it easier to hook in user permission groups etc. some
3072 // time in the future. Most importantly, to finally get UserPreferences
3073 // fully working properly for all classes of users: AnonUser, BogoUser,
3074 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
3075 // want a cookie or not, and to bring back optional AutoLogin with the
3076 // UserName stored in a cookie--something that was lost after PhpWiki had
3077 // dropped the default http auth login method.
3078 //
3079 // Added WikiUser classes which will (almost) work together with existing
3080 // UserPreferences class. Other parts of PhpWiki need to be updated yet
3081 // before this code can be hooked up.
3082 //
3083
3084 // Local Variables:
3085 // mode: php
3086 // tab-width: 8
3087 // c-basic-offset: 4
3088 // c-hanging-comment-ender-p: nil
3089 // indent-tabs-mode: nil
3090 // End:
3091 ?>