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