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