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