]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
login cleanup: better debug msg on failing login,
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.115 2004-11-05 20:53:35 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 name, authlevel and 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 config/config.ini
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  *    Update: not needed anymore. we use eval to fool the load-time syntax checker.
83  * 2004-03-24 rurban
84  * 6) enforced new cookie policy: prefs don't get stored in cookies
85  *    anymore, only in homepage and/or database, but always in the 
86  *    current session. old pref cookies will get deleted.
87  * 2004-04-04 rurban
88  * 7) Certain themes should be able to extend the predefined list 
89  *    of preferences. Display/editing is done in the theme specific userprefs.tmpl,
90  *    but storage must be extended to the Get/SetPreferences methods.
91  *    <theme>/themeinfo.php must provide CustomUserPreferences:
92  *      A list of name => _UserPreference class pairs.
93  */
94
95 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
96 define('WIKIAUTH_ANON', 0);       // Not signed in.
97 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
98 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
99 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
100 define('WIKIAUTH_UNOBTAINABLE', 100);  // Permissions that no user can achieve
101
102 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
103 //if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
104 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
105 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
106 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
107
108 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
109 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
110 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
111
112 define('TIMEOFFSET_MIN_HOURS', -26);
113 define('TIMEOFFSET_MAX_HOURS',  26);
114 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
115
116 /**
117  * There are be the following constants in config/config.ini to 
118  * establish login parameters:
119  *
120  * ALLOW_ANON_USER         default true
121  * ALLOW_ANON_EDIT         default true
122  * ALLOW_BOGO_LOGIN        default true
123  * ALLOW_USER_PASSWORDS    default true
124  * PASSWORD_LENGTH_MINIMUM default 0
125  *
126  * To require user passwords for editing:
127  * ALLOW_ANON_USER  = true
128  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
129  * ALLOW_BOGO_LOGIN = false
130  * ALLOW_USER_PASSWORDS = true
131  *
132  * To establish a COMPLETELY private wiki, such as an internal
133  * corporate one:
134  * ALLOW_ANON_USER = false
135  * (and probably require user passwords as described above). In this
136  * case the user will be prompted to login immediately upon accessing
137  * any page.
138  *
139  * There are other possible combinations, but the typical wiki (such
140  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four 
141  * enabled.
142  *
143  */
144
145 // The last object in the row is the bad guy...
146 if (!is_array($USER_AUTH_ORDER))
147     $USER_AUTH_ORDER = array("Forbidden");
148 else
149     $USER_AUTH_ORDER[] = "Forbidden";
150
151 // Local convenience functions.
152 function _isAnonUserAllowed() {
153     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
154 }
155 function _isBogoUserAllowed() {
156     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
157 }
158 function _isUserPasswordsAllowed() {
159     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
160 }
161
162 // Possibly upgrade userobject functions.
163 function _determineAdminUserOrOtherUser($UserName) {
164     // Sanity check. User name is a condition of the definition of the
165     // _AdminUser, _BogoUser and _passuser.
166     if (!$UserName)
167         return $GLOBALS['ForbiddenUser'];
168
169     //FIXME: check admin membership later at checkPass. now we cannot raise the level.
170     //$group = &WikiGroup::getGroup($GLOBALS['request']);
171     if ($UserName == ADMIN_USER)
172         return new _AdminUser($UserName);
173     /* elseif ($group->isMember(GROUP_ADMIN)) {
174         return _determineBogoUserOrPassUser($UserName);
175     }
176     */
177     else
178         return _determineBogoUserOrPassUser($UserName);
179 }
180
181 function _determineBogoUserOrPassUser($UserName) {
182     global $ForbiddenUser;
183
184     // Sanity check. User name is a condition of the definition of
185     // _BogoUser and _PassUser.
186     if (!$UserName)
187         return $ForbiddenUser;
188
189     // Check for password and possibly upgrade user object.
190     // $_BogoUser = new _BogoUser($UserName);
191     if (_isBogoUserAllowed() and isWikiWord($UserName)) {
192         include_once("lib/WikiUser/BogoLogin.php");
193         $_BogoUser = new _BogoLoginPassUser($UserName);
194         if ($_BogoUser->userExists())
195             return $_BogoUser;
196     }
197     if (_isUserPasswordsAllowed()) {
198         // PassUsers override BogoUsers if a password is stored
199         if (isset($_BogoUser) and isset($_BogoUser->_prefs) 
200             and $_BogoUser->_prefs->get('passwd'))
201             return new _PassUser($UserName,$_BogoUser->_prefs);
202         else { 
203             $_PassUser = new _PassUser($UserName,
204                                        isset($_BogoUser) ? $_BogoUser->_prefs : false);
205             if ($_PassUser->userExists())
206                 return $_PassUser;
207         }
208     }
209     // No Bogo- or PassUser exists, or
210     // passwords are not allowed, and bogo is disallowed too.
211     // (Only the admin can sign in).
212     return $ForbiddenUser;
213 }
214
215 /**
216  * Primary WikiUser function, called by lib/main.php.
217  * 
218  * This determines the user's type and returns an appropriate user
219  * object. lib/main.php then querys the resultant object for password
220  * validity as necessary.
221  *
222  * If an _AnonUser object is returned, the user may only browse pages
223  * (and save prefs in a cookie).
224  *
225  * To disable access but provide prefs the global $ForbiddenUser class 
226  * is returned. (was previously false)
227  * 
228  */
229 function WikiUser ($UserName = '') {
230     global $ForbiddenUser;
231
232     //Maybe: Check sessionvar for username & save username into
233     //sessionvar (may be more appropriate to do this in lib/main.php).
234     if ($UserName) {
235         $ForbiddenUser = new _ForbiddenUser($UserName);
236         // Found a user name.
237         return _determineAdminUserOrOtherUser($UserName);
238     }
239     elseif (!empty($_SESSION['userid'])) {
240         // Found a user name.
241         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
242         return _determineAdminUserOrOtherUser($_SESSION['userid']);
243     }
244     else {
245         // Check for autologin pref in cookie and possibly upgrade
246         // user object to another type.
247         $_AnonUser = new _AnonUser();
248         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
249             // Found a user name.
250             $ForbiddenUser = new _ForbiddenUser($UserName);
251             return _determineAdminUserOrOtherUser($UserName);
252         }
253         else {
254             $ForbiddenUser = new _ForbiddenUser();
255             if (_isAnonUserAllowed())
256                 return $_AnonUser;
257             return $ForbiddenUser; // User must sign in to browse pages.
258         }
259         return $ForbiddenUser;     // User must sign in with a password.
260     }
261     /*
262     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
263                   . "Unexpectedly, an appropriate user class could not be determined.");
264     return $ForbiddenUser; // Failsafe.
265     */
266 }
267
268 /**
269  * WikiUser.php use the name 'WikiUser'
270  */
271 function WikiUserClassname() {
272     return '_WikiUser';
273 }
274
275
276 /**
277  * Upgrade olduser by copying properties from user to olduser.
278  * We are not sure yet, for which php's a simple $this = $user works reliably,
279  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
280  * that's why try it the hard way.
281  */
282 function UpgradeUser ($olduser, $user) {
283     if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
284         // populate the upgraded class $olduser with the values from the new user object
285         //only _auth_level, _current_method, _current_index,
286         if (!empty($user->_level) and 
287             $user->_level > $olduser->_level)
288             $olduser->_level = $user->_level;
289         if (!empty($user->_current_index) and
290             $user->_current_index > $olduser->_current_index) {
291             $olduser->_current_index = $user->_current_index;
292             $olduser->_current_method = $user->_current_method;
293         }
294         if (!empty($user->_authmethod))
295             $olduser->_authmethod = $user->_authmethod;
296         /*
297         foreach (get_object_vars($user) as $k => $v) {
298             if (!empty($v)) $olduser->$k = $v;  
299         }
300         */
301         $olduser->hasHomePage(); // revive db handle, because these don't survive sessions
302         //$GLOBALS['request']->_user = $olduser;
303         return $olduser;
304     } else {
305         return false;
306     }
307 }
308
309 /**
310  * Probably not needed, since we use the various user objects methods so far.
311  * Anyway, here it is, looping through all available objects.
312  */
313 function UserExists ($UserName) {
314     global $request;
315     if (!($user = $request->getUser()))
316         $user = WikiUser($UserName);
317     if (!$user) 
318         return false;
319     if ($user->userExists($UserName)) {
320         $request->_user = $user;
321         return true;
322     }
323     if (isa($user,'_BogoUser'))
324         $user = new _PassUser($UserName,$user->_prefs);
325     $class = $user->nextClass();
326     if ($user = new $class($UserName,$user->_prefs)) {
327         return $user->userExists($UserName);
328     }
329     $request->_user = $GLOBALS['ForbiddenUser'];
330     return false;
331 }
332
333 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
334
335 /** 
336  * Base WikiUser class.
337  */
338 class _WikiUser
339 {
340      var $_userid = '';
341      var $_level = WIKIAUTH_ANON;
342      var $_prefs = false;
343      var $_HomePagehandle = false;
344
345     // constructor
346     function _WikiUser($UserName='', $prefs=false) {
347
348         $this->_userid = $UserName;
349         $this->_HomePagehandle = false;
350         if ($UserName) {
351             $this->hasHomePage();
352         }
353         if (empty($this->_prefs)) {
354             if ($prefs) $this->_prefs = $prefs;
355             else $this->getPreferences();
356         }
357     }
358
359     function UserName() {
360         if (!empty($this->_userid))
361             return $this->_userid;
362     }
363
364     function getPreferences() {
365         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
366                       . "New subclasses of _WikiUser must override this function.");
367         return false;
368     }
369
370     function setPreferences($prefs, $id_only) {
371         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." 
372                       . " "
373                       . "New subclasses of _WikiUser must override this function.");
374         return false;
375     }
376
377     function userExists() {
378         return $this->hasHomePage();
379     }
380
381     function checkPass($submitted_password) {
382         // By definition, an undefined user class cannot sign in.
383         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." 
384                       . " "
385                       . "New subclasses of _WikiUser must override this function.");
386         return false;
387     }
388
389     // returns page_handle to user's home page or false if none
390     function hasHomePage() {
391         if ($this->_userid) {
392             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
393                 return $this->_HomePagehandle->exists();
394             }
395             else {
396                 // check db again (maybe someone else created it since
397                 // we logged in.)
398                 global $request;
399                 $this->_HomePagehandle = $request->getPage($this->_userid);
400                 return $this->_HomePagehandle->exists();
401             }
402         }
403         // nope
404         return false;
405     }
406
407     // innocent helper: case-insensitive position in _auth_methods
408     function array_position ($string, $array) {
409         $string = strtolower($string);
410         for ($found = 0; $found < count($array); $found++) {
411             if (strtolower($array[$found]) == $string)
412                 return $found;
413         }
414         return false;
415     }
416
417     function nextAuthMethodIndex() {
418         if (empty($this->_auth_methods)) 
419             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
420         if (empty($this->_current_index)) {
421             if (strtolower(get_class($this)) != '_passuser') {
422                 $this->_current_method = substr(get_class($this),1,-8);
423                 $this->_current_index = $this->array_position($this->_current_method,
424                                                               $this->_auth_methods);
425             } else {
426                 $this->_current_index = -1;
427             }
428         }
429         $this->_current_index++;
430         if ($this->_current_index >= count($this->_auth_methods))
431             return false;
432         $this->_current_method = $this->_auth_methods[$this->_current_index];
433         return $this->_current_index;
434     }
435
436     function AuthMethod($index = false) {
437         return $this->_auth_methods[ $index === false 
438                                      ? count($this->_auth_methods)-1 
439                                      : $index];
440     }
441
442     // upgrade the user object
443     function nextClass() {
444         $method = $this->AuthMethod($this->nextAuthMethodIndex());
445         include_once("lib/WikiUser/$method.php");
446         return "_".$method."PassUser";
447     }
448
449     //Fixme: for _HttpAuthPassUser
450     function PrintLoginForm (&$request, $args, $fail_message = false,
451                              $seperate_page = false) {
452         include_once('lib/Template.php');
453         // Call update_locale in case the system's default language is not 'en'.
454         // (We have no user pref for lang at this point yet, no one is logged in.)
455         if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
456             update_locale(DEFAULT_LANGUAGE);
457         $userid = $this->_userid;
458         $require_level = 0;
459         extract($args); // fixme
460
461         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
462
463         $pagename = $request->getArg('pagename');
464         $nocache = 1;
465         $login = Template('login',
466                           compact('pagename', 'userid', 'require_level',
467                                   'fail_message', 'pass_required', 'nocache'));
468         // check if the html template was already processed
469         $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
470         if ($seperate_page) {
471             $page = $request->getPage($pagename);
472             $revision = $page->getCurrentRevision();
473             return GeneratePage($login,_("Sign In"),$revision);
474         } else {
475             return $login->printExpansion();
476         }
477     }
478
479     /** Signed in but not password checked or empty password.
480      */
481     function isSignedIn() {
482         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
483     }
484
485     /** This is password checked for sure.
486      */
487     function isAuthenticated() {
488         //return isa($this,'_PassUser');
489         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
490         return $this->_level >= WIKIAUTH_BOGO;
491     }
492
493     function isAdmin () {
494         static $group; 
495         if ($this->_level == WIKIAUTH_ADMIN) return true;
496         if (!$this->isSignedIn()) return false;
497         if (!$this->isAuthenticated()) return false;
498
499         if (!$group) $group = &$GLOBALS['request']->getGroup();
500         return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
501     }
502
503     /** Name or IP for a signed user. UserName could come from a cookie e.g.
504      */
505     function getId () {
506         return ( $this->UserName()
507                  ? $this->UserName()
508                  : $GLOBALS['request']->get('REMOTE_ADDR') );
509     }
510
511     /** Name for an authenticated user. No IP here.
512      */
513     function getAuthenticatedId() {
514         return ( $this->isAuthenticated()
515                  ? $this->_userid
516                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
517     }
518
519     function hasAuthority ($require_level) {
520         return $this->_level >= $require_level;
521     }
522
523     function isValidName ($userid = false) {
524         if (!$userid)
525             $userid = $this->_userid;
526         return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32;
527     }
528
529     /**
530      * Called on an auth_args POST request, such as login, logout or signin.
531      * TODO: Check BogoLogin users with empty password. (self-signed users)
532      */
533     function AuthCheck ($postargs) {
534         // Normalize args, and extract.
535         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
536                       'cancel');
537         foreach ($keys as $key)
538             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
539         extract($args);
540         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
541
542         if ($logout) { // Log out
543             $GLOBALS['request']->_user = new _AnonUser();
544             $GLOBALS['request']->_user->_userid = '';
545             $GLOBALS['request']->_user->_level = WIKIAUTH_ANON;
546             return $GLOBALS['request']->_user; 
547         } elseif ($cancel)
548             return false;        // User hit cancel button.
549         elseif (!$login && !$userid)
550             return false;       // Nothing to do?
551
552         if (!$this->isValidName($userid))
553             return _("Invalid username.");;
554
555         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
556         if ($authlevel <= 0) { // anon or forbidden
557             if ($passwd)
558                 return _("Invalid password.");
559             else
560                 return _("Invalid password or userid.");
561         } elseif ($authlevel < $require_level) { // auth ok, but not enough 
562             if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') 
563             {
564                 // upgrade class
565                 $class = "_" . $this->_current_method . "PassUser";
566                 include_once("lib/WikiUser/".$this->_current_method.".php");
567                 $user = new $class($userid,$this->_prefs);
568                 if (!check_php_version(5))
569                     eval("\$this = \$user;");
570                 // /*PHP5 patch*/$this = $user;
571                 $this->_level = $authlevel;
572                 return $user;
573             }
574             $this->_userid = $userid;
575             $this->_level = $authlevel;
576             return _("Insufficient permissions.");
577         }
578
579         // Successful login.
580         //$user = $GLOBALS['request']->_user;
581         if (!empty($this->_current_method) and 
582             strtolower(get_class($this)) == '_passuser') 
583         {
584             // upgrade class
585             $class = "_" . $this->_current_method . "PassUser";
586             include_once("lib/WikiUser/".$this->_current_method.".php");
587             $user = new $class($userid,$this->_prefs);
588             if (!check_php_version(5))
589                 eval("\$this = \$user;");
590             // /*PHP5 patch*/$this = $user;
591             $user->_level = $authlevel;
592             return $user;
593         }
594         $this->_userid = $userid;
595         $this->_level = $authlevel;
596         return $this;
597     }
598
599 }
600
601 /**
602  * Not authenticated in user, but he may be signed in. Basicly with view access only.
603  * prefs are stored in cookies, but only the userid.
604  */
605 class _AnonUser
606 extends _WikiUser
607 {
608     var $_level = WIKIAUTH_ANON;        // var in php-5.0.0RC1 deprecated
609
610     /** Anon only gets to load and save prefs in a cookie, that's it.
611      */
612     function getPreferences() {
613         global $request;
614
615         if (empty($this->_prefs))
616             $this->_prefs = new UserPreferences;
617         $UserName = $this->UserName();
618
619         // Try to read deprecated 1.3.x style cookies
620         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
621             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
622                 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.") 
623                               . "\n"
624                               . sprintf("%s='%s'", WIKI_NAME, $cookie)
625                               . "\n"
626                               . _("Default preferences will be used."),
627                               E_USER_NOTICE);
628             }
629             /**
630              * Only set if it matches the UserName who is
631              * signing in or if this really is an Anon login (no
632              * username). (Remember, _BogoUser and higher inherit this
633              * function too!).
634              */
635             if (! $UserName || $UserName == @$unboxedcookie['userid']) {
636                 $updated = $this->_prefs->updatePrefs($unboxedcookie);
637                 //$this->_prefs = new UserPreferences($unboxedcookie);
638                 $UserName = @$unboxedcookie['userid'];
639                 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
640                     $this->_userid = $UserName;
641                 else 
642                     $UserName = false;    
643             }
644             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
645             if (!headers_sent())
646                 $request->deleteCookieVar(WIKI_NAME);
647         }
648         // Try to read deprecated 1.3.4 style cookies
649         if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
650             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
651                 if (! $UserName || $UserName == $unboxedcookie['userid']) {
652                     $updated = $this->_prefs->updatePrefs($unboxedcookie);
653                     //$this->_prefs = new UserPreferences($unboxedcookie);
654                     $UserName = $unboxedcookie['userid'];
655                     if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
656                         $this->_userid = $UserName;
657                     else 
658                         $UserName = false;    
659                 }
660                 if (!headers_sent())
661                     $request->deleteCookieVar("WIKI_PREF2");
662             }
663         }
664         if (! $UserName ) {
665             // Try reading userid from old PhpWiki cookie formats:
666             if ($cookie = $request->cookies->get_old('WIKI_ID')) {
667                 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
668                     $UserName = $cookie;
669                 elseif (is_array($cookie) and !empty($cookie['userid']))
670                     $UserName = $cookie['userid'];
671             }
672             if (! $UserName and !headers_sent())
673                 $request->deleteCookieVar("WIKI_ID");
674             else
675                 $this->_userid = $UserName;
676         }
677
678         // initializeTheme() needs at least an empty object
679         /*
680          if (empty($this->_prefs))
681             $this->_prefs = new UserPreferences;
682         */
683         return $this->_prefs;
684     }
685
686     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
687      *
688      * Allow for multiple wikis in same domain. Encode only the
689      * _prefs array of the UserPreference object. Ideally the
690      * prefs array should just be imploded into a single string or
691      * something so it is completely human readable by the end
692      * user. In that case stricter error checking will be needed
693      * when loading the cookie.
694      */
695     function setPreferences($prefs, $id_only=false) {
696         if (!is_object($prefs)) {
697             if (is_object($this->_prefs)) {
698                 $updated = $this->_prefs->updatePrefs($prefs);
699                 $prefs =& $this->_prefs;
700             } else {
701                 // update the prefs values from scratch. This could leed to unnecessary
702                 // side-effects: duplicate emailVerified, ...
703                 $this->_prefs = new UserPreferences($prefs);
704                 $updated = true;
705             }
706         } else {
707             if (!isset($this->_prefs))
708                 $this->_prefs =& $prefs;
709             else
710                 $updated = $this->_prefs->isChanged($prefs);
711         }
712         if ($updated) {
713             if ($id_only and !headers_sent()) {
714                 global $request;
715                 // new 1.3.8 policy: no array cookies, only plain userid string as in 
716                 // the pre 1.3.x versions.
717                 // prefs should be stored besides the session in the homepagehandle or in a db.
718                 $request->setCookieVar('WIKI_ID', $this->_userid,
719                                        COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
720                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
721                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
722             }
723         }
724         $packed = $prefs->store();
725         $unpacked = $prefs->unpack($packed);
726         if (count($unpacked)) {
727             foreach (array('_method','_select','_update') as $param) {
728                 if (!empty($this->_prefs->{$param}))
729                     $prefs->{$param} = $this->_prefs->{$param};
730             }
731             $this->_prefs = $prefs;
732             //FIXME! The following must be done in $request->_setUser(), not here,
733             // to be able to iterate over multiple users, without tampering the current user.
734             if (0) {
735                 global $request;
736                 $request->_prefs =& $this->_prefs; 
737                 $request->_user->_prefs =& $this->_prefs;
738                 if (isset($request->_user->_auth_dbi)) {
739                     $user = $request->_user;
740                     unset($user->_auth_dbi);
741                     $request->setSessionVar('wiki_user', $user);
742                 } else {
743                     //$request->setSessionVar('wiki_prefs', $this->_prefs);
744                     $request->setSessionVar('wiki_user', $request->_user);
745                 }
746             }
747         }
748         return $updated;
749     }
750
751     function userExists() {
752         return true;
753     }
754
755     function checkPass($submitted_password) {
756         return false;
757         // this might happen on a old-style signin button.
758
759         // By definition, the _AnonUser does not HAVE a password
760         // (compared to _BogoUser, who has an EMPTY password).
761         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
762                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
763                       . "New subclasses of _WikiUser must override this function.");
764         return false;
765     }
766
767 }
768
769 /** 
770  * Helper class to finish the PassUser auth loop. 
771  * This is added automatically to USER_AUTH_ORDER.
772  */
773 class _ForbiddenUser
774 extends _AnonUser
775 {
776     var $_level = WIKIAUTH_FORBIDDEN;
777
778     function checkPass($submitted_password) {
779         return WIKIAUTH_FORBIDDEN;
780     }
781
782     function userExists() {
783         if ($this->_HomePagehandle) return true;
784         return false;
785     }
786 }
787
788 /**
789  * Do NOT extend _BogoUser to other classes, for checkPass()
790  * security. (In case of defects in code logic of the new class!)
791  * The intermediate step between anon and passuser.
792  * We also have the _BogoLoginPassUser class with stricter 
793  * password checking, which fits into the auth loop.
794  * Note: This class is not called anymore by WikiUser()
795  */
796 class _BogoUser
797 extends _AnonUser
798 {
799     function userExists() {
800         if (isWikiWord($this->_userid)) {
801             $this->_level = WIKIAUTH_BOGO;
802             return true;
803         } else {
804             $this->_level = WIKIAUTH_ANON;
805             return false;
806         }
807     }
808
809     function checkPass($submitted_password) {
810         // By definition, BogoUser has an empty password.
811         $this->userExists();
812         return $this->_level;
813     }
814 }
815
816 class _PassUser
817 extends _AnonUser
818 /**
819  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
820  *
821  * The classes for all subsequent auth methods extend from this class. 
822  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
823  * the three auth method policies first-only, strict and stacked
824  * and the two methods for prefs: homepage or database, 
825  * if $DBAuthParams['pref_select'] is defined.
826  *
827  * Default is PersonalPage auth and prefs.
828  * 
829  * @author: Reini Urban
830  * @tables: pref
831  */
832 {
833     var $_auth_dbi, $_prefs;
834     var $_current_method, $_current_index;
835
836     // check and prepare the auth and pref methods only once
837     function _PassUser($UserName='', $prefs=false) {
838         //global $DBAuthParams, $DBParams;
839         if ($UserName) {
840             if (!$this->isValidName($UserName))
841                 return false;
842             $this->_userid = $UserName;
843             if ($this->hasHomePage())
844                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
845         }
846         $this->_authmethod = substr(get_class($this),1,-8);
847         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
848
849         // Check the configured Prefs methods
850         $dbi = $this->getAuthDbh();
851         $dbh = $GLOBALS['request']->getDbh();
852         if ( $dbi and !isset($this->_prefs->_select) and $dbh->getAuthParam('pref_select')) {
853             if (!$this->_prefs) {
854                 $this->_prefs = new UserPreferences();
855                 $need_pref = true;
856             }
857             $this->_prefs->_method = $dbh->getParam('dbtype');
858             $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
859             // read-only prefs?
860             if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
861                 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'), 
862                                                         array("userid", "pref_blob"));
863             }
864         } else {
865             if (!$this->_prefs) {
866                 $this->_prefs = new UserPreferences();
867                 $need_pref = true;
868             }
869             $this->_prefs->_method = 'HomePage';
870         }
871         
872         if (! $this->_prefs or isset($need_pref) ) {
873             if ($prefs) $this->_prefs = $prefs;
874             else $this->getPreferences();
875         }
876         
877         // Upgrade to the next parent _PassUser class. Avoid recursion.
878         if ( strtolower(get_class($this)) === '_passuser' ) {
879             //auth policy: Check the order of the configured auth methods
880             // 1. first-only: Upgrade the class here in the constructor
881             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as 
882             ///              in the previous PhpWiki releases (slow)
883             // 3. strict:    upgrade the class after checking the user existance in userExists()
884             // 4. stacked:   upgrade the class after the password verification in checkPass()
885             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
886             //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
887             if (defined('USER_AUTH_POLICY')) {
888                 // policy 1: only pre-define one method for all users
889                 if (USER_AUTH_POLICY === 'first-only') {
890                     $class = $this->nextClass();
891                     return new $class($UserName,$this->_prefs);
892                 }
893                 // Use the default behaviour from the previous versions:
894                 elseif (USER_AUTH_POLICY === 'old') {
895                     // Default: try to be smart
896                     // On php5 we can directly return and upgrade the Object,
897                     // before we have to upgrade it manually.
898                     if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
899                         include_once("lib/WikiUser/HttpAuth.php");
900                         if (check_php_version(5))
901                             return new _HttpAuthPassUser($UserName,$this->_prefs);
902                         else {
903                             $user = new _HttpAuthPassUser($UserName,$this->_prefs);
904                             eval("\$this = \$user;");
905                             // /*PHP5 patch*/$this = $user;
906                             return $user;
907                         }
908                     } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
909                               $dbh->getAuthParam('auth_check') and
910                               ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
911                         if (check_php_version(5))
912                             return new _DbPassUser($UserName,$this->_prefs);
913                         else {
914                             $user = new _DbPassUser($UserName,$this->_prefs);
915                             eval("\$this = \$user;");
916                             // /*PHP5 patch*/$this = $user;
917                             return $user;
918                         }
919                     } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
920                               defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and 
921                               function_exists('ldap_connect')) {
922                         include_once("lib/WikiUser/LDAP.php");
923                         if (check_php_version(5))
924                             return new _LDAPPassUser($UserName,$this->_prefs);
925                         else {
926                             $user = new _LDAPPassUser($UserName,$this->_prefs);
927                             eval("\$this = \$user;");
928                             // /*PHP5 patch*/$this = $user;
929                             return $user;
930                         }
931                     } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
932                               defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
933                         include_once("lib/WikiUser/IMAP.php");
934                         if (check_php_version(5))
935                             return new _IMAPPassUser($UserName,$this->_prefs);
936                         else {
937                             $user = new _IMAPPassUser($UserName,$this->_prefs);
938                             eval("\$this = \$user;");
939                             // /*PHP5 patch*/$this = $user;
940                             return $user;
941                         }
942                     } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
943                               defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
944                         include_once("lib/WikiUser/File.php");
945                         if (check_php_version(5))
946                             return new _FilePassUser($UserName, $this->_prefs);
947                         else {
948                             $user = new _FilePassUser($UserName, $this->_prefs);
949                             eval("\$this = \$user;");
950                             // /*PHP5 patch*/$this = $user;
951                             return $user;
952                         }
953                     } else {
954                         include_once("lib/WikiUser/PersonalPage.php");
955                         if (check_php_version(5))
956                             return new _PersonalPagePassUser($UserName,$this->_prefs);
957                         else {
958                             $user = new _PersonalPagePassUser($UserName,$this->_prefs);
959                             eval("\$this = \$user;");
960                             // /*PHP5 patch*/$this = $user;
961                             return $user;
962                         }
963                     }
964                 }
965                 else 
966                     // else use the page methods defined in _PassUser.
967                     return $this;
968             }
969         }
970     }
971
972     function getAuthDbh () {
973         global $request; //, $DBParams, $DBAuthParams;
974
975         $dbh = $request->getDbh();
976         // session restauration doesn't re-connect to the database automatically, 
977         // so dirty it here, to force a reconnect.
978         if (isset($this->_auth_dbi)) {
979             if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
980                 unset($this->_auth_dbi);
981             if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
982                 unset($this->_auth_dbi);
983         }
984         if (empty($this->_auth_dbi)) {
985             if ($dbh->getParam('dbtype') != 'SQL' and $dbh->getParam('dbtype') != 'ADODB')
986                 return false;
987             if (empty($GLOBALS['DBAuthParams']))
988                 return false;
989             if (!$dbh->getAuthParam('auth_dsn')) {
990                 $dbh = $request->getDbh(); // use phpwiki database 
991             } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
992                 $dbh = $request->getDbh(); // same phpwiki database 
993             } else { // use another external database handle. needs PHP >= 4.1
994                 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
995                 $local_params['dsn'] = $local_params['auth_dsn'];
996                 $dbh = WikiDB::open($local_params);
997             }       
998             $this->_auth_dbi =& $dbh->_backend->_dbh;    
999         }
1000         return $this->_auth_dbi;
1001     }
1002
1003     function _normalize_stmt_var($var, $oldstyle = false) {
1004         static $valid_variables = array('userid','password','pref_blob','groupname');
1005         // old-style: "'$userid'"
1006         // new-style: '"\$userid"' or just "userid"
1007         $new = str_replace(array("'",'"','\$','$'),'',$var);
1008         if (!in_array($new,$valid_variables)) {
1009             trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1010             return false;
1011         }
1012         return !$oldstyle ? "'$".$new."'" : '"\$'.$new.'"';
1013     }
1014
1015     // TODO: use it again for the auth and member tables
1016     function prepare ($stmt, $variables, $oldstyle = false) {
1017         global $request;
1018         $dbi = $request->getDbh();
1019         $this->getAuthDbh();
1020         // "'\$userid"' => '%s'
1021         // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1022         // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1023         $new = array();
1024         if (is_array($variables)) {
1025             for ($i=0; $i < count($variables); $i++) { 
1026                 $var = $this->_normalize_stmt_var($variables[$i],$oldstyle);
1027                 if (!$var)
1028                     trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1029                                           $variables[$i], $stmt), E_USER_WARNING);
1030                 $variables[$i] = $var;
1031                 if (!$var) $new[] = '';
1032                 else $new[] = '%s';
1033             }
1034         } else {
1035             $var = $this->_normalize_stmt_var($variables,$oldstyle);
1036             if (!$var)
1037                 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1038                                       $variables,$stmt), E_USER_WARNING);
1039             $variables = $var;
1040             if (!$var) $new = ''; 
1041             else $new = '%s'; 
1042         }
1043         $prefix = $dbi->getParam('prefix');
1044         // probably prefix table names if in same database
1045         if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and 
1046             ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1047         {
1048             if (!stristr($stmt, $prefix)) {
1049                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1050                 trigger_error("TODO: Need to prefix the DBAuthParam tablename in config/config.ini:\n  $stmt",
1051                               E_USER_WARNING);
1052                 $stmt = str_replace(array(" user "," pref "," member "),
1053                                     array(" ".$prefix."user ",
1054                                           " ".$prefix."pref ",
1055                                           " ".$prefix."member "),$stmt);
1056             }
1057         }
1058         // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1059         // Simple sprintf-style.
1060         $new_stmt = str_replace($variables, $new, $stmt);
1061         if ($new_stmt == $stmt) {
1062             if ($oldstyle) {
1063                 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1064                                   $stmt), E_USER_WARNING);
1065             } else {
1066                 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1067                                   $stmt), E_USER_WARNING);
1068                 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1069             }
1070         }
1071         return $new_stmt;
1072     }
1073
1074     function getPreferences() {
1075         if (!empty($this->_prefs->_method)) {
1076             if ($this->_prefs->_method == 'ADODB') {
1077                 include_once("lib/WikiUser/Db.php");
1078                 include_once("lib/WikiUser/AdoDb.php");
1079                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
1080                 return _AdoDbPassUser::getPreferences();
1081             } elseif ($this->_prefs->_method == 'SQL') {
1082                 include_once("lib/WikiUser/Db.php");
1083                 include_once("lib/WikiUser/PearDb.php");
1084                 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
1085                 return _PearDbPassUser::getPreferences();
1086             }
1087         }
1088
1089         // We don't necessarily have to read the cookie first. Since
1090         // the user has a password, the prefs stored in the homepage
1091         // cannot be arbitrarily altered by other Bogo users.
1092         _AnonUser::getPreferences();
1093         // User may have deleted cookie, retrieve from his
1094         // PersonalPage if there is one.
1095         if ($this->_HomePagehandle) {
1096             if ($restored_from_page = $this->_prefs->retrieve
1097                 ($this->_HomePagehandle->get('pref'))) {
1098                 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1099                 //$this->_prefs = new UserPreferences($restored_from_page);
1100                 return $this->_prefs;
1101             }
1102         }
1103         return $this->_prefs;
1104     }
1105
1106     function setPreferences($prefs, $id_only=false) {
1107         if (!empty($this->_prefs->_method)) {
1108             if ($this->_prefs->_method == 'ADODB') {
1109                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
1110                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1111             }
1112             elseif ($this->_prefs->_method == 'SQL') {
1113                 _PearDbPassUser::_PearDbPassUser($this->_userid, $prefs);
1114                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1115             }
1116         }
1117         if (_AnonUser::setPreferences($prefs, $id_only)) {
1118             // Encode only the _prefs array of the UserPreference object
1119             if ($this->_HomePagehandle and !$id_only) {
1120                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1121             }
1122         }
1123         return;
1124     }
1125
1126     function mayChangePass() {
1127         return true;
1128     }
1129
1130     //The default method is getting the password from prefs. 
1131     // child methods obtain $stored_password from external auth.
1132     function userExists() {
1133         //if ($this->_HomePagehandle) return true;
1134         $class = $this->nextClass();
1135         while ($user = new $class($this->_userid, $this->_prefs)) {
1136             if (!check_php_version(5))
1137                 eval("\$this = \$user;");
1138             // /*PHP5 patch*/$this = $user;
1139             UpgradeUser($this,$user);
1140             if ($user->userExists()) {
1141                 return true;
1142             }
1143             // prevent endless loop. does this work on all PHP's?
1144             // it just has to set the classname, what it correctly does.
1145             $class = $user->nextClass();
1146             if ($class == "_ForbiddenPassUser")
1147                 return false;
1148         }
1149         return false;
1150     }
1151
1152     //The default method is getting the password from prefs. 
1153     // child methods obtain $stored_password from external auth.
1154     function checkPass($submitted_password) {
1155         $stored_password = $this->_prefs->get('passwd');
1156         if ($this->_checkPass($submitted_password, $stored_password)) {
1157             $this->_level = WIKIAUTH_USER;
1158             return $this->_level;
1159         } else {
1160             return $this->_tryNextPass($submitted_password);
1161         }
1162     }
1163
1164     /**
1165      * The basic password checker for all PassUser objects.
1166      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1167      * Empty passwords are always false!
1168      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1169      * @see UserPreferences::set
1170      *
1171      * DBPassUser password's have their own crypt definition.
1172      * That's why DBPassUser::checkPass() doesn't call this method, if 
1173      * the db password method is 'plain', which means that the DB SQL 
1174      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
1175      * don't store plain passwords in the DB.
1176      * 
1177      * TODO: remove crypt() function check from config.php:396 ??
1178      */
1179     function _checkPass($submitted_password, $stored_password) {
1180         if(!empty($submitted_password)) {
1181             //FIXME: This will work only on plaintext passwords.
1182             if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1183                 // With the EditMetaData plugin
1184                 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."));
1185                 return false;
1186             }
1187             if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1188                 trigger_error(_("The length of the password is shorter than the system policy allows."));
1189                 return false;
1190             }
1191             if (ENCRYPTED_PASSWD) {
1192                 // Verify against encrypted password.
1193                 if (function_exists('crypt')) {
1194                     if (crypt($submitted_password, $stored_password) == $stored_password )
1195                         return true; // matches encrypted password
1196                     else
1197                         return false;
1198                 }
1199                 else {
1200                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1201                                   . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1202                                   E_USER_WARNING);
1203                     return false;
1204                 }
1205             }
1206             else {
1207                 // Verify against cleartext password.
1208                 if ($submitted_password == $stored_password)
1209                     return true;
1210                 else {
1211                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1212                     if (function_exists('crypt')) {
1213                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1214                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1215                                           E_USER_WARNING);
1216                             return true;
1217                         }
1218                     }
1219                 }
1220             }
1221         }
1222         return false;
1223     }
1224
1225     /** The default method is storing the password in prefs. 
1226      *  Child methods (DB,File) may store in external auth also, but this 
1227      *  must be explicitly enabled.
1228      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1229      */
1230     function changePass($submitted_password) {
1231         $stored_password = $this->_prefs->get('passwd');
1232         // check if authenticated
1233         if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1234             $this->_prefs->set('passwd',$submitted_password);
1235             //update the storage (session, homepage, ...)
1236             $this->SetPreferences($this->_prefs);
1237             return true;
1238         }
1239         //Todo: return an error msg to the caller what failed? 
1240         // same password or no privilege
1241         return false;
1242     }
1243
1244     function _tryNextPass($submitted_password) {
1245         if (DEBUG) {
1246             $class = strtolower(get_class($this));
1247             if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1248             $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1249         }
1250         if (USER_AUTH_POLICY === 'strict') {
1251             $class = $this->nextClass();
1252             if ($user = new $class($this->_userid,$this->_prefs)) {
1253                 if ($user->userExists()) {
1254                     return $user->checkPass($submitted_password);
1255                 }
1256             }
1257         }
1258         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1259             $class = $this->nextClass();
1260             if ($user = new $class($this->_userid,$this->_prefs))
1261                 return $user->checkPass($submitted_password);
1262         }
1263         return $this->_level;
1264     }
1265
1266     function _tryNextUser() {
1267         if (DEBUG) {
1268             $class = strtolower(get_class($this));
1269             if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1270             $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1271         }
1272         if (USER_AUTH_POLICY === 'strict') {
1273             $class = $this->nextClass();
1274             while ($user = new $class($this->_userid,$this->_prefs)) {
1275                 if (!check_php_version(5))
1276                     eval("\$this = \$user;");
1277                 // /*PHP5 patch*/$this = $user;
1278                 //$user = UpgradeUser($this, $user);
1279                 if ($user->userExists()) {
1280                     return true;
1281                 }
1282                 $class = $this->nextClass();
1283             }
1284         }
1285         return false;
1286     }
1287
1288 }
1289
1290 /**
1291  * Insert more auth classes here...
1292  * For example a customized db class for another db connection 
1293  * or a socket-based auth server.
1294  *
1295  */
1296
1297
1298 /**
1299  * For security, this class should not be extended. Instead, extend
1300  * from _PassUser (think of this as unix "root").
1301  *
1302  * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1303  * Other members of the Administrators group must raise their level otherwise somehow.
1304  * Currently every member is a AdminUser, which will not work for the various 
1305  * storage methods.
1306  */
1307 class _AdminUser
1308 extends _PassUser
1309 {
1310     function mayChangePass() {
1311         return false;
1312     }
1313     function checkPass($submitted_password) {
1314         if ($this->_userid == ADMIN_USER)
1315             $stored_password = ADMIN_PASSWD;
1316         else {
1317             return $this->_tryNextPass($submitted_password);
1318             // TODO: safety check if really member of the ADMIN group?
1319             $stored_password = $this->_pref->get('passwd');
1320         }
1321         if ($this->_checkPass($submitted_password, $stored_password)) {
1322             $this->_level = WIKIAUTH_ADMIN;
1323             return $this->_level;
1324         } else {
1325             return $this->_tryNextPass($submitted_password);
1326             //$this->_level = WIKIAUTH_ANON;
1327             //return $this->_level;
1328         }
1329         
1330     }
1331     function storePass($submitted_password) {
1332         return false;
1333     }
1334 }
1335
1336 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1337 /**
1338  * Various data classes for the preference types, 
1339  * to support get, set, sanify (range checking, ...)
1340  * update() will do the neccessary side-effects if a 
1341  * setting gets changed (theme, language, ...)
1342 */
1343
1344 class _UserPreference
1345 {
1346     var $default_value;
1347
1348     function _UserPreference ($default_value) {
1349         $this->default_value = $default_value;
1350     }
1351
1352     function sanify ($value) {
1353         return (string)$value;
1354     }
1355
1356     function get ($name) {
1357         if (isset($this->{$name}))
1358             return $this->{$name};
1359         else 
1360             return $this->default_value;
1361     }
1362
1363     function getraw ($name) {
1364         if (!empty($this->{$name}))
1365             return $this->{$name};
1366     }
1367
1368     // stores the value as $this->$name, and not as $this->value (clever?)
1369     function set ($name, $value) {
1370         $return = 0;
1371         $value = $this->sanify($value);
1372         if ($this->get($name) != $value) {
1373             $this->update($value);
1374             $return = 1;
1375         }
1376         if ($value != $this->default_value) {
1377             $this->{$name} = $value;
1378         } else {
1379             unset($this->{$name});
1380         }
1381         return $return;
1382     }
1383
1384     // default: no side-effects 
1385     function update ($value) {
1386         ;
1387     }
1388 }
1389
1390 class _UserPreference_numeric
1391 extends _UserPreference
1392 {
1393     function _UserPreference_numeric ($default, $minval = false,
1394                                       $maxval = false) {
1395         $this->_UserPreference((double)$default);
1396         $this->_minval = (double)$minval;
1397         $this->_maxval = (double)$maxval;
1398     }
1399
1400     function sanify ($value) {
1401         $value = (double)$value;
1402         if ($this->_minval !== false && $value < $this->_minval)
1403             $value = $this->_minval;
1404         if ($this->_maxval !== false && $value > $this->_maxval)
1405             $value = $this->_maxval;
1406         return $value;
1407     }
1408 }
1409
1410 class _UserPreference_int
1411 extends _UserPreference_numeric
1412 {
1413     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1414         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1415     }
1416
1417     function sanify ($value) {
1418         return (int)parent::sanify((int)$value);
1419     }
1420 }
1421
1422 class _UserPreference_bool
1423 extends _UserPreference
1424 {
1425     function _UserPreference_bool ($default = false) {
1426         $this->_UserPreference((bool)$default);
1427     }
1428
1429     function sanify ($value) {
1430         if (is_array($value)) {
1431             /* This allows for constructs like:
1432              *
1433              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1434              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1435              *
1436              * (If the checkbox is not checked, only the hidden input
1437              * gets sent. If the checkbox is sent, both inputs get
1438              * sent.)
1439              */
1440             foreach ($value as $val) {
1441                 if ($val)
1442                     return true;
1443             }
1444             return false;
1445         }
1446         return (bool) $value;
1447     }
1448 }
1449
1450 class _UserPreference_language
1451 extends _UserPreference
1452 {
1453     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1454         $this->_UserPreference($default);
1455     }
1456
1457     // FIXME: check for valid locale
1458     function sanify ($value) {
1459         // Revert to DEFAULT_LANGUAGE if user does not specify
1460         // language in UserPreferences or chooses <system language>.
1461         if ($value == '' or empty($value))
1462             $value = DEFAULT_LANGUAGE;
1463
1464         return (string) $value;
1465     }
1466     
1467     function update ($newvalue) {
1468         if (! $this->_init ) {
1469             // invalidate etag to force fresh output
1470             $GLOBALS['request']->setValidators(array('%mtime' => false));
1471             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1472         }
1473     }
1474 }
1475
1476 class _UserPreference_theme
1477 extends _UserPreference
1478 {
1479     function _UserPreference_theme ($default = THEME) {
1480         $this->_UserPreference($default);
1481     }
1482
1483     function sanify ($value) {
1484         if (!empty($value) and FindFile($this->_themefile($value)))
1485             return $value;
1486         return $this->default_value;
1487     }
1488
1489     function update ($newvalue) {
1490         global $WikiTheme;
1491         // invalidate etag to force fresh output
1492         if (! $this->_init )
1493             $GLOBALS['request']->setValidators(array('%mtime' => false));
1494         if ($newvalue)
1495             include_once($this->_themefile($newvalue));
1496         if (empty($WikiTheme))
1497             include_once($this->_themefile(THEME));
1498     }
1499
1500     function _themefile ($theme) {
1501         return "themes/$theme/themeinfo.php";
1502     }
1503 }
1504
1505 class _UserPreference_notify
1506 extends _UserPreference
1507 {
1508     function sanify ($value) {
1509         if (!empty($value))
1510             return $value;
1511         else
1512             return $this->default_value;
1513     }
1514
1515     /** update to global user prefs: side-effect on set notify changes
1516      * use a global_data notify hash:
1517      * notify = array('pagematch' => array(userid => ('email' => mail, 
1518      *                                                'verified' => 0|1),
1519      *                                     ...),
1520      *                ...);
1521      */
1522     function update ($value) {
1523         if (!empty($this->_init)) return;
1524         $dbh = $GLOBALS['request']->getDbh();
1525         $notify = $dbh->get('notify');
1526         if (empty($notify))
1527             $data = array();
1528         else 
1529             $data = & $notify;
1530         // expand to existing pages only or store matches?
1531         // for now we store (glob-style) matches which is easier for the user
1532         $pages = $this->_page_split($value);
1533         // Limitation: only current user.
1534         $user = $GLOBALS['request']->getUser();
1535         if (!$user or !method_exists($user,'UserName')) return;
1536         // This fails with php5 and a WIKI_ID cookie:
1537         $userid = $user->UserName();
1538         $email  = $user->_prefs->get('email');
1539         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1540         // check existing notify hash and possibly delete pages for email
1541         if (!empty($data)) {
1542             foreach ($data as $page => $users) {
1543                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1544                     unset($data[$page][$userid]);
1545                 }
1546                 if (count($data[$page]) == 0)
1547                     unset($data[$page]);
1548             }
1549         }
1550         // add the new pages
1551         if (!empty($pages)) {
1552             foreach ($pages as $page) {
1553                 if (!isset($data[$page]))
1554                     $data[$page] = array();
1555                 if (!isset($data[$page][$userid])) {
1556                     // should we really store the verification notice here or 
1557                     // check it dynamically at every page->save?
1558                     if ($verified) {
1559                         $data[$page][$userid] = array('email' => $email,
1560                                                       'verified' => $verified);
1561                     } else {
1562                         $data[$page][$userid] = array('email' => $email);
1563                     }
1564                 }
1565             }
1566         }
1567         // store users changes
1568         $dbh->set('notify',$data);
1569     }
1570
1571     /** split the user-given comma or whitespace delimited pagenames
1572      *  to array
1573      */
1574     function _page_split($value) {
1575         return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1576     }
1577 }
1578
1579 class _UserPreference_email
1580 extends _UserPreference
1581 {
1582     function sanify($value) {
1583         // check for valid email address
1584         if ($this->get('email') == $value and $this->getraw('emailVerified'))
1585             return $value;
1586         // hack!
1587         if ($value == 1 or $value === true)
1588             return $value;
1589         list($ok,$msg) = ValidateMail($value,'noconnect');
1590         if ($ok) {
1591             return $value;
1592         } else {
1593             trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
1594             return $this->default_value;
1595         }
1596     }
1597     
1598     /** Side-effect on email changes:
1599      * Send a verification mail or for now just a notification email.
1600      * For true verification (value = 2), we'd need a mailserver hook.
1601      */
1602     function update($value) {
1603         if (!empty($this->_init)) return;
1604         $verified = $this->getraw('emailVerified');
1605         // hack!
1606         if (($value == 1 or $value === true) and $verified)
1607             return;
1608         if (!empty($value) and !$verified) {
1609             list($ok,$msg) = ValidateMail($value);
1610             if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
1611                      sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1612                              WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true))))
1613                 $this->set('emailVerified',1);
1614         }
1615     }
1616 }
1617
1618 /** Check for valid email address
1619     fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1620     Note: too strict, Bug #1053681
1621  */
1622 function ValidateMail($email, $noconnect=false) {
1623     $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1624
1625     // if this check is too strict (like invalid mail addresses in a local network only)
1626     // uncomment the following line:
1627     // return array(true,"not validated");
1628     // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1629
1630     $result = array();
1631     // well, technically ".a.a.@host.com" is also valid
1632     if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
1633         $result[0] = false;
1634         $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
1635         return $result;
1636     }
1637     if ($noconnect)
1638       return array(true,sprintf(_("E-Mail address '%s' is properly formatted"), $email));
1639
1640     list ( $Username, $Domain ) = split ("@", $email);
1641     //Todo: getmxrr workaround on windows or manual input field to verify it manually
1642     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. 
1643         $ConnectAddress = $MXHost[0];
1644     } else {
1645         $ConnectAddress = $Domain;
1646     }
1647     $Connect = @fsockopen ( $ConnectAddress, 25 );
1648     if ($Connect) {
1649         if (ereg("^220", $Out = fgets($Connect, 1024))) {
1650             fputs ($Connect, "HELO $HTTP_HOST\r\n");
1651             $Out = fgets ( $Connect, 1024 );
1652             fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
1653             $From = fgets ( $Connect, 1024 );
1654             fputs ($Connect, "RCPT TO: <".$email.">\r\n");
1655             $To = fgets ($Connect, 1024);
1656             fputs ($Connect, "QUIT\r\n");
1657             fclose($Connect);
1658             if (!ereg ("^250", $From)) {
1659                 $result[0]=false;
1660                 $result[1]="Server rejected address: ". $From;
1661                 return $result;
1662             }
1663             if (!ereg ( "^250", $To )) {
1664                 $result[0]=false;
1665                 $result[1]="Server rejected address: ". $To;
1666                 return $result;
1667             }
1668         } else {
1669             $result[0] = false;
1670             $result[1] = "No response from server";
1671             return $result;
1672           }
1673     }  else {
1674         $result[0]=false;
1675         $result[1]="Can not connect E-Mail server.";
1676         return $result;
1677     }
1678     $result[0]=true;
1679     $result[1]="E-Mail address '$email' appears to be valid.";
1680     return $result;
1681 } // end of function 
1682
1683 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1684
1685 /**
1686  * UserPreferences
1687  * 
1688  * This object holds the $request->_prefs subobjects.
1689  * A simple packed array of non-default values get's stored as cookie,
1690  * homepage, or database, which are converted to the array of 
1691  * ->_prefs objects.
1692  * We don't store the objects, because otherwise we will
1693  * not be able to upgrade any subobject. And it's a waste of space also.
1694  *
1695  */
1696 class UserPreferences
1697 {
1698     function UserPreferences($saved_prefs = false) {
1699         // userid stored too, to ensure the prefs are being loaded for
1700         // the correct (currently signing in) userid if stored in a
1701         // cookie.
1702         // Update: for db prefs we disallow passwd. 
1703         // userid is needed for pref reflexion. current pref must know its username, 
1704         // if some app needs prefs from different users, different from current user.
1705         $this->_prefs
1706             = array(
1707                     'userid'        => new _UserPreference(''),
1708                     'passwd'        => new _UserPreference(''),
1709                     'autologin'     => new _UserPreference_bool(),
1710                     //'emailVerified' => new _UserPreference_emailVerified(), 
1711                     //fixed: store emailVerified as email parameter, 1.3.8
1712                     'email'         => new _UserPreference_email(''),
1713                     'notifyPages'   => new _UserPreference_notify(''), // 1.3.8
1714                     'theme'         => new _UserPreference_theme(THEME),
1715                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
1716                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1717                                                                EDITWIDTH_MIN_COLS,
1718                                                                EDITWIDTH_MAX_COLS),
1719                     'noLinkIcons'   => new _UserPreference_bool(),    // 1.3.8 
1720                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1721                                                                EDITHEIGHT_MIN_ROWS,
1722                                                                EDITHEIGHT_DEFAULT_ROWS),
1723                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1724                                                                    TIMEOFFSET_MIN_HOURS,
1725                                                                    TIMEOFFSET_MAX_HOURS),
1726                     'relativeDates' => new _UserPreference_bool(),
1727                     'googleLink'    => new _UserPreference_bool(), // 1.3.10
1728                     );
1729         // add custom theme-specific pref types:
1730         // FIXME: on theme changes the wiki_user session pref object will fail. 
1731         // We will silently ignore this.
1732         if (!empty($customUserPreferenceColumns))
1733             $this->_prefs = array_merge($this->_prefs,$customUserPreferenceColumns);
1734 /*
1735         if (isset($this->_method) and $this->_method == 'SQL') {
1736             //unset($this->_prefs['userid']);
1737             unset($this->_prefs['passwd']);
1738         }
1739 */
1740         if (is_array($saved_prefs)) {
1741             foreach ($saved_prefs as $name => $value)
1742                 $this->set($name, $value);
1743         }
1744     }
1745
1746     function _getPref($name) {
1747         if ($name == 'emailVerified')
1748             $name = 'email';
1749         if (!isset($this->_prefs[$name])) {
1750             if ($name == 'passwd2') return false;
1751             if ($name == 'passwd') return false;
1752             trigger_error("$name: unknown preference", E_USER_NOTICE);
1753             return false;
1754         }
1755         return $this->_prefs[$name];
1756     }
1757     
1758     // get the value or default_value of the subobject
1759     function get($name) {
1760         if ($_pref = $this->_getPref($name))
1761             if ($name == 'emailVerified')
1762                 return $_pref->getraw($name);
1763             else
1764                 return $_pref->get($name);
1765         else
1766             return false;  
1767     }
1768
1769     // check and set the new value in the subobject
1770     function set($name, $value) {
1771         $pref = $this->_getPref($name);
1772         if ($pref === false)
1773             return false;
1774
1775         /* do it here or outside? */
1776         if ($name == 'passwd' and 
1777             defined('PASSWORD_LENGTH_MINIMUM') and 
1778             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1779             //TODO: How to notify the user?
1780             return false;
1781         }
1782         /*
1783         if ($name == 'theme' and $value == '')
1784            return true;
1785         */
1786         if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
1787             if ($name == 'emailVerified') $newvalue = $value;
1788             else $newvalue = $pref->sanify($value);
1789             $pref->set($name,$newvalue);
1790         }
1791         $this->_prefs[$name] =& $pref;
1792         return true;
1793     }
1794     /**
1795      * use init to avoid update on set
1796      */
1797     function updatePrefs($prefs, $init = false) {
1798         $count = 0;
1799         if ($init) $this->_init = $init;
1800         if (is_object($prefs)) {
1801             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
1802             $obj->_init = $init;
1803             if ($obj->get($type) !== $prefs->get($type)) {
1804                 if ($obj->set($type,$prefs->get($type)))
1805                     $count++;
1806             }
1807             foreach (array_keys($this->_prefs) as $type) {
1808                 $obj =& $this->_prefs[$type];
1809                 $obj->_init = $init;
1810                 if ($prefs->get($type) !== $obj->get($type)) {
1811                     // special systemdefault prefs: (probably not needed)
1812                     if ($type == 'theme' and $prefs->get($type) == '' and 
1813                         $obj->get($type) == THEME) continue;
1814                     if ($type == 'lang' and $prefs->get($type) == '' and 
1815                         $obj->get($type) == DEFAULT_LANGUAGE) continue;
1816                     if ($this->_prefs[$type]->set($type,$prefs->get($type)))
1817                         $count++;
1818                 }
1819             }
1820         } elseif (is_array($prefs)) {
1821             //unset($this->_prefs['userid']);
1822             /*
1823             if (isset($this->_method) and 
1824                  ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
1825                 unset($this->_prefs['passwd']);
1826             }
1827             */
1828             // emailVerified at first, the rest later
1829             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
1830             $obj->_init = $init;
1831             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
1832                 if ($obj->set($type,$prefs[$type]))
1833                     $count++;
1834             }
1835             foreach (array_keys($this->_prefs) as $type) {
1836                 $obj =& $this->_prefs[$type];
1837                 $obj->_init = $init;
1838                 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool")) 
1839                     $prefs[$type] = false;
1840                 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
1841                     $prefs[$type] = (int) $prefs[$type];
1842                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
1843                     // special systemdefault prefs:
1844                     if ($type == 'theme' and $prefs[$type] == '' and 
1845                         $obj->get($type) == THEME) continue;
1846                     if ($type == 'lang' and $prefs[$type] == '' and 
1847                         $obj->get($type) == DEFAULT_LANGUAGE) continue;
1848                     if ($obj->set($type,$prefs[$type]))
1849                         $count++;
1850                 }
1851             }
1852         }
1853         return $count;
1854     }
1855
1856     // For now convert just array of objects => array of values
1857     // Todo: the specialized subobjects must override this.
1858     function store() {
1859         $prefs = array();
1860         foreach ($this->_prefs as $name => $object) {
1861             if ($value = $object->getraw($name))
1862                 $prefs[$name] = $value;
1863             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
1864                 $prefs['emailVerified'] = $value;
1865             if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
1866                 $prefs['passwd'] = crypt($value);
1867             }
1868         }
1869         return $this->pack($prefs);
1870     }
1871
1872     // packed string or array of values => array of values
1873     // Todo: the specialized subobjects must override this.
1874     function retrieve($packed) {
1875         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1876             $packed = unserialize($packed);
1877         if (!is_array($packed)) return false;
1878         $prefs = array();
1879         foreach ($packed as $name => $packed_pref) {
1880             if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
1881                 //legacy: check if it's an old array of objects
1882                 // Looks like a serialized object. 
1883                 // This might fail if the object definition does not exist anymore.
1884                 // object with ->$name and ->default_value vars.
1885                 $pref =  @unserialize($packed_pref);
1886                 if (empty($pref))
1887                     $pref = @unserialize(base64_decode($packed_pref));
1888                 $prefs[$name] = $pref->get($name);
1889             // fix old-style prefs
1890             } elseif (is_numeric($name) and is_array($packed_pref)) {
1891                 if (count($packed_pref) == 1) {
1892                     list($name,$value) = each($packed_pref);
1893                     $prefs[$name] = $value;
1894                 }
1895             } else {
1896                 $prefs[$name] = @unserialize($packed_pref);
1897                 if (empty($prefs[$name]))
1898                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
1899                 // patched by frederik@pandora.be
1900                 if (empty($prefs[$name]))
1901                     $prefs[$name] = $packed_pref;
1902             }
1903         }
1904         return $prefs;
1905     }
1906
1907     /**
1908      * Check if the given prefs object is different from the current prefs object
1909      */
1910     function isChanged($other) {
1911         foreach ($this->_prefs as $type => $obj) {
1912             if ($obj->get($type) !== $other->get($type))
1913                 return true;
1914         }
1915         return false;
1916     }
1917
1918     function defaultPreferences() {
1919         $prefs = array();
1920         foreach ($this->_prefs as $key => $obj) {
1921             $prefs[$key] = $obj->default_value;
1922         }
1923         return $prefs;
1924     }
1925     
1926     // array of objects
1927     function getAll() {
1928         return $this->_prefs;
1929     }
1930
1931     function pack($nonpacked) {
1932         return serialize($nonpacked);
1933     }
1934
1935     function unpack($packed) {
1936         if (!$packed)
1937             return false;
1938         //$packed = base64_decode($packed);
1939         if (substr($packed, 0, 2) == "O:") {
1940             // Looks like a serialized object
1941             return unserialize($packed);
1942         }
1943         if (substr($packed, 0, 2) == "a:") {
1944             return unserialize($packed);
1945         }
1946         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1947         //E_USER_WARNING);
1948         return false;
1949     }
1950
1951     function hash () {
1952         return hash($this->_prefs);
1953     }
1954 }
1955
1956 /** TODO: new pref storage classes
1957  *  These are currently user specific and should be rewritten to be pref specific.
1958  *  i.e. $this == $user->_prefs
1959  */
1960 /*
1961 class CookieUserPreferences
1962 extends UserPreferences
1963 {
1964     function CookieUserPreferences ($saved_prefs = false) {
1965         //_AnonUser::_AnonUser('',$saved_prefs);
1966         UserPreferences::UserPreferences($saved_prefs);
1967     }
1968 }
1969
1970 class PageUserPreferences
1971 extends UserPreferences
1972 {
1973     function PageUserPreferences ($saved_prefs = false) {
1974         UserPreferences::UserPreferences($saved_prefs);
1975     }
1976 }
1977
1978 class PearDbUserPreferences
1979 extends UserPreferences
1980 {
1981     function PearDbUserPreferences ($saved_prefs = false) {
1982         UserPreferences::UserPreferences($saved_prefs);
1983     }
1984 }
1985
1986 class AdoDbUserPreferences
1987 extends UserPreferences
1988 {
1989     function AdoDbUserPreferences ($saved_prefs = false) {
1990         UserPreferences::UserPreferences($saved_prefs);
1991     }
1992     function getPreferences() {
1993         // override the generic slow method here for efficiency
1994         _AnonUser::getPreferences();
1995         $this->getAuthDbh();
1996         if (isset($this->_select)) {
1997             $dbh = & $this->_auth_dbi;
1998             $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
1999             if ($rs->EOF) {
2000                 $rs->Close();
2001             } else {
2002                 $prefs_blob = $rs->fields['pref_blob'];
2003                 $rs->Close();
2004                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2005                     $updated = $this->_prefs->updatePrefs($restored_from_db);
2006                     //$this->_prefs = new UserPreferences($restored_from_db);
2007                     return $this->_prefs;
2008                 }
2009             }
2010         }
2011         if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2012             if ($restored_from_page = $this->_prefs->retrieve
2013                 ($this->_HomePagehandle->get('pref'))) {
2014                 $updated = $this->_prefs->updatePrefs($restored_from_page);
2015                 //$this->_prefs = new UserPreferences($restored_from_page);
2016                 return $this->_prefs;
2017             }
2018         }
2019         return $this->_prefs;
2020     }
2021 }
2022 */
2023
2024 // $Log: not supported by cvs2svn $
2025 // Revision 1.114  2004/11/05 16:15:57  rurban
2026 // forgot the BogoLogin inclusion with the latest rewrite
2027 //
2028 // Revision 1.113  2004/11/03 17:13:49  rurban
2029 // make it easier to disable EmailVerification
2030 //   Bug #1053681
2031 //
2032 // Revision 1.112  2004/11/01 10:43:57  rurban
2033 // seperate PassUser methods into seperate dir (memory usage)
2034 // fix WikiUser (old) overlarge data session
2035 // remove wikidb arg from various page class methods, use global ->_dbi instead
2036 // ...
2037 //
2038 // Revision 1.111  2004/10/21 21:03:50  rurban
2039 // isAdmin must be signed and authenticated
2040 // comment out unused sections (memory)
2041 //
2042 // Revision 1.110  2004/10/14 19:19:33  rurban
2043 // loadsave: check if the dumped file will be accessible from outside.
2044 // and some other minor fixes. (cvsclient native not yet ready)
2045 //
2046 // Revision 1.109  2004/10/07 16:08:58  rurban
2047 // fixed broken FileUser session handling.
2048 //   thanks to Arnaud Fontaine for detecting this.
2049 // enable file user Administrator membership.
2050 //
2051 // Revision 1.108  2004/10/05 17:00:04  rurban
2052 // support paging for simple lists
2053 // fix RatingDb sql backend.
2054 // remove pages from AllPages (this is ListPages then)
2055 //
2056 // Revision 1.107  2004/10/04 23:42:15  rurban
2057 // HttpAuth admin group logic. removed old logs
2058 //
2059 // Revision 1.106  2004/07/01 08:49:38  rurban
2060 // obsolete php5-patch.php: minor php5 login problem though
2061 //
2062 // Revision 1.105  2004/06/29 06:48:03  rurban
2063 // Improve LDAP auth and GROUP_LDAP membership:
2064 //   no error message on false password,
2065 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2066 //   fixed two group queries (this -> user)
2067 // stdlib: ConvertOldMarkup still flawed
2068 //
2069 // Revision 1.104  2004/06/28 15:39:37  rurban
2070 // fixed endless recursion in WikiGroup: isAdmin()
2071 //
2072 // Revision 1.103  2004/06/28 15:01:07  rurban
2073 // fixed LDAP_SET_OPTION handling, LDAP error on connection problem
2074 //
2075 // Revision 1.102  2004/06/27 10:23:48  rurban
2076 // typo detected by Philippe Vanhaesendonck
2077 //
2078 // Revision 1.101  2004/06/25 14:29:19  rurban
2079 // WikiGroup refactoring:
2080 //   global group attached to user, code for not_current user.
2081 //   improved helpers for special groups (avoid double invocations)
2082 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2083 // fixed a XHTML validation error on userprefs.tmpl
2084 //
2085 // Revision 1.100  2004/06/21 06:29:35  rurban
2086 // formatting: linewrap only
2087 //
2088 // Revision 1.99  2004/06/20 15:30:05  rurban
2089 // get_class case-sensitivity issues
2090 //
2091 // Revision 1.98  2004/06/16 21:24:31  rurban
2092 // do not display no-connect warning: #2662
2093 //
2094 // Revision 1.97  2004/06/16 13:21:16  rurban
2095 // stabilize on failing ldap queries or bind
2096 //
2097 // Revision 1.96  2004/06/16 12:42:06  rurban
2098 // fix homepage prefs
2099 //
2100 // Revision 1.95  2004/06/16 10:38:58  rurban
2101 // Disallow refernces in calls if the declaration is a reference
2102 // ("allow_call_time_pass_reference clean").
2103 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
2104 //   but several external libraries may not.
2105 //   In detail these libs look to be affected (not tested):
2106 //   * Pear_DB odbc
2107 //   * adodb oracle
2108 //
2109 // Revision 1.94  2004/06/15 10:40:35  rurban
2110 // minor WikiGroup cleanup: no request param, start of current user independency
2111 //
2112 // Revision 1.93  2004/06/15 09:15:52  rurban
2113 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
2114 //   fix encrypted usage, actually store and retrieve them from db
2115 //   fix bogologin with passwd set.
2116 // fix php crashes with call-time pass-by-reference (references wrongly used
2117 //   in declaration AND call). This affected mainly Apache2 and IIS.
2118 //   (Thanks to John Cole to detect this!)
2119 //
2120 // Revision 1.92  2004/06/14 11:31:36  rurban
2121 // renamed global $Theme to $WikiTheme (gforge nameclash)
2122 // inherit PageList default options from PageList
2123 //   default sortby=pagename
2124 // use options in PageList_Selectable (limit, sortby, ...)
2125 // added action revert, with button at action=diff
2126 // added option regex to WikiAdminSearchReplace
2127 //
2128 // Revision 1.91  2004/06/08 14:57:43  rurban
2129 // stupid ldap bug detected by John Cole
2130 //
2131 // Revision 1.90  2004/06/08 09:31:15  rurban
2132 // fixed typo detected by lucidcarbon (line 1663 assertion)
2133 //
2134 // Revision 1.89  2004/06/06 16:58:51  rurban
2135 // added more required ActionPages for foreign languages
2136 // install now english ActionPages if no localized are found. (again)
2137 // fixed default anon user level to be 0, instead of -1
2138 //   (wrong "required administrator to view this page"...)
2139 //
2140 // Revision 1.88  2004/06/04 20:32:53  rurban
2141 // Several locale related improvements suggested by Pierrick Meignen
2142 // LDAP fix by John Cole
2143 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2144 //
2145 // Revision 1.87  2004/06/04 12:40:21  rurban
2146 // Restrict valid usernames to prevent from attacks against external auth or compromise
2147 // possible holes.
2148 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
2149 // Fxied more warnings
2150 //
2151 // Revision 1.86  2004/06/03 18:06:29  rurban
2152 // fix file locking issues (only needed on write)
2153 // fixed immediate LANG and THEME in-session updates if not stored in prefs
2154 // advanced editpage toolbars (search & replace broken)
2155 //
2156 // Revision 1.85  2004/06/03 12:46:03  rurban
2157 // fix signout, level must be 0 not -1
2158 //
2159 // Revision 1.84  2004/06/03 12:36:03  rurban
2160 // fix eval warning on signin
2161 //
2162 // Revision 1.83  2004/06/03 10:18:19  rurban
2163 // fix User locking issues, new config ENABLE_PAGEPERM
2164 //
2165 // Revision 1.82  2004/06/03 09:39:51  rurban
2166 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
2167 //
2168 // Revision 1.81  2004/06/02 18:01:45  rurban
2169 // init global FileFinder to add proper include paths at startup
2170 //   adds PHPWIKI_DIR if started from another dir, lib/pear also
2171 // fix slashify for Windows
2172 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
2173 //
2174 // Revision 1.80  2004/06/02 14:20:27  rurban
2175 // fix adodb DbPassUser login
2176 //
2177 // Revision 1.79  2004/06/01 15:27:59  rurban
2178 // AdminUser only ADMIN_USER not member of Administrators
2179 // some RateIt improvements by dfrankow
2180 // edit_toolbar buttons
2181 //
2182 // Revision 1.78  2004/05/27 17:49:06  rurban
2183 // renamed DB_Session to DbSession (in CVS also)
2184 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
2185 // remove leading slash in error message
2186 // added force_unlock parameter to File_Passwd (no return on stale locks)
2187 // fixed adodb session AffectedRows
2188 // added FileFinder helpers to unify local filenames and DATA_PATH names
2189 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
2190 //
2191 // Revision 1.77  2004/05/18 14:49:51  rurban
2192 // Simplified strings for easier translation
2193 //
2194 // Revision 1.76  2004/05/18 13:30:04  rurban
2195 // prevent from endless loop with oldstyle warnings
2196 //
2197 // Revision 1.75  2004/05/16 22:07:35  rurban
2198 // check more config-default and predefined constants
2199 // various PagePerm fixes:
2200 //   fix default PagePerms, esp. edit and view for Bogo and Password users
2201 //   implemented Creator and Owner
2202 //   BOGOUSERS renamed to BOGOUSER
2203 // fixed syntax errors in signin.tmpl
2204 //
2205 // Revision 1.74  2004/05/15 19:48:33  rurban
2206 // fix some too loose PagePerms for signed, but not authenticated users
2207 //  (admin, owner, creator)
2208 // no double login page header, better login msg.
2209 // moved action_pdf to lib/pdf.php
2210 //
2211 // Revision 1.73  2004/05/15 18:31:01  rurban
2212 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
2213 //
2214 // Revision 1.72  2004/05/12 10:49:55  rurban
2215 // require_once fix for those libs which are loaded before FileFinder and
2216 //   its automatic include_path fix, and where require_once doesn't grok
2217 //   dirname(__FILE__) != './lib'
2218 // upgrade fix with PearDB
2219 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2220 //
2221 // Revision 1.71  2004/05/10 12:34:47  rurban
2222 // stabilize DbAuthParam statement pre-prozessor:
2223 //   try old-style and new-style (double-)quoting
2224 //   reject unknown $variables
2225 //   use ->prepare() for all calls (again)
2226 //
2227 // Revision 1.70  2004/05/06 19:26:16  rurban
2228 // improve stability, trying to find the InlineParser endless loop on sf.net
2229 //
2230 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
2231 //
2232 // Revision 1.69  2004/05/06 13:56:40  rurban
2233 // Enable the Administrators group, and add the WIKIPAGE group default root page.
2234 //
2235 // Revision 1.68  2004/05/05 13:37:54  rurban
2236 // Support to remove all UserPreferences
2237 //
2238 // Revision 1.66  2004/05/03 21:44:24  rurban
2239 // fixed sf,net bug #947264: LDAP options are constants, not strings!
2240 //
2241 // Revision 1.65  2004/05/03 13:16:47  rurban
2242 // fixed UserPreferences update, esp for boolean and int
2243 //
2244 // Revision 1.64  2004/05/02 15:10:06  rurban
2245 // new finally reliable way to detect if /index.php is called directly
2246 //   and if to include lib/main.php
2247 // new global AllActionPages
2248 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
2249 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
2250 // PageGroupTestOne => subpages
2251 // renamed PhpWikiRss to PhpWikiRecentChanges
2252 // more docs, default configs, ...
2253 //
2254 // Revision 1.63  2004/05/01 15:59:29  rurban
2255 // more php-4.0.6 compatibility: superglobals
2256 //
2257 // Revision 1.62  2004/04/29 18:31:24  rurban
2258 // Prevent from warning where no db pref was previously stored.
2259 //
2260 // Revision 1.61  2004/04/29 17:18:19  zorloc
2261 // Fixes permission failure issues.  With PagePermissions and Disabled Actions when user did not have permission WIKIAUTH_FORBIDDEN was returned.  In WikiUser this was ok because WIKIAUTH_FORBIDDEN had a value of 11 -- thus no user could perform that action.  But WikiUserNew has a WIKIAUTH_FORBIDDEN value of -1 -- thus a user without sufficent permission to do anything.  The solution is a new high value permission level (WIKIAUTH_UNOBTAINABLE) to be the default level for access failure.
2262 //
2263 // Revision 1.60  2004/04/27 18:20:54  rurban
2264 // sf.net patch #940359 by rassie
2265 //
2266 // Revision 1.59  2004/04/26 12:35:21  rurban
2267 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
2268 // File_Passwd is already loaded
2269 //
2270 // Revision 1.58  2004/04/20 17:08:28  rurban
2271 // Some IniConfig fixes: prepend our private lib/pear dir
2272 //   switch from " to ' in the auth statements
2273 //   use error handling.
2274 // WikiUserNew changes for the new "'$variable'" syntax
2275 //   in the statements
2276 // TODO: optimization to put config vars into the session.
2277 //
2278 // Revision 1.57  2004/04/19 18:27:45  rurban
2279 // Prevent from some PHP5 warnings (ref args, no :: object init)
2280 //   php5 runs now through, just one wrong XmlElement object init missing
2281 // Removed unneccesary UpgradeUser lines
2282 // Changed WikiLink to omit version if current (RecentChanges)
2283 //
2284 // Revision 1.56  2004/04/19 09:13:24  rurban
2285 // new pref: googleLink
2286 //
2287 // Revision 1.54  2004/04/18 00:24:45  rurban
2288 // re-use our simple prepare: just for table prefix warnings
2289 //
2290 // Revision 1.53  2004/04/12 18:29:15  rurban
2291 // exp. Session auth for already authenticated users from another app
2292 //
2293 // Revision 1.52  2004/04/12 13:04:50  rurban
2294 // added auth_create: self-registering Db users
2295 // fixed IMAP auth
2296 // removed rating recommendations
2297 // ziplib reformatting
2298 //
2299 // Revision 1.51  2004/04/11 10:42:02  rurban
2300 // pgsrc/CreatePagePlugin
2301 //
2302 // Revision 1.50  2004/04/10 05:34:35  rurban
2303 // sf bug#830912
2304 //
2305 // Revision 1.49  2004/04/07 23:13:18  rurban
2306 // fixed pear/File_Passwd for Windows
2307 // fixed FilePassUser sessions (filehandle revive) and password update
2308 //
2309 // Revision 1.48  2004/04/06 20:00:10  rurban
2310 // Cleanup of special PageList column types
2311 // Added support of plugin and theme specific Pagelist Types
2312 // Added support for theme specific UserPreferences
2313 // Added session support for ip-based throttling
2314 //   sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
2315 // Enhanced postgres schema
2316 // Added DB_Session_dba support
2317 //
2318 // Revision 1.47  2004/04/02 15:06:55  rurban
2319 // fixed a nasty ADODB_mysql session update bug
2320 // improved UserPreferences layout (tabled hints)
2321 // fixed UserPreferences auth handling
2322 // improved auth stability
2323 // improved old cookie handling: fixed deletion of old cookies with paths
2324 //
2325 // Revision 1.46  2004/04/01 06:29:51  rurban
2326 // better wording
2327 // RateIt also for ADODB
2328 //
2329
2330 // Local Variables:
2331 // mode: php
2332 // tab-width: 8
2333 // c-basic-offset: 4
2334 // c-hanging-comment-ender-p: nil
2335 // indent-tabs-mode: nil
2336 // End:
2337 ?>