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