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