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