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