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