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