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