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