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