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