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