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