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