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