]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
check more config-default and predefined constants
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.75 2004-05-16 22:07:35 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             trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1014                                   $stmt), E_USER_WARNING);
1015             $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1016         }
1017         return $new_stmt;
1018     }
1019
1020     function getPreferences() {
1021         if (!empty($this->_prefs->_method)) {
1022             if ($this->_prefs->_method == 'ADODB') {
1023                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
1024                 return _AdoDbPassUser::getPreferences();
1025             } elseif ($this->_prefs->_method == 'SQL') {
1026                 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
1027                 return _PearDbPassUser::getPreferences();
1028             }
1029         }
1030
1031         // We don't necessarily have to read the cookie first. Since
1032         // the user has a password, the prefs stored in the homepage
1033         // cannot be arbitrarily altered by other Bogo users.
1034         _AnonUser::getPreferences();
1035         // User may have deleted cookie, retrieve from his
1036         // PersonalPage if there is one.
1037         if ($this->_HomePagehandle) {
1038             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1039                 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1040                 //$this->_prefs = new UserPreferences($restored_from_page);
1041                 return $this->_prefs;
1042             }
1043         }
1044         return $this->_prefs;
1045     }
1046
1047     function setPreferences($prefs, $id_only=false) {
1048         if (!empty($this->_prefs->_method)) {
1049             if ($this->_prefs->_method == 'ADODB') {
1050                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
1051                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1052             }
1053             elseif ($this->_prefs->_method == 'SQL') {
1054                 _PearDbPassUser::_PearDbPassUser($this->_userid,$prefs);
1055                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1056             }
1057         }
1058         if (_AnonUser::setPreferences($prefs, $id_only)) {
1059             // Encode only the _prefs array of the UserPreference object
1060             if ($this->_HomePagehandle and !$id_only) {
1061                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1062             }
1063         }
1064         return;
1065     }
1066
1067     function mayChangePass() {
1068         return true;
1069     }
1070
1071     //The default method is getting the password from prefs. 
1072     // child methods obtain $stored_password from external auth.
1073     function userExists() {
1074         //if ($this->_HomePagehandle) return true;
1075         $class = $this->nextClass();
1076         while ($user = new $class($this->_userid,$this->_prefs)) {
1077             //todo: with php5 comment the following line:
1078             /*PHP5 patch*/$this = $user;
1079             //UpgradeUser($this,$user);
1080             if ($user->userExists()) {
1081                 return true;
1082             }
1083             // prevent endless loop. does this work on all PHP's?
1084             // it just has to set the classname, what it correctly does.
1085             $class = $user->nextClass();
1086             if ($class == "_ForbiddenPassUser")
1087                 return false;
1088         }
1089         return false;
1090     }
1091
1092     //The default method is getting the password from prefs. 
1093     // child methods obtain $stored_password from external auth.
1094     function checkPass($submitted_password) {
1095         $stored_password = $this->_prefs->get('passwd');
1096         if ($this->_checkPass($submitted_password, $stored_password)) {
1097             $this->_level = WIKIAUTH_USER;
1098             return $this->_level;
1099         } else {
1100             return $this->_tryNextPass($submitted_password);
1101         }
1102     }
1103
1104     /**
1105      * The basic password checker for all PassUser objects.
1106      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1107      * Empty passwords are always false!
1108      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1109      * @see UserPreferences::set
1110      *
1111      * DBPassUser password's have their own crypt definition.
1112      * That's why DBPassUser::checkPass() doesn't call this method, if 
1113      * the db password method is 'plain', which means that the DB SQL 
1114      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
1115      * don't store plain passwords in the DB.
1116      * 
1117      * TODO: remove crypt() function check from config.php:396 ??
1118      */
1119     function _checkPass($submitted_password, $stored_password) {
1120         if(!empty($submitted_password)) {
1121             if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1122                 // Todo. hmm...
1123                 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."));
1124                 return false;
1125             }
1126             if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
1127                 return false;
1128             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
1129                 // Verify against encrypted password.
1130                 if (function_exists('crypt')) {
1131                     if (crypt($submitted_password, $stored_password) == $stored_password )
1132                         return true; // matches encrypted password
1133                     else
1134                         return false;
1135                 }
1136                 else {
1137                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1138                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and probably change ADMIN_PASSWD."),
1139                                   E_USER_WARNING);
1140                     return false;
1141                 }
1142             }
1143             else {
1144                 // Verify against cleartext password.
1145                 if ($submitted_password == $stored_password)
1146                     return true;
1147                 else {
1148                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1149                     if (function_exists('crypt')) {
1150                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1151                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
1152                                           E_USER_WARNING);
1153                             return true;
1154                         }
1155                     }
1156                 }
1157             }
1158         }
1159         return false;
1160     }
1161
1162     /** The default method is storing the password in prefs. 
1163      *  Child methods (DB,File) may store in external auth also, but this 
1164      *  must be explicitly enabled.
1165      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1166      */
1167     function changePass($submitted_password) {
1168         $stored_password = $this->_prefs->get('passwd');
1169         // check if authenticated
1170         if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1171             $this->_prefs->set('passwd',$submitted_password);
1172             //update the storage (session, homepage, ...)
1173             $this->SetPreferences($this->_prefs);
1174             return true;
1175         }
1176         //Todo: return an error msg to the caller what failed? 
1177         // same password or no privilege
1178         return false;
1179     }
1180
1181     function _tryNextPass($submitted_password) {
1182         if (USER_AUTH_POLICY === 'strict') {
1183                 $class = $this->nextClass();
1184             if ($user = new $class($this->_userid,$this->_prefs)) {
1185                 if ($user->userExists()) {
1186                     return $user->checkPass($submitted_password);
1187                 }
1188             }
1189         }
1190         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1191                 $class = $this->nextClass();
1192             if ($user = new $class($this->_userid,$this->_prefs))
1193                 return $user->checkPass($submitted_password);
1194         }
1195         return $this->_level;
1196     }
1197
1198     function _tryNextUser() {
1199         if (USER_AUTH_POLICY === 'strict') {
1200                 $class = $this->nextClass();
1201             while ($user = new $class($this->_userid,$this->_prefs)) {
1202                 //todo: with php5 comment the following line:
1203                 /*PHP5 patch*/$this = $user;
1204                 //$user = UpgradeUser($this, $user);
1205                 if ($user->userExists()) {
1206                     return true;
1207                 }
1208                 $class = $this->nextClass();
1209             }
1210         }
1211         return false;
1212     }
1213
1214 }
1215
1216 /** Without stored password. A _BogoLoginPassUser with password 
1217  *  is automatically upgraded to a PersonalPagePassUser.
1218  */
1219 class _BogoLoginPassUser
1220 extends _PassUser
1221 {
1222     var $_authmethod = 'BogoLogin';
1223     function userExists() {
1224         if (isWikiWord($this->_userid)) {
1225             $this->_level = WIKIAUTH_BOGO;
1226             return true;
1227         } else {
1228             $this->_level = WIKIAUTH_ANON;
1229             return false;
1230         }
1231     }
1232
1233     /** A BogoLoginUser requires no password at all
1234      *  But if there's one stored, we should prefer PersonalPage instead
1235      */
1236     function checkPass($submitted_password) {
1237         if ($this->_prefs->get('passwd')) {
1238             $user = new _PersonalPagePassUser($this->_userid);
1239             if ($user->checkPass($submitted_password)) {
1240                 //todo: with php5 comment the following line:
1241                 /*PHP5 patch*/$this = $user;
1242                 $user = UpgradeUser($this, $user);
1243                 $this->_level = WIKIAUTH_USER;
1244                 return $this->_level;
1245             } else {
1246                 $this->_level = WIKIAUTH_ANON;
1247                 return $this->_level;
1248             }
1249         }
1250         $this->userExists();
1251         return $this->_level;
1252     }
1253 }
1254
1255
1256 /**
1257  * This class is only to simplify the auth method dispatcher.
1258  * It inherits almost all all methods from _PassUser.
1259  */
1260 class _PersonalPagePassUser
1261 extends _PassUser
1262 {
1263     var $_authmethod = 'PersonalPage';
1264
1265     function userExists() {
1266         return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1267     }
1268
1269     /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1270      *  BUT if the user already has a homepage with an empty password 
1271      *  stored, allow login but warn him to change it.
1272      */
1273     function checkPass($submitted_password) {
1274         if ($this->userExists()) {
1275             $stored_password = $this->_prefs->get('passwd');
1276             if (empty($stored_password)) {
1277                 trigger_error(sprintf(
1278                 _("\nYou stored an empty password in your '%s' page.\n").
1279                 _("Your access permissions are only for a BogoUser.\n").
1280                 _("Please set your password in UserPreferences."),
1281                                         $this->_userid), E_USER_NOTICE);
1282                 $this->_level = WIKIAUTH_BOGO;
1283                 return $this->_level;
1284             }
1285             if ($this->_checkPass($submitted_password, $stored_password))
1286                 return ($this->_level = WIKIAUTH_USER);
1287             return _PassUser::checkPass($submitted_password);
1288         }
1289         return WIKIAUTH_ANON;
1290     }
1291 }
1292
1293 /**
1294  * We have two possibilities here.
1295  * 1) The webserver location is already HTTP protected (usually Basic). Then just 
1296  *    use the username and do nothing
1297  * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1298  *    by sending a 401 error and let the client display the login dialog.
1299  *    This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1300  *    since the other methods cannot be transparently called after this enforced 
1301  *    external dialog.
1302  *    Try the available auth methods (most likely Bogo) and sent this header back.
1303  *    header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1304  */
1305 class _HttpAuthPassUser
1306 extends _PassUser
1307 {
1308     function _HttpAuthPassUser($UserName='',$prefs=false) {
1309         if ($prefs) $this->_prefs = $prefs;
1310         if (!isset($this->_prefs->_method))
1311            _PassUser::_PassUser($UserName);
1312         if ($UserName) $this->_userid = $UserName;
1313         $this->_authmethod = 'HttpAuth';
1314         if ($this->userExists())
1315             return $this;
1316         else 
1317             return $GLOBALS['ForbiddenUser'];
1318     }
1319
1320     function _http_username() {
1321         if (!isset($_SERVER))
1322             $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
1323         if (!empty($_SERVER['PHP_AUTH_USER']))
1324             return $_SERVER['PHP_AUTH_USER'];
1325         if (!empty($_SERVER['REMOTE_USER']))
1326             return $_SERVER['REMOTE_USER'];
1327         if (!empty($GLOBALS['HTTP_ENV_VARS']['REMOTE_USER']))
1328             return $GLOBALS['HTTP_ENV_VARS']['REMOTE_USER'];
1329         if (!empty($GLOBALS['REMOTE_USER']))
1330             return $GLOBALS['REMOTE_USER'];
1331         return '';
1332     }
1333     
1334     //force http auth authorization
1335     function userExists() {
1336         // todo: older php's
1337         $username = $this->_http_username();
1338         if (empty($username) or $username != $this->_userid) {
1339             header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1340             header('HTTP/1.0 401 Unauthorized'); 
1341             exit;
1342         }
1343         $this->_userid = $username;
1344         $this->_level = WIKIAUTH_USER;
1345         return $this;
1346     }
1347         
1348     function checkPass($submitted_password) {
1349         return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1350     }
1351
1352     function mayChangePass() {
1353         return false;
1354     }
1355
1356     // hmm... either the server dialog or our own.
1357     function PrintLoginForm (&$request, $args, $fail_message = false,
1358                              $seperate_page = true) {
1359         header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1360         header('HTTP/1.0 401 Unauthorized'); 
1361         exit;
1362     }
1363
1364 }
1365
1366 /** 
1367  * Support reuse of existing user session from another application.
1368  * You have to define which session variable holds the userid, and 
1369  * at what level is that user then. 1: BogoUser, 2: PassUser
1370  *   define('AUTH_SESS_USER','userid');
1371  *   define('AUTH_SESS_LEVEL',2);
1372  */
1373 class _SessionPassUser
1374 extends _PassUser
1375 {
1376     function _SessionPassUser($UserName='',$prefs=false) {
1377         if ($prefs) $this->_prefs = $prefs;
1378         if (!defined("AUTH_SESS_USER") or !defined("AUTH_SESS_LEVEL")) {
1379             trigger_error(
1380                 "AUTH_SESS_USER or AUTH_SESS_LEVEL is not defined for the SessionPassUser method",
1381                 E_USER_ERROR);
1382             exit;
1383         }
1384         $sess =& $GLOBALS['HTTP_SESSION_VARS'];
1385         // FIXME: user hash: "[user][userid]" or object "user->id"
1386         $this->_userid = $sess[AUTH_SESS_USER];
1387         if (!isset($this->_prefs->_method))
1388            _PassUser::_PassUser($this->_userid);
1389         $this->_level = AUTH_SESS_LEVEL;
1390         $this->_authmethod = 'Session';
1391     }
1392     function userExists() {
1393         return !empty($this->_userid);
1394     }
1395     function checkPass($submitted_password) {
1396         return $this->userExists() and $this->_level;
1397     }
1398     function mayChangePass() {
1399         return false;
1400     }
1401 }
1402
1403 /**
1404  * Baseclass for PearDB and ADODB PassUser's
1405  * Authenticate against a database, to be able to use shared users.
1406  *   internal: no different $DbAuthParams['dsn'] defined, or
1407  *   external: different $DbAuthParams['dsn']
1408  * The magic is done in the symbolic SQL statements in index.php, similar to
1409  * libnss-mysql.
1410  *
1411  * We support only the SQL and ADODB backends.
1412  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
1413  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
1414  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn']. 
1415  * (Not supported yet, since we require SQL. SQLite would make since when 
1416  * it will come to PHP)
1417  *
1418  * @tables: user, pref
1419  *
1420  * Preferences are handled in the parent class _PassUser, because the 
1421  * previous classes may also use DB pref_select and pref_update.
1422  *
1423  * Flat files auth is handled by the auth method "File".
1424  */
1425 class _DbPassUser
1426 extends _PassUser
1427 {
1428     var $_authselect, $_authupdate, $_authcreate;
1429
1430     // This can only be called from _PassUser, because the parent class 
1431     // sets the auth_dbi and pref methods, before this class is initialized.
1432     function _DbPassUser($UserName='',$prefs=false) {
1433         if (!$this->_prefs) {
1434             if ($prefs) $this->_prefs = $prefs;
1435         }
1436         if (!isset($this->_prefs->_method))
1437            _PassUser::_PassUser($UserName);
1438         $this->_authmethod = 'Db';
1439         //$this->getAuthDbh();
1440         //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1441         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') {
1442             if (check_php_version(5))
1443                 return new _AdoDbPassUser($UserName,$this->_prefs);
1444             else {
1445                 $user = new _AdoDbPassUser($UserName,$this->_prefs);
1446                 //todo: with php5 comment the following line:
1447                 /*PHP5 patch*/$this = $user;
1448                 return $user;
1449             }
1450         }
1451         elseif ($GLOBALS['DBParams']['dbtype'] == 'SQL') {
1452             if (check_php_version(5))
1453                 return new _PearDbPassUser($UserName,$this->_prefs);
1454             else {
1455                 $user = new _PearDbPassUser($UserName,$this->_prefs);
1456                 //todo: with php5 comment the following line:
1457                 /*PHP5 patch*/$this = $user;
1458                 return $user;
1459             }
1460         }
1461         return false;
1462     }
1463
1464     function mayChangePass() {
1465         return !isset($this->_authupdate);
1466     }
1467
1468 }
1469
1470 class _PearDbPassUser
1471 extends _DbPassUser
1472 /**
1473  * Pear DB methods
1474  * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1475  * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1476  *
1477  * @tables: user
1478  * @tables: pref
1479  */
1480 {
1481     var $_authmethod = 'PearDb';
1482     function _PearDbPassUser($UserName='',$prefs=false) {
1483         global $DBAuthParams;
1484         if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1485             if ($prefs) $this->_prefs = $prefs;
1486         }
1487         if (!isset($this->_prefs->_method))
1488             _PassUser::_PassUser($UserName);
1489         $this->_userid = $UserName;
1490         // make use of session data. generally we only initialize this every time, 
1491         // but do auth checks only once
1492         $this->_auth_crypt_method = @$DBAuthParams['auth_crypt_method'];
1493         //$this->getAuthDbh();
1494         return $this;
1495     }
1496
1497     function getPreferences() {
1498         // override the generic slow method here for efficiency and not to 
1499         // clutter the homepage metadata with prefs.
1500         _AnonUser::getPreferences();
1501         $this->getAuthDbh();
1502         if (isset($this->_prefs->_select)) {
1503             $dbh = &$this->_auth_dbi;
1504             $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1505             // patched by frederik@pandora.be
1506             $prefs = $db_result->fetchRow();
1507             $prefs_blob = @$prefs["prefs"]; 
1508             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1509                 $updated = $this->_prefs->updatePrefs($restored_from_db);
1510                 //$this->_prefs = new UserPreferences($restored_from_db);
1511                 return $this->_prefs;
1512             }
1513         }
1514         if ($this->_HomePagehandle) {
1515             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1516                 $updated = $this->_prefs->updatePrefs($restored_from_page);
1517                 //$this->_prefs = new UserPreferences($restored_from_page);
1518                 return $this->_prefs;
1519             }
1520         }
1521         return $this->_prefs;
1522     }
1523
1524     function setPreferences($prefs, $id_only=false) {
1525         // if the prefs are changed
1526         if ($count = _AnonUser::setPreferences($prefs, 1)) {
1527             //global $request;
1528             //$user = $request->_user;
1529             //unset($user->_auth_dbi);
1530             // this must be done in $request->_setUser, not here!
1531             //$request->setSessionVar('wiki_user', $user);
1532             $this->getAuthDbh();
1533             $packed = $this->_prefs->store();
1534             if (!$id_only and isset($this->_prefs->_update)) {
1535                 $dbh = &$this->_auth_dbi;
1536                 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1537                                           $dbh->quote($packed),
1538                                           $dbh->quote($this->_userid)));
1539             } else {
1540                 //store prefs in homepage, not in cookie
1541                 if ($this->_HomePagehandle and !$id_only)
1542                     $this->_HomePagehandle->set('pref', $packed);
1543             }
1544             return $count; //count($this->_prefs->unpack($packed));
1545         }
1546         return 0;
1547     }
1548
1549     function userExists() {
1550         global $DBAuthParams;
1551         $this->getAuthDbh();
1552         $dbh = &$this->_auth_dbi;
1553         if (!$dbh) { // needed?
1554             return $this->_tryNextUser();
1555         }
1556         // Prepare the configured auth statements
1557         if (!empty($DBAuthParams['auth_check']) and empty($this->_authselect)) {
1558             $this->_authselect = $this->prepare($DBAuthParams['auth_check'], 
1559                                                 array("userid","password"));
1560         }
1561         if (empty($this->_authselect))
1562             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1563                           E_USER_WARNING);
1564         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1565         if ($this->_auth_crypt_method == 'crypt') {
1566             $rs = $dbh->query(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1567             if ($rs->numRows())
1568                 return true;
1569         }
1570         else {
1571             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1572                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1573                               E_USER_WARNING);
1574             $this->_authcheck = $this->prepare($DBAuthParams['auth_user_exists'],"userid");
1575             $rs = $dbh->query(sprintf($this->_authcheck,$dbh->quote($this->_userid)));
1576             if ($rs->numRows())
1577                 return true;
1578         }
1579         // maybe the user is allowed to create himself. Generally not wanted in 
1580         // external databases, but maybe wanted for the wiki database, for performance 
1581         // reasons
1582         if (empty($this->_authcreate) and !empty($DBAuthParams['auth_create'])) {
1583             $this->_authcreate = $this->prepare($DBAuthParams['auth_create'],
1584                                                 array("userid","password"));
1585         }
1586         if (!empty($this->_authcreate)) {
1587             $dbh->simpleQuery(sprintf($this->_authcreate,
1588                                       $dbh->quote($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1589                                       $dbh->quote($this->_userid)
1590                                       ));
1591             return true;
1592         }
1593         return $this->_tryNextUser();
1594     }
1595  
1596     function checkPass($submitted_password) {
1597         global $DBAuthParams;
1598         $this->getAuthDbh();
1599         if (!$this->_auth_dbi) {  // needed?
1600             return $this->_tryNextPass($submitted_password);
1601         }
1602         if (!isset($this->_authselect))
1603             $this->userExists();
1604         if (!isset($this->_authselect))
1605             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1606                           E_USER_WARNING);
1607
1608         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1609         $dbh = &$this->_auth_dbi;
1610         if ($this->_auth_crypt_method == 'crypt') {
1611             $stored_password = $dbh->getOne(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1612             $result = $this->_checkPass($submitted_password, $stored_password);
1613         } else {
1614             $okay = $dbh->getOne(sprintf($this->_authselect,
1615                                          $dbh->quote($submitted_password),
1616                                          $dbh->quote($this->_userid)));
1617             $result = !empty($okay);
1618         }
1619
1620         if ($result) {
1621             $this->_level = WIKIAUTH_USER;
1622             return $this->_level;
1623         } else {
1624             return $this->_tryNextPass($submitted_password);
1625         }
1626     }
1627
1628     function mayChangePass() {
1629         global $DBAuthParams;
1630         return !empty($DBAuthParams['auth_update']);
1631     }
1632
1633     function storePass($submitted_password) {
1634         global $DBAuthParams;
1635         if (!empty($DBAuthParams['auth_update']) and empty($this->_authupdate)) {
1636             $this->_authupdate = $this->prepare($DBAuthParams['auth_update'],
1637                                                 array("userid","password"));
1638         }
1639         if (empty($this->_authupdate)) {
1640             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1641                           E_USER_WARNING);
1642             return false;
1643         }
1644
1645         if ($this->_auth_crypt_method == 'crypt') {
1646             if (function_exists('crypt'))
1647                 $submitted_password = crypt($submitted_password);
1648         }
1649         $this->getAuthDbh();
1650         $dbh = &$this->_auth_dbi;
1651         $dbh->simpleQuery(sprintf($this->_authupdate,
1652                                   $dbh->quote($submitted_password),
1653                                   $dbh->quote($this->_userid)
1654                                   ));
1655     }
1656
1657 }
1658
1659 class _AdoDbPassUser
1660 extends _DbPassUser
1661 /**
1662  * ADODB methods
1663  * Simple sprintf, no prepare.
1664  *
1665  * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster 
1666  * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1667  *
1668  * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1669  *
1670  * @tables: user
1671  */
1672 {
1673     var $_authmethod = 'AdoDb';
1674     function _AdoDbPassUser($UserName='',$prefs=false) {
1675         if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1676             if ($prefs) $this->_prefs = $prefs;
1677             if (!isset($this->_prefs->_method))
1678               _PassUser::_PassUser($UserName);
1679         }
1680         $this->_userid = $UserName;
1681         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1682         $this->getAuthDbh();
1683         // Don't prepare the configured auth statements anymore
1684         return $this;
1685     }
1686
1687     function getPreferences() {
1688         // override the generic slow method here for efficiency
1689         _AnonUser::getPreferences();
1690         $this->getAuthDbh();
1691         if (isset($this->_prefs->_select)) {
1692             $dbh = & $this->_auth_dbi;
1693             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
1694             if ($rs->EOF) {
1695                 $rs->Close();
1696             } else {
1697                 $prefs_blob = @$rs->fields['prefs'];
1698                 $rs->Close();
1699                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1700                     $updated = $this->_prefs->updatePrefs($restored_from_db);
1701                     //$this->_prefs = new UserPreferences($restored_from_db);
1702                     return $this->_prefs;
1703                 }
1704             }
1705         }
1706         if ($this->_HomePagehandle) {
1707             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1708                 $updated = $this->_prefs->updatePrefs($restored_from_page);
1709                 //$this->_prefs = new UserPreferences($restored_from_page);
1710                 return $this->_prefs;
1711             }
1712         }
1713         return $this->_prefs;
1714     }
1715
1716     function setPreferences($prefs, $id_only=false) {
1717         // if the prefs are changed
1718         if (_AnonUser::setPreferences($prefs, 1)) {
1719             global $request;
1720             $packed = $this->_prefs->store();
1721             //$user = $request->_user;
1722             //unset($user->_auth_dbi);
1723             if (!$id_only and isset($this->_prefs->_update)) {
1724                 $this->getAuthDbh();
1725                 $dbh = &$this->_auth_dbi;
1726                 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1727                                                    $dbh->qstr($packed),
1728                                                    $dbh->qstr($this->_userid)));
1729                 $db_result->Close();
1730             } else {
1731                 //store prefs in homepage, not in cookie
1732                 if ($this->_HomePagehandle and !$id_only)
1733                     $this->_HomePagehandle->set('pref', $packed);
1734             }
1735             return count($this->_prefs->unpack($packed));
1736         }
1737         return 0;
1738     }
1739  
1740     function userExists() {
1741         global $DBAuthParams;
1742         $this->getAuthDbh();
1743         $dbh = &$this->_auth_dbi;
1744         if (!$dbh) { // needed?
1745             return $this->_tryNextUser();
1746         }
1747         if (empty($this->_authselect) and !empty($DBAuthParams['auth_check'])) {
1748             $this->_authselect = $this->prepare($DBAuthParams['auth_check'],
1749                                                 array("userid","password"));
1750         }
1751         if (empty($this->_authselect))
1752             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1753                           E_USER_WARNING);
1754         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1755         if ($this->_auth_crypt_method == 'crypt') {
1756             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1757             if (!$rs->EOF) {
1758                 $rs->Close();
1759                 return true;
1760             } else {
1761                 $rs->Close();
1762             }
1763         }
1764         else {
1765             if (! $DBAuthParams['auth_user_exists'])
1766                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1767                               E_USER_WARNING);
1768             $this->_authcheck = $this->prepare($DBAuthParams['auth_user_exists'],'userid');
1769             $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1770             if (!$rs->EOF) {
1771                 $rs->Close();
1772                 return true;
1773             } else {
1774                 $rs->Close();
1775             }
1776         }
1777         // maybe the user is allowed to create himself. Generally not wanted in 
1778         // external databases, but maybe wanted for the wiki database, for performance 
1779         // reasons
1780         if (empty($this->_authcreate) and !empty($DBAuthParams['auth_create'])) {
1781             $this->_authcreate = $this->prepare($DBAuthParams['auth_create'],
1782                                                 array("userid","password"));
1783         }
1784         if (!empty($this->_authcreate) and 
1785             isset($GLOBALS['HTTP_POST_VARS']['auth']) and
1786             isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd'])) {
1787             $dbh->Execute(sprintf($this->_authcreate,
1788                                   $dbh->qstr($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1789                                   $dbh->qstr($this->_userid)));
1790             return true;
1791         }
1792         
1793         return $this->_tryNextUser();
1794     }
1795
1796     function checkPass($submitted_password) {
1797         global $DBAuthParams;
1798         $this->getAuthDbh();
1799         if (!$this->_auth_dbi) {  // needed?
1800             return $this->_tryNextPass($submitted_password);
1801         }
1802         if (empty($this->_authselect) and !empty($DBAuthParams['auth_check'])) {
1803             $this->_authselect = $this->prepare($DBAuthParams['auth_check'],
1804                                                 array("userid","password"));
1805         }
1806         if (!isset($this->_authselect))
1807             $this->userExists();
1808         if (!isset($this->_authselect))
1809             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1810                           E_USER_WARNING);
1811         $dbh = &$this->_auth_dbi;
1812         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1813         if ($this->_auth_crypt_method == 'crypt') {
1814             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1815             if (!$rs->EOF) {
1816                 $stored_password = $rs->fields['password'];
1817                 $rs->Close();
1818                 $result = $this->_checkPass($submitted_password, $stored_password);
1819             } else {
1820                 $rs->Close();
1821                 $result = false;
1822             }
1823         }
1824         else {
1825             $rs = $dbh->Execute(sprintf($this->_authselect,
1826                                         $dbh->qstr($submitted_password),
1827                                         $dbh->qstr($this->_userid)));
1828             $okay = $rs->fields['ok'];
1829             $rs->Close();
1830             $result = !empty($okay);
1831         }
1832
1833         if ($result) { 
1834             $this->_level = WIKIAUTH_USER;
1835             return $this->_level;
1836         } else {
1837             return $this->_tryNextPass($submitted_password);
1838         }
1839     }
1840
1841     function mayChangePass() {
1842         global $DBAuthParams;
1843         return !empty($DBAuthParams['auth_update']);
1844     }
1845
1846     function storePass($submitted_password) {
1847         global $DBAuthParams;
1848         if (!isset($this->_authupdate) and !empty($DBAuthParams['auth_update'])) {
1849             $this->_authupdate = $this->prepare($DBAuthParams['auth_update'],
1850                                                 array("userid","password"));
1851         }
1852         if (!isset($this->_authupdate)) {
1853             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1854                           E_USER_WARNING);
1855             return false;
1856         }
1857
1858         if ($this->_auth_crypt_method == 'crypt') {
1859             if (function_exists('crypt'))
1860                 $submitted_password = crypt($submitted_password);
1861         }
1862         $this->getAuthDbh();
1863         $dbh = &$this->_auth_dbi;
1864         $rs = $dbh->Execute(sprintf($this->_authupdate,
1865                                     $dbh->qstr($submitted_password),
1866                                     $dbh->qstr($this->_userid)
1867                                     ));
1868         $rs->Close();
1869         return $rs;
1870     }
1871
1872 }
1873
1874 class _LDAPPassUser
1875 extends _PassUser
1876 /**
1877  * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in index.php
1878  *
1879  * Preferences are handled in _PassUser
1880  */
1881 {
1882     function checkPass($submitted_password) {
1883         global $LDAP_SET_OPTION;
1884
1885         $this->_authmethod = 'LDAP';
1886         $userid = $this->_userid;
1887         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1888             if (defined('LDAP_AUTH_USER'))
1889                 if (defined('LDAP_AUTH_PASSWORD'))
1890                     // Windows Active Directory Server is strict
1891                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1892                 else
1893                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1894             else
1895                 $r = @ldap_bind($ldap); // this is an anonymous bind
1896             if (!empty($LDAP_SET_OPTION)) {
1897                 foreach ($LDAP_SET_OPTION as $key => $value) {
1898                     if (is_string($key) and defined($key))
1899                         $key = constant($key);
1900                     ldap_set_option($ldap,$key,$value);
1901                 }
1902             }
1903             // Need to set the right root search information. see ../index.php
1904             $st_search = defined('LDAP_SEARCH_FIELD') 
1905                 ? LDAP_SEARCH_FIELD."=$userid"
1906                 : "uid=$userid";
1907             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1908             $info = ldap_get_entries($ldap, $sr); 
1909             // there may be more hits with this userid.
1910             // of course it would be better to narrow down the BASE_DN
1911             for ($i = 0; $i < $info["count"]; $i++) {
1912                 $dn = $info[$i]["dn"];
1913                 // The password is still plain text.
1914                 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
1915                     // ldap_bind will return TRUE if everything matches
1916                     ldap_close($ldap);
1917                     $this->_level = WIKIAUTH_USER;
1918                     return $this->_level;
1919                 }
1920             }
1921         } else {
1922             trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), 
1923                           E_USER_WARNING);
1924             //return false;
1925         }
1926
1927         return $this->_tryNextPass($submitted_password);
1928     }
1929
1930     function userExists() {
1931         global $LDAP_SET_OPTION;
1932
1933         $userid = $this->_userid;
1934         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1935             if (defined('LDAP_AUTH_USER'))
1936                 if (defined('LDAP_AUTH_PASSWORD'))
1937                     // Windows Active Directory Server is strict
1938                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1939                 else
1940                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1941             else
1942                 $r = @ldap_bind($ldap); // this is an anonymous bind
1943             if (!empty($LDAP_SET_OPTION)) {
1944                 foreach ($LDAP_SET_OPTION as $key => $value) {
1945                     ldap_set_option($ldap,$key,$value);
1946                 }
1947             }
1948             // Need to set the right root search information. see ../index.php
1949             $st_search = defined('LDAP_SEARCH_FIELD') 
1950                 ? LDAP_SEARCH_FIELD."=$userid"
1951                 : "uid=$userid";
1952             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1953             $info = ldap_get_entries($ldap, $sr); 
1954
1955             if ($info["count"] > 0) {
1956                 ldap_close($ldap);
1957                 return true;
1958             }
1959         } else {
1960             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1961         }
1962
1963         return $this->_tryNextUser();
1964     }
1965
1966     function mayChangePass() {
1967         return false;
1968     }
1969
1970 }
1971
1972 class _IMAPPassUser
1973 extends _PassUser
1974 /**
1975  * Define the var IMAP_AUTH_HOST in index.php (with port probably)
1976  *
1977  * Preferences are handled in _PassUser
1978  */
1979 {
1980     function checkPass($submitted_password) {
1981         $userid = $this->_userid;
1982         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1983                             $userid, $submitted_password, OP_HALFOPEN );
1984         if ($mbox) {
1985             imap_close($mbox);
1986             $this->_authmethod = 'IMAP';
1987             $this->_level = WIKIAUTH_USER;
1988             return $this->_level;
1989         } else {
1990             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1991         }
1992
1993         return $this->_tryNextPass($submitted_password);
1994     }
1995
1996     //CHECKME: this will not be okay for the auth policy strict
1997     function userExists() {
1998         return true;
1999         if (checkPass($this->_prefs->get('passwd')))
2000             return true;
2001             
2002         return $this->_tryNextUser();
2003     }
2004
2005     function mayChangePass() {
2006         return false;
2007     }
2008 }
2009
2010
2011 class _POP3PassUser
2012 extends _IMAPPassUser {
2013 /**
2014  * Define the var POP3_AUTH_HOST in index.php
2015  * Preferences are handled in _PassUser
2016  */
2017     function checkPass($submitted_password) {
2018         $userid = $this->_userid;
2019         $pass = $submitted_password;
2020         $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost:110';
2021         if (defined('POP3_AUTH_PORT'))
2022             $port = POP3_AUTH_PORT;
2023         elseif (strstr($host,':')) {
2024             list(,$port) = split(':',$host);
2025         } else {
2026             $port = 110;
2027         }
2028         $retval = false;
2029         $fp = fsockopen($host, $port, $errno, $errstr, 10);
2030         if ($fp) {
2031             // Get welcome string
2032             $line = fgets($fp, 1024);
2033             if (! strncmp("+OK ", $line, 4)) {
2034                 // Send user name
2035                 fputs($fp, "user $userid\n");
2036                 // Get response
2037                 $line = fgets($fp, 1024);
2038                 if (! strncmp("+OK ", $line, 4)) {
2039                     // Send password
2040                     fputs($fp, "pass $pass\n");
2041                     // Get response
2042                     $line = fgets($fp, 1024);
2043                     if (! strncmp("+OK ", $line, 4)) {
2044                         $retval = true;
2045                     }
2046                 }
2047             }
2048             // quit the connection
2049             fputs($fp, "quit\n");
2050             // Get the sayonara message
2051             $line = fgets($fp, 1024);
2052             fclose($fp);
2053         } else {
2054             trigger_error(_("Couldn't connect to %s","POP3_AUTH_HOST ".$host.':'.$port),
2055                           E_USER_WARNING);
2056         }
2057         $this->_authmethod = 'POP3';
2058         if ($retval) {
2059             $this->_level = WIKIAUTH_USER;
2060         } else {
2061             $this->_level = WIKIAUTH_ANON;
2062         }
2063         return $this->_level;
2064     }
2065 }
2066
2067 class _FilePassUser
2068 extends _PassUser
2069 /**
2070  * Check users defined in a .htaccess style file
2071  * username:crypt\n...
2072  *
2073  * Preferences are handled in _PassUser
2074  */
2075 {
2076     var $_file, $_may_change;
2077
2078     // This can only be called from _PassUser, because the parent class 
2079     // sets the pref methods, before this class is initialized.
2080     function _FilePassUser($UserName='',$prefs=false,$file='') {
2081         if (!$this->_prefs and isa($this,"_FilePassUser")) {
2082             if ($prefs) $this->_prefs = $prefs;
2083             if (!isset($this->_prefs->_method))
2084               _PassUser::_PassUser($UserName);
2085         }
2086
2087         $this->_userid = $UserName;
2088         // read the .htaccess style file. We use our own copy of the standard pear class.
2089         //include_once 'lib/pear/File_Passwd.php';
2090         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
2091         if (empty($file) and defined('AUTH_USER_FILE'))
2092             $file = AUTH_USER_FILE;
2093         // if passwords may be changed we have to lock them:
2094         if ($this->_may_change) {
2095             $lock = true;
2096             $lockfile = $file . ".lock";
2097         } else {
2098             $lock = false;
2099             $lockfile = false;
2100         }
2101         // "__PHP_Incomplete_Class"
2102         if (!empty($file) or empty($this->_file) or !isa($this->_file,"File_Passwd"))
2103             $this->_file = new File_Passwd($file, $lock, $lockfile);
2104         else
2105             return false;
2106         return $this;
2107     }
2108  
2109     function mayChangePass() {
2110         return $this->_may_change;
2111     }
2112
2113     function userExists() {
2114         $this->_authmethod = 'File';
2115         if (isset($this->_file->users[$this->_userid]))
2116             return true;
2117             
2118         return $this->_tryNextUser();
2119     }
2120
2121     function checkPass($submitted_password) {
2122         //include_once 'lib/pear/File_Passwd.php';
2123         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
2124             $this->_authmethod = 'File';
2125             $this->_level = WIKIAUTH_USER;
2126             return $this->_level;
2127         }
2128         
2129         return $this->_tryNextPass($submitted_password);
2130     }
2131
2132     function storePass($submitted_password) {
2133         if ($this->_may_change) {
2134             if ($this->_file->modUser($this->_userid,$submitted_password)) {
2135                 $this->_file->close();
2136                 $this->_file = new File_Passwd($this->_file->_filename, true, $this->_file->lockfile);
2137                 return true;
2138             }
2139         }
2140         return false;
2141     }
2142
2143 }
2144
2145 /**
2146  * Insert more auth classes here...
2147  * For example a customized db class for another db connection 
2148  * or a socket-based auth server
2149  *
2150  */
2151
2152
2153 /**
2154  * For security, this class should not be extended. Instead, extend
2155  * from _PassUser (think of this as unix "root").
2156  */
2157 class _AdminUser
2158 extends _PassUser
2159 {
2160     function mayChangePass() {
2161         return false;
2162     }
2163     function checkPass($submitted_password) {
2164         $stored_password = ADMIN_PASSWD;
2165         if ($this->_checkPass($submitted_password, $stored_password)) {
2166             $this->_level = WIKIAUTH_ADMIN;
2167             return $this->_level;
2168         } else {
2169             $this->_level = WIKIAUTH_ANON;
2170             return $this->_level;
2171         }
2172     }
2173     function storePass($submitted_password) {
2174         return false;
2175     }
2176 }
2177
2178 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2179 /**
2180  * Various data classes for the preference types, 
2181  * to support get, set, sanify (range checking, ...)
2182  * update() will do the neccessary side-effects if a 
2183  * setting gets changed (theme, language, ...)
2184 */
2185
2186 class _UserPreference
2187 {
2188     var $default_value;
2189
2190     function _UserPreference ($default_value) {
2191         $this->default_value = $default_value;
2192     }
2193
2194     function sanify ($value) {
2195         return (string)$value;
2196     }
2197
2198     function get ($name) {
2199         if (isset($this->{$name}))
2200             return $this->{$name};
2201         else 
2202             return $this->default_value;
2203     }
2204
2205     function getraw ($name) {
2206         if (!empty($this->{$name}))
2207             return $this->{$name};
2208     }
2209
2210     // stores the value as $this->$name, and not as $this->value (clever?)
2211     function set ($name, $value) {
2212         $return = 0;
2213         $value = $this->sanify($value);
2214         if ($this->get($name) != $value) {
2215             $this->update($value);
2216             $return = 1;
2217         }
2218         if ($value != $this->default_value) {
2219             $this->{$name} = $value;
2220         } else {
2221             unset($this->{$name});
2222         }
2223         return $return;
2224     }
2225
2226     // default: no side-effects 
2227     function update ($value) {
2228         ;
2229     }
2230 }
2231
2232 class _UserPreference_numeric
2233 extends _UserPreference
2234 {
2235     function _UserPreference_numeric ($default, $minval = false,
2236                                       $maxval = false) {
2237         $this->_UserPreference((double)$default);
2238         $this->_minval = (double)$minval;
2239         $this->_maxval = (double)$maxval;
2240     }
2241
2242     function sanify ($value) {
2243         $value = (double)$value;
2244         if ($this->_minval !== false && $value < $this->_minval)
2245             $value = $this->_minval;
2246         if ($this->_maxval !== false && $value > $this->_maxval)
2247             $value = $this->_maxval;
2248         return $value;
2249     }
2250 }
2251
2252 class _UserPreference_int
2253 extends _UserPreference_numeric
2254 {
2255     function _UserPreference_int ($default, $minval = false, $maxval = false) {
2256         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
2257     }
2258
2259     function sanify ($value) {
2260         return (int)parent::sanify((int)$value);
2261     }
2262 }
2263
2264 class _UserPreference_bool
2265 extends _UserPreference
2266 {
2267     function _UserPreference_bool ($default = false) {
2268         $this->_UserPreference((bool)$default);
2269     }
2270
2271     function sanify ($value) {
2272         if (is_array($value)) {
2273             /* This allows for constructs like:
2274              *
2275              *   <input type="hidden" name="pref[boolPref][]" value="0" />
2276              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
2277              *
2278              * (If the checkbox is not checked, only the hidden input
2279              * gets sent. If the checkbox is sent, both inputs get
2280              * sent.)
2281              */
2282             foreach ($value as $val) {
2283                 if ($val)
2284                     return true;
2285             }
2286             return false;
2287         }
2288         return (bool) $value;
2289     }
2290 }
2291
2292 class _UserPreference_language
2293 extends _UserPreference
2294 {
2295     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
2296         $this->_UserPreference($default);
2297     }
2298
2299     // FIXME: check for valid locale
2300     function sanify ($value) {
2301         // Revert to DEFAULT_LANGUAGE if user does not specify
2302         // language in UserPreferences or chooses <system language>.
2303         if ($value == '' or empty($value))
2304             $value = DEFAULT_LANGUAGE;
2305
2306         return (string) $value;
2307     }
2308     
2309     function update ($newvalue) {
2310         if (! $this->_init ) {
2311             // invalidate etag to force fresh output
2312             $GLOBALS['request']->setValidators(array('%mtime' => false));
2313             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
2314         }
2315     }
2316 }
2317
2318 class _UserPreference_theme
2319 extends _UserPreference
2320 {
2321     function _UserPreference_theme ($default = THEME) {
2322         $this->_UserPreference($default);
2323     }
2324
2325     function sanify ($value) {
2326         if (!empty($value) and FindFile($this->_themefile($value)))
2327             return $value;
2328         return $this->default_value;
2329     }
2330
2331     function update ($newvalue) {
2332         global $Theme;
2333         // invalidate etag to force fresh output
2334         if (! $this->_init )
2335             $GLOBALS['request']->setValidators(array('%mtime' => false));
2336         if ($newvalue)
2337             include_once($this->_themefile($newvalue));
2338         if (empty($Theme))
2339             include_once($this->_themefile(THEME));
2340     }
2341
2342     function _themefile ($theme) {
2343         return "themes/$theme/themeinfo.php";
2344     }
2345 }
2346
2347 class _UserPreference_notify
2348 extends _UserPreference
2349 {
2350     function sanify ($value) {
2351         if (!empty($value))
2352             return $value;
2353         else
2354             return $this->default_value;
2355     }
2356
2357     /** update to global user prefs: side-effect on set notify changes
2358      * use a global_data notify hash:
2359      * notify = array('pagematch' => array(userid => ('email' => mail, 
2360      *                                                'verified' => 0|1),
2361      *                                     ...),
2362      *                ...);
2363      */
2364     function update ($value) {
2365         if (!empty($this->_init)) return;
2366         $dbh = $GLOBALS['request']->getDbh();
2367         $notify = $dbh->get('notify');
2368         if (empty($notify))
2369             $data = array();
2370         else 
2371             $data = & $notify;
2372         // expand to existing pages only or store matches?
2373         // for now we store (glob-style) matches which is easier for the user
2374         $pages = $this->_page_split($value);
2375         // Limitation: only current user.
2376         $user = $GLOBALS['request']->getUser();
2377         if (!$user or !method_exists($user,'UserName')) return;
2378         // This fails with php5 and a WIKI_ID cookie:
2379         $userid = $user->UserName();
2380         $email  = $user->_prefs->get('email');
2381         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
2382         // check existing notify hash and possibly delete pages for email
2383         if (!empty($data)) {
2384             foreach ($data as $page => $users) {
2385                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
2386                     unset($data[$page][$userid]);
2387                 }
2388                 if (count($data[$page]) == 0)
2389                     unset($data[$page]);
2390             }
2391         }
2392         // add the new pages
2393         if (!empty($pages)) {
2394             foreach ($pages as $page) {
2395                 if (!isset($data[$page]))
2396                     $data[$page] = array();
2397                 if (!isset($data[$page][$userid])) {
2398                     // should we really store the verification notice here or 
2399                     // check it dynamically at every page->save?
2400                     if ($verified) {
2401                         $data[$page][$userid] = array('email' => $email,
2402                                                       'verified' => $verified);
2403                     } else {
2404                         $data[$page][$userid] = array('email' => $email);
2405                     }
2406                 }
2407             }
2408         }
2409         // store users changes
2410         $dbh->set('notify',$data);
2411     }
2412
2413     /** split the user-given comma or whitespace delimited pagenames
2414      *  to array
2415      */
2416     function _page_split($value) {
2417         return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
2418     }
2419 }
2420
2421 class _UserPreference_email
2422 extends _UserPreference
2423 {
2424     function sanify($value) {
2425         // check for valid email address
2426         if ($this->get('email') == $value and $this->getraw('emailVerified'))
2427             return $value;
2428         // hack!
2429         if ($value == 1 or $value === true)
2430             return $value;
2431         list($ok,$msg) = ValidateMail($value,'noconnect');
2432         if ($ok) {
2433             return $value;
2434         } else {
2435             trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
2436             return $this->default_value;
2437         }
2438     }
2439     
2440     /** Side-effect on email changes:
2441      * Send a verification mail or for now just a notification email.
2442      * For true verification (value = 2), we'd need a mailserver hook.
2443      */
2444     function update($value) {
2445         if (!empty($this->_init)) return;
2446         $verified = $this->getraw('emailVerified');
2447         // hack!
2448         if (($value == 1 or $value === true) and $verified)
2449             return;
2450         if (!empty($value) and !$verified) {
2451             list($ok,$msg) = ValidateMail($value);
2452             if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
2453                      sprintf(_("Welcome to %s!\nYou email account is verified and\nwill be used to send pagechange notifications.\nSee %s"),
2454                              WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true))))
2455                 $this->set('emailVerified',1);
2456         }
2457     }
2458 }
2459
2460 /** Check for valid email address
2461     fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
2462  */
2463 function ValidateMail($email, $noconnect=false) {
2464     if (!isset($_SERVER))
2465         $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
2466     $HTTP_HOST = $_SERVER['HTTP_HOST'];
2467     $result = array();
2468     // well, technically ".a.a.@host.com" is also valid
2469     if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
2470         $result[0] = false;
2471         $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"),$email);
2472         return $result;
2473     }
2474     if ($noconnect)
2475       return array(true,sprintf(_("E-Mail address '%s' is properly formatted"),$email));
2476
2477     list ( $Username, $Domain ) = split ("@",$email);
2478     //Todo: getmxrr workaround on windows or manual input field to verify it manually
2479     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. 
2480         $ConnectAddress = $MXHost[0];
2481     } else {
2482         $ConnectAddress = $Domain;
2483     }
2484     $Connect = fsockopen ( $ConnectAddress, 25 );
2485     if ($Connect) {
2486         if (ereg("^220", $Out = fgets($Connect, 1024))) {
2487             fputs ($Connect, "HELO $HTTP_HOST\r\n");
2488             $Out = fgets ( $Connect, 1024 );
2489             fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
2490             $From = fgets ( $Connect, 1024 );
2491             fputs ($Connect, "RCPT TO: <".$email.">\r\n");
2492             $To = fgets ($Connect, 1024);
2493             fputs ($Connect, "QUIT\r\n");
2494             fclose($Connect);
2495             if (!ereg ("^250", $From)) {
2496                 $result[0]=false;
2497                 $result[1]="Server rejected address: ". $From;
2498                 return $result;
2499             }
2500             if (!ereg ( "^250", $To )) {
2501                 $result[0]=false;
2502                 $result[1]="Server rejected address: ". $To;
2503                 return $result;
2504             }
2505         } else {
2506             $result[0] = false;
2507             $result[1] = "No response from server";
2508             return $result;
2509           }
2510     }  else {
2511         $result[0]=false;
2512         $result[1]="Can not connect E-Mail server.";
2513         return $result;
2514     }
2515     $result[0]=true;
2516     $result[1]="E-Mail address '$email' appears to be valid.";
2517     return $result;
2518 } // end of function 
2519
2520 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2521
2522 /**
2523  * UserPreferences
2524  * 
2525  * This object holds the $request->_prefs subobjects.
2526  * A simple packed array of non-default values get's stored as cookie,
2527  * homepage, or database, which are converted to the array of 
2528  * ->_prefs objects.
2529  * We don't store the objects, because otherwise we will
2530  * not be able to upgrade any subobject. And it's a waste of space also.
2531  *
2532  */
2533 class UserPreferences
2534 {
2535     function UserPreferences($saved_prefs = false) {
2536         // userid stored too, to ensure the prefs are being loaded for
2537         // the correct (currently signing in) userid if stored in a
2538         // cookie.
2539         // Update: for db prefs we disallow passwd. 
2540         // userid is needed for pref reflexion. current pref must know its username, 
2541         // if some app needs prefs from different users, different from current user.
2542         $this->_prefs
2543             = array(
2544                     'userid'        => new _UserPreference(''),
2545                     'passwd'        => new _UserPreference(''),
2546                     'autologin'     => new _UserPreference_bool(),
2547                     //'emailVerified' => new _UserPreference_emailVerified(), 
2548                     //fixed: store emailVerified as email parameter, 1.3.8
2549                     'email'         => new _UserPreference_email(''),
2550                     'notifyPages'   => new _UserPreference_notify(''), // 1.3.8
2551                     'theme'         => new _UserPreference_theme(THEME),
2552                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
2553                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2554                                                                EDITWIDTH_MIN_COLS,
2555                                                                EDITWIDTH_MAX_COLS),
2556                     'noLinkIcons'   => new _UserPreference_bool(),    // 1.3.8 
2557                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2558                                                                EDITHEIGHT_MIN_ROWS,
2559                                                                EDITHEIGHT_DEFAULT_ROWS),
2560                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2561                                                                    TIMEOFFSET_MIN_HOURS,
2562                                                                    TIMEOFFSET_MAX_HOURS),
2563                     'relativeDates' => new _UserPreference_bool(),
2564                     'googleLink'    => new _UserPreference_bool(), // 1.3.10
2565                     );
2566         // add custom theme-specific pref types:
2567         // FIXME: on theme changes the wiki_user session pref object will fail. 
2568         // We will silently ignore this.
2569         if (!empty($customUserPreferenceColumns))
2570             $this->_prefs = array_merge($this->_prefs,$customUserPreferenceColumns);
2571
2572         if (isset($this->_method) and $this->_method == 'SQL') {
2573             //unset($this->_prefs['userid']);
2574             unset($this->_prefs['passwd']);
2575         }
2576
2577         if (is_array($saved_prefs)) {
2578             foreach ($saved_prefs as $name => $value)
2579                 $this->set($name, $value);
2580         }
2581     }
2582
2583     function _getPref($name) {
2584         if ($name == 'emailVerified')
2585             $name = 'email';
2586         if (!isset($this->_prefs[$name])) {
2587             if ($name == 'passwd2') return false;
2588             if ($name == 'passwd') return false;
2589             trigger_error("$name: unknown preference", E_USER_NOTICE);
2590             return false;
2591         }
2592         return $this->_prefs[$name];
2593     }
2594     
2595     // get the value or default_value of the subobject
2596     function get($name) {
2597         if ($_pref = $this->_getPref($name))
2598             if ($name == 'emailVerified')
2599                 return $_pref->getraw($name);
2600             else
2601                 return $_pref->get($name);
2602         else
2603             return false;  
2604     }
2605
2606     // check and set the new value in the subobject
2607     function set($name, $value) {
2608         $pref = $this->_getPref($name);
2609         if ($pref === false)
2610             return false;
2611
2612         /* do it here or outside? */
2613         if ($name == 'passwd' and 
2614             defined('PASSWORD_LENGTH_MINIMUM') and 
2615             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2616             //TODO: How to notify the user?
2617             return false;
2618         }
2619         /*
2620         if ($name == 'theme' and $value == '')
2621            return true;
2622         */
2623         if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
2624             if ($name == 'emailVerified') $newvalue = $value;
2625             else $newvalue = $pref->sanify($value);
2626             $pref->set($name,$newvalue);
2627         }
2628         $this->_prefs[$name] =& $pref;
2629         return true;
2630     }
2631     /**
2632      * use init to avoid update on set
2633      */
2634     function updatePrefs($prefs, $init = false) {
2635         $count = 0;
2636         if ($init) $this->_init = $init;
2637         if (is_object($prefs)) {
2638             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2639             $obj->_init = $init;
2640             if ($obj->get($type) !== $prefs->get($type)) {
2641                 if ($obj->set($type,$prefs->get($type)))
2642                     $count++;
2643             }
2644             foreach (array_keys($this->_prefs) as $type) {
2645                 $obj =& $this->_prefs[$type];
2646                 $obj->_init = $init;
2647                 if ($prefs->get($type) !== $obj->get($type)) {
2648                     // special systemdefault prefs: (probably not needed)
2649                     if ($type == 'theme' and $prefs->get($type) == '' and $obj->get($type) == THEME) continue;
2650                     if ($type == 'lang' and $prefs->get($type) == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue;
2651                     if ($this->_prefs[$type]->set($type,$prefs->get($type)))
2652                         $count++;
2653                 }
2654             }
2655         } elseif (is_array($prefs)) {
2656             //unset($this->_prefs['userid']);
2657             if (isset($this->_method) and 
2658                  ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2659                 unset($this->_prefs['passwd']);
2660             }
2661             // emailVerified at first, the rest later
2662             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2663             $obj->_init = $init;
2664             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2665                 if ($obj->set($type,$prefs[$type]))
2666                     $count++;
2667             }
2668             foreach (array_keys($this->_prefs) as $type) {
2669                 $obj =& $this->_prefs[$type];
2670                 $obj->_init = $init;
2671                 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool")) 
2672                     $prefs[$type] = false;
2673                 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2674                     $prefs[$type] = (int) $prefs[$type];
2675                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2676                     // special systemdefault prefs:
2677                     if ($type == 'theme' and $prefs[$type] == '' and $obj->get($type) == THEME) continue;
2678                     if ($type == 'lang' and $prefs[$type] == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue;
2679                     if ($obj->set($type,$prefs[$type]))
2680                         $count++;
2681                 }
2682             }
2683         }
2684         return $count;
2685     }
2686
2687     // for now convert just array of objects => array of values
2688     // Todo: the specialized subobjects must override this.
2689     function store() {
2690         $prefs = array();
2691         foreach ($this->_prefs as $name => $object) {
2692             if ($value = $object->getraw($name))
2693                 $prefs[$name] = $value;
2694             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2695                 $prefs['emailVerified'] = $value;
2696         }
2697         return $this->pack($prefs);
2698     }
2699
2700     // packed string or array of values => array of values
2701     // Todo: the specialized subobjects must override this.
2702     function retrieve($packed) {
2703         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2704             $packed = unserialize($packed);
2705         if (!is_array($packed)) return false;
2706         $prefs = array();
2707         foreach ($packed as $name => $packed_pref) {
2708             if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2709                 //legacy: check if it's an old array of objects
2710                 // Looks like a serialized object. 
2711                 // This might fail if the object definition does not exist anymore.
2712                 // object with ->$name and ->default_value vars.
2713                 $pref =  @unserialize($packed_pref);
2714                 if (empty($pref))
2715                     $pref = @unserialize(base64_decode($packed_pref));
2716                 $prefs[$name] = $pref->get($name);
2717             // fix old-style prefs
2718             } elseif (is_numeric($name) and is_array($packed_pref)) {
2719                 if (count($packed_pref) == 1) {
2720                     list($name,$value) = each($packed_pref);
2721                     $prefs[$name] = $value;
2722                 }
2723             } else {
2724                 $prefs[$name] = @unserialize($packed_pref);
2725                 if (empty($prefs[$name]))
2726                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
2727                 // patched by frederik@pandora.be
2728                 if (empty($prefs[$name]))
2729                     $prefs[$name] = $packed_pref;
2730             }
2731         }
2732         return $prefs;
2733     }
2734
2735     /**
2736      * Check if the given prefs object is different from the current prefs object
2737      */
2738     function isChanged($other) {
2739         foreach ($this->_prefs as $type => $obj) {
2740             if ($obj->get($type) !== $other->get($type))
2741                 return true;
2742         }
2743         return false;
2744     }
2745
2746     function defaultPreferences() {
2747         $prefs = array();
2748         foreach ($this->_prefs as $key => $obj) {
2749             $prefs[$key] = $obj->default_value;
2750         }
2751         return $prefs;
2752     }
2753     
2754     // array of objects
2755     function getAll() {
2756         return $this->_prefs;
2757     }
2758
2759     function pack($nonpacked) {
2760         return serialize($nonpacked);
2761     }
2762
2763     function unpack($packed) {
2764         if (!$packed)
2765             return false;
2766         //$packed = base64_decode($packed);
2767         if (substr($packed, 0, 2) == "O:") {
2768             // Looks like a serialized object
2769             return unserialize($packed);
2770         }
2771         if (substr($packed, 0, 2) == "a:") {
2772             return unserialize($packed);
2773         }
2774         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2775         //E_USER_WARNING);
2776         return false;
2777     }
2778
2779     function hash () {
2780         return hash($this->_prefs);
2781     }
2782 }
2783
2784 /** TODO: new pref storage classes
2785  *  These are currently user specific and should be rewritten to be pref specific.
2786  *  i.e. $this == $user->_prefs
2787  */
2788 class CookieUserPreferences
2789 extends UserPreferences
2790 {
2791     function CookieUserPreferences ($saved_prefs = false) {
2792         //_AnonUser::_AnonUser('',$saved_prefs);
2793         UserPreferences::UserPreferences($saved_prefs);
2794     }
2795 }
2796
2797 class PageUserPreferences
2798 extends UserPreferences
2799 {
2800     function PageUserPreferences ($saved_prefs = false) {
2801         UserPreferences::UserPreferences($saved_prefs);
2802     }
2803 }
2804
2805 class PearDbUserPreferences
2806 extends UserPreferences
2807 {
2808     function PearDbUserPreferences ($saved_prefs = false) {
2809         UserPreferences::UserPreferences($saved_prefs);
2810     }
2811 }
2812
2813 class AdoDbUserPreferences
2814 extends UserPreferences
2815 {
2816     function AdoDbUserPreferences ($saved_prefs = false) {
2817         UserPreferences::UserPreferences($saved_prefs);
2818     }
2819     function getPreferences() {
2820         // override the generic slow method here for efficiency
2821         _AnonUser::getPreferences();
2822         $this->getAuthDbh();
2823         if (isset($this->_select)) {
2824             $dbh = & $this->_auth_dbi;
2825             $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2826             if ($rs->EOF) {
2827                 $rs->Close();
2828             } else {
2829                 $prefs_blob = $rs->fields['pref_blob'];
2830                 $rs->Close();
2831                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2832                     $updated = $this->_prefs->updatePrefs($restored_from_db);
2833                     //$this->_prefs = new UserPreferences($restored_from_db);
2834                     return $this->_prefs;
2835                 }
2836             }
2837         }
2838         if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2839             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2840                 $updated = $this->_prefs->updatePrefs($restored_from_page);
2841                 //$this->_prefs = new UserPreferences($restored_from_page);
2842                 return $this->_prefs;
2843             }
2844         }
2845         return $this->_prefs;
2846     }
2847 }
2848
2849
2850 // $Log: not supported by cvs2svn $
2851 // Revision 1.74  2004/05/15 19:48:33  rurban
2852 // fix some too loose PagePerms for signed, but not authenticated users
2853 //  (admin, owner, creator)
2854 // no double login page header, better login msg.
2855 // moved action_pdf to lib/pdf.php
2856 //
2857 // Revision 1.73  2004/05/15 18:31:01  rurban
2858 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
2859 //
2860 // Revision 1.72  2004/05/12 10:49:55  rurban
2861 // require_once fix for those libs which are loaded before FileFinder and
2862 //   its automatic include_path fix, and where require_once doesn't grok
2863 //   dirname(__FILE__) != './lib'
2864 // upgrade fix with PearDB
2865 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2866 //
2867 // Revision 1.71  2004/05/10 12:34:47  rurban
2868 // stabilize DbAuthParam statement pre-prozessor:
2869 //   try old-style and new-style (double-)quoting
2870 //   reject unknown $variables
2871 //   use ->prepare() for all calls (again)
2872 //
2873 // Revision 1.70  2004/05/06 19:26:16  rurban
2874 // improve stability, trying to find the InlineParser endless loop on sf.net
2875 //
2876 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
2877 //
2878 // Revision 1.69  2004/05/06 13:56:40  rurban
2879 // Enable the Administrators group, and add the WIKIPAGE group default root page.
2880 //
2881 // Revision 1.68  2004/05/05 13:37:54  rurban
2882 // Support to remove all UserPreferences
2883 //
2884 // Revision 1.66  2004/05/03 21:44:24  rurban
2885 // fixed sf,net bug #947264: LDAP options are constants, not strings!
2886 //
2887 // Revision 1.65  2004/05/03 13:16:47  rurban
2888 // fixed UserPreferences update, esp for boolean and int
2889 //
2890 // Revision 1.64  2004/05/02 15:10:06  rurban
2891 // new finally reliable way to detect if /index.php is called directly
2892 //   and if to include lib/main.php
2893 // new global AllActionPages
2894 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
2895 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
2896 // PageGroupTestOne => subpages
2897 // renamed PhpWikiRss to PhpWikiRecentChanges
2898 // more docs, default configs, ...
2899 //
2900 // Revision 1.63  2004/05/01 15:59:29  rurban
2901 // more php-4.0.6 compatibility: superglobals
2902 //
2903 // Revision 1.62  2004/04/29 18:31:24  rurban
2904 // Prevent from warning where no db pref was previously stored.
2905 //
2906 // Revision 1.61  2004/04/29 17:18:19  zorloc
2907 // 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.
2908 //
2909 // Revision 1.60  2004/04/27 18:20:54  rurban
2910 // sf.net patch #940359 by rassie
2911 //
2912 // Revision 1.59  2004/04/26 12:35:21  rurban
2913 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
2914 // File_Passwd is already loaded
2915 //
2916 // Revision 1.58  2004/04/20 17:08:28  rurban
2917 // Some IniConfig fixes: prepend our private lib/pear dir
2918 //   switch from " to ' in the auth statements
2919 //   use error handling.
2920 // WikiUserNew changes for the new "'$variable'" syntax
2921 //   in the statements
2922 // TODO: optimization to put config vars into the session.
2923 //
2924 // Revision 1.57  2004/04/19 18:27:45  rurban
2925 // Prevent from some PHP5 warnings (ref args, no :: object init)
2926 //   php5 runs now through, just one wrong XmlElement object init missing
2927 // Removed unneccesary UpgradeUser lines
2928 // Changed WikiLink to omit version if current (RecentChanges)
2929 //
2930 // Revision 1.56  2004/04/19 09:13:24  rurban
2931 // new pref: googleLink
2932 //
2933 // Revision 1.54  2004/04/18 00:24:45  rurban
2934 // re-use our simple prepare: just for table prefix warnings
2935 //
2936 // Revision 1.53  2004/04/12 18:29:15  rurban
2937 // exp. Session auth for already authenticated users from another app
2938 //
2939 // Revision 1.52  2004/04/12 13:04:50  rurban
2940 // added auth_create: self-registering Db users
2941 // fixed IMAP auth
2942 // removed rating recommendations
2943 // ziplib reformatting
2944 //
2945 // Revision 1.51  2004/04/11 10:42:02  rurban
2946 // pgsrc/CreatePagePlugin
2947 //
2948 // Revision 1.50  2004/04/10 05:34:35  rurban
2949 // sf bug#830912
2950 //
2951 // Revision 1.49  2004/04/07 23:13:18  rurban
2952 // fixed pear/File_Passwd for Windows
2953 // fixed FilePassUser sessions (filehandle revive) and password update
2954 //
2955 // Revision 1.48  2004/04/06 20:00:10  rurban
2956 // Cleanup of special PageList column types
2957 // Added support of plugin and theme specific Pagelist Types
2958 // Added support for theme specific UserPreferences
2959 // Added session support for ip-based throttling
2960 //   sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
2961 // Enhanced postgres schema
2962 // Added DB_Session_dba support
2963 //
2964 // Revision 1.47  2004/04/02 15:06:55  rurban
2965 // fixed a nasty ADODB_mysql session update bug
2966 // improved UserPreferences layout (tabled hints)
2967 // fixed UserPreferences auth handling
2968 // improved auth stability
2969 // improved old cookie handling: fixed deletion of old cookies with paths
2970 //
2971 // Revision 1.46  2004/04/01 06:29:51  rurban
2972 // better wording
2973 // RateIt also for ADODB
2974 //
2975 // Revision 1.45  2004/03/30 02:14:03  rurban
2976 // fixed yet another Prefs bug
2977 // added generic PearDb_iter
2978 // $request->appendValidators no so strict as before
2979 // added some box plugin methods
2980 // PageList commalist for condensed output
2981 //
2982 // Revision 1.44  2004/03/27 22:01:03  rurban
2983 // two catches by Konstantin Zadorozhny
2984 //
2985 // Revision 1.43  2004/03/27 19:40:09  rurban
2986 // init fix and validator reset
2987 //
2988 // Revision 1.40  2004/03/25 22:54:31  rurban
2989 // fixed HttpAuth
2990 //
2991 // Revision 1.38  2004/03/25 17:37:36  rurban
2992 // helper to patch to and from php5 (workaround for stricter parser, no macros in php)
2993 //
2994 // Revision 1.37  2004/03/25 17:00:31  rurban
2995 // more code to convert old-style pref array to new hash
2996 //
2997 // Revision 1.36  2004/03/24 19:39:02  rurban
2998 // php5 workaround code (plus some interim debugging code in XmlElement)
2999 //   php5 doesn't work yet with the current XmlElement class constructors,
3000 //   WikiUserNew does work better than php4.
3001 // rewrote WikiUserNew user upgrading to ease php5 update
3002 // fixed pref handling in WikiUserNew
3003 // added Email Notification
3004 // added simple Email verification
3005 // removed emailVerify userpref subclass: just a email property
3006 // changed pref binary storage layout: numarray => hash of non default values
3007 // print optimize message only if really done.
3008 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
3009 //   prefs should be stored in db or homepage, besides the current session.
3010 //
3011 // Revision 1.35  2004/03/18 22:18:31  rurban
3012 // workaround for php5 object upgrading problem
3013 //
3014 // Revision 1.34  2004/03/18 21:41:09  rurban
3015 // fixed sqlite support
3016 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
3017 //
3018 // Revision 1.33  2004/03/16 15:42:04  rurban
3019 // more fixes for undefined property warnings
3020 //
3021 // Revision 1.32  2004/03/14 16:30:52  rurban
3022 // db-handle session revivification, dba fixes
3023 //
3024 // Revision 1.31  2004/03/12 23:20:58  rurban
3025 // pref fixes (base64)
3026 //
3027 // Revision 1.30  2004/03/12 20:59:17  rurban
3028 // important cookie fix by Konstantin Zadorozhny
3029 // new editpage feature: JS_SEARCHREPLACE
3030 //
3031 // Revision 1.29  2004/03/11 13:30:47  rurban
3032 // fixed File Auth for user and group
3033 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
3034 //
3035 // Revision 1.28  2004/03/08 18:17:09  rurban
3036 // added more WikiGroup::getMembersOf methods, esp. for special groups
3037 // fixed $LDAP_SET_OPTIONS
3038 // fixed _AuthInfo group methods
3039 //
3040 // Revision 1.27  2004/03/01 09:35:13  rurban
3041 // fixed DbPassuser pref init; lost userid
3042 //
3043 // Revision 1.26  2004/02/29 04:10:56  rurban
3044 // new POP3 auth (thanks to BiloBilo: pentothal at despammed dot com)
3045 // fixed syntax error in index.php
3046 //
3047 // Revision 1.25  2004/02/28 22:25:07  rurban
3048 // First PagePerm implementation:
3049 //
3050 // $Theme->setAnonEditUnknownLinks(false);
3051 //
3052 // Layout improvement with dangling links for mostly closed wiki's:
3053 // If false, only users with edit permissions will be presented the
3054 // special wikiunknown class with "?" and Tooltip.
3055 // If true (default), any user will see the ?, but will be presented
3056 // the PrintLoginForm on a click.
3057 //
3058 // Revision 1.24  2004/02/28 21:14:08  rurban
3059 // generally more PHPDOC docs
3060 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
3061 // fxied WikiUserNew pref handling: empty theme not stored, save only
3062 //   changed prefs, sql prefs improved, fixed password update,
3063 //   removed REPLACE sql (dangerous)
3064 // moved gettext init after the locale was guessed
3065 // + some minor changes
3066 //
3067 // Revision 1.23  2004/02/27 13:21:17  rurban
3068 // several performance improvements, esp. with peardb
3069 // simplified loops
3070 // storepass seperated from prefs if defined so
3071 // stacked and strict still not working
3072 //
3073 // Revision 1.22  2004/02/27 05:15:40  rurban
3074 // more stability. detected by Micki
3075 //
3076 // Revision 1.21  2004/02/26 20:43:49  rurban
3077 // new HttpAuthPassUser class (forces http auth if in the auth loop)
3078 // fixed user upgrade: don't return _PassUser in the first hand.
3079 //
3080 // Revision 1.20  2004/02/26 01:29:11  rurban
3081 // important fixes: endless loops in certain cases. minor rewrite
3082 //
3083 // Revision 1.19  2004/02/25 17:15:17  rurban
3084 // improve stability
3085 //
3086 // Revision 1.18  2004/02/24 15:20:05  rurban
3087 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
3088 //
3089 // Revision 1.17  2004/02/17 12:16:42  rurban
3090 // started with changePass support. not yet used.
3091 //
3092 // Revision 1.16  2004/02/15 22:23:45  rurban
3093 // oops, fixed showstopper (endless recursion)
3094 //
3095 // Revision 1.15  2004/02/15 21:34:37  rurban
3096 // PageList enhanced and improved.
3097 // fixed new WikiAdmin... plugins
3098 // editpage, Theme with exp. htmlarea framework
3099 //   (htmlarea yet committed, this is really questionable)
3100 // WikiUser... code with better session handling for prefs
3101 // enhanced UserPreferences (again)
3102 // RecentChanges for show_deleted: how should pages be deleted then?
3103 //
3104 // Revision 1.14  2004/02/15 17:30:13  rurban
3105 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
3106 // fixed getPreferences() (esp. from sessions)
3107 // fixed setPreferences() (update and set),
3108 // fixed AdoDb DB statements,
3109 // update prefs only at UserPreferences POST (for testing)
3110 // unified db prefs methods (but in external pref classes yet)
3111 //
3112 // Revision 1.13  2004/02/09 03:58:12  rurban
3113 // for now default DB_SESSION to false
3114 // PagePerm:
3115 //   * not existing perms will now query the parent, and not
3116 //     return the default perm
3117 //   * added pagePermissions func which returns the object per page
3118 //   * added getAccessDescription
3119 // WikiUserNew:
3120 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
3121 //   * force init of authdbh in the 2 db classes
3122 // main:
3123 //   * fixed session handling (not triple auth request anymore)
3124 //   * don't store cookie prefs with sessions
3125 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
3126 //
3127 // Revision 1.12  2004/02/07 10:41:25  rurban
3128 // fixed auth from session (still double code but works)
3129 // fixed GroupDB
3130 // fixed DbPassUser upgrade and policy=old
3131 // added GroupLdap
3132 //
3133 // Revision 1.11  2004/02/03 09:45:39  rurban
3134 // LDAP cleanup, start of new Pref classes
3135 //
3136 // Revision 1.10  2004/02/01 09:14:11  rurban
3137 // Started with Group_Ldap (not yet ready)
3138 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
3139 // fixed some configurator vars
3140 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
3141 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
3142 // USE_DB_SESSION defaults to true on SQL
3143 // changed GROUP_METHOD definition to string, not constants
3144 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
3145 //   create users. (Not to be used with external databases generally, but
3146 //   with the default internal user table)
3147 //
3148 // fixed the IndexAsConfigProblem logic. this was flawed:
3149 //   scripts which are the same virtual path defined their own lib/main call
3150 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
3151 //
3152 // Revision 1.9  2004/01/30 19:57:58  rurban
3153 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
3154 //
3155 // Revision 1.8  2004/01/30 18:46:15  rurban
3156 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
3157 //
3158 // Revision 1.7  2004/01/27 23:23:39  rurban
3159 // renamed ->Username => _userid for consistency
3160 // renamed mayCheckPassword => mayCheckPass
3161 // fixed recursion problem in WikiUserNew
3162 // fixed bogo login (but not quite 100% ready yet, password storage)
3163 //
3164 // Revision 1.6  2004/01/26 09:17:49  rurban
3165 // * changed stored pref representation as before.
3166 //   the array of objects is 1) bigger and 2)
3167 //   less portable. If we would import packed pref
3168 //   objects and the object definition was changed, PHP would fail.
3169 //   This doesn't happen with an simple array of non-default values.
3170 // * use $prefs->retrieve and $prefs->store methods, where retrieve
3171 //   understands the interim format of array of objects also.
3172 // * simplified $prefs->get() and fixed $prefs->set()
3173 // * added $user->_userid and class '_WikiUser' portability functions
3174 // * fixed $user object ->_level upgrading, mostly using sessions.
3175 //   this fixes yesterdays problems with loosing authorization level.
3176 // * fixed WikiUserNew::checkPass to return the _level
3177 // * fixed WikiUserNew::isSignedIn
3178 // * added explodePageList to class PageList, support sortby arg
3179 // * fixed UserPreferences for WikiUserNew
3180 // * fixed WikiPlugin for empty defaults array
3181 // * UnfoldSubpages: added pagename arg, renamed pages arg,
3182 //   removed sort arg, support sortby arg
3183 //
3184 // Revision 1.5  2004/01/25 03:05:00  rurban
3185 // First working version, but has some problems with the current main loop.
3186 // Implemented new auth method dispatcher and policies, all the external
3187 // _PassUser classes (also for ADODB and Pear DB).
3188 // The two global funcs UserExists() and CheckPass() are probably not needed,
3189 // since the auth loop is done recursively inside the class code, upgrading
3190 // the user class within itself.
3191 // Note: When a higher user class is returned, this doesn't mean that the user
3192 // is authorized, $user->_level is still low, and only upgraded on successful
3193 // login.
3194 //
3195 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
3196 // Code Housecleaning: fixed syntax errors. (php -l *.php)
3197 //
3198 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
3199 // Finished off logic for determining user class, including
3200 // PassUser. Removed ability of BogoUser to save prefs into a page.
3201 //
3202 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
3203 // Added admin user, password user, and preference classes. Added
3204 // password checking functions for users and the admin. (Now the easy
3205 // parts are nearly done).
3206 //
3207 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
3208 // Complete rewrite of WikiUser.php.
3209 //
3210 // This should make it easier to hook in user permission groups etc. some
3211 // time in the future. Most importantly, to finally get UserPreferences
3212 // fully working properly for all classes of users: AnonUser, BogoUser,
3213 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
3214 // want a cookie or not, and to bring back optional AutoLogin with the
3215 // UserName stored in a cookie--something that was lost after PhpWiki had
3216 // dropped the default http auth login method.
3217 //
3218 // Added WikiUser classes which will (almost) work together with existing
3219 // UserPreferences class. Other parts of PhpWiki need to be updated yet
3220 // before this code can be hooked up.
3221 //
3222
3223 // Local Variables:
3224 // mode: php
3225 // tab-width: 8
3226 // c-basic-offset: 4
3227 // c-hanging-comment-ender-p: nil
3228 // indent-tabs-mode: nil
3229 // End:
3230 ?>