]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
silence AdminUser HomePagehandle warning
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.143 2007-05-24 18:37:53 rurban Exp $');
3 /* Copyright (C) 2004,2005,2006,2007 $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 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
105 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
106 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
107
108 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
109 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
110 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
111
112 define('TIMEOFFSET_MIN_HOURS', -26);
113 define('TIMEOFFSET_MAX_HOURS',  26);
114 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
115
116 /* EMAIL VERIFICATION
117  * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
118  * Provide some overrides here.
119  *    ( username @ ) domain => mail-domain
120  */
121 $EMailHosts = array('avl.com' => 'mail.avl.com');
122
123 /**
124  * There are be the following constants in config/config.ini to 
125  * establish login parameters:
126  *
127  * ALLOW_ANON_USER         default true
128  * ALLOW_ANON_EDIT         default true
129  * ALLOW_BOGO_LOGIN        default true
130  * ALLOW_USER_PASSWORDS    default true
131  * PASSWORD_LENGTH_MINIMUM default 0
132  *
133  * To require user passwords for editing:
134  * ALLOW_ANON_USER  = true
135  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
136  * ALLOW_BOGO_LOGIN = false
137  * ALLOW_USER_PASSWORDS = true
138  *
139  * To establish a COMPLETELY private wiki, such as an internal
140  * corporate one:
141  * ALLOW_ANON_USER = false
142  * (and probably require user passwords as described above). In this
143  * case the user will be prompted to login immediately upon accessing
144  * any page.
145  *
146  * There are other possible combinations, but the typical wiki (such
147  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four 
148  * enabled.
149  *
150  */
151
152 // The last object in the row is the bad guy...
153 if (!is_array($USER_AUTH_ORDER))
154     $USER_AUTH_ORDER = array("Forbidden");
155 else
156     $USER_AUTH_ORDER[] = "Forbidden";
157
158 // Local convenience functions.
159 function _isAnonUserAllowed() {
160     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
161 }
162 function _isBogoUserAllowed() {
163     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
164 }
165 function _isUserPasswordsAllowed() {
166     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
167 }
168
169 // Possibly upgrade userobject functions.
170 function _determineAdminUserOrOtherUser($UserName) {
171     // Sanity check. User name is a condition of the definition of the
172     // _AdminUser, _BogoUser and _passuser.
173     if (!$UserName)
174         return $GLOBALS['ForbiddenUser'];
175
176     //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
177     //$group = &WikiGroup::getGroup($GLOBALS['request']);
178     if ($UserName == ADMIN_USER)
179         return new _AdminUser($UserName);
180     /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
181         return _determineBogoUserOrPassUser($UserName);
182     }
183     */
184     else
185         return _determineBogoUserOrPassUser($UserName);
186 }
187
188 function _determineBogoUserOrPassUser($UserName) {
189     global $ForbiddenUser;
190
191     // Sanity check. User name is a condition of the definition of
192     // _BogoUser and _PassUser.
193     if (!$UserName)
194         return $ForbiddenUser;
195
196     // Check for password and possibly upgrade user object.
197     // $_BogoUser = new _BogoUser($UserName);
198     if (_isBogoUserAllowed() and isWikiWord($UserName)) {
199         include_once("lib/WikiUser/BogoLogin.php");
200         $_BogoUser = new _BogoLoginPassUser($UserName);
201         if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
202             return $_BogoUser;
203     }
204     if (_isUserPasswordsAllowed()) {
205         // PassUsers override BogoUsers if a password is stored
206         if (isset($_BogoUser) and isset($_BogoUser->_prefs) 
207             and $_BogoUser->_prefs->get('passwd'))
208             return new _PassUser($UserName, $_BogoUser->_prefs);
209         else { 
210             $_PassUser = new _PassUser($UserName,
211                                        isset($_BogoUser) ? $_BogoUser->_prefs : false);
212             if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
213                 if (isset($GLOBALS['request']->_user_class))
214                     $class = $GLOBALS['request']->_user_class;
215                 elseif (strtolower(get_class($_PassUser)) == "_passuser")
216                     $class = $_PassUser->nextClass();
217                 else
218                     $class = get_class($_PassUser);
219                 if ($user = new $class($UserName, $_PassUser->_prefs)) {
220                     return $user;
221                 } else {
222                     return $_PassUser;
223                 }
224             }
225         }
226     }
227     // No Bogo- or PassUser exists, or
228     // passwords are not allowed, and bogo is disallowed too.
229     // (Only the admin can sign in).
230     return $ForbiddenUser;
231 }
232
233 /**
234  * Primary WikiUser function, called by lib/main.php.
235  * 
236  * This determines the user's type and returns an appropriate user
237  * object. lib/main.php then querys the resultant object for password
238  * validity as necessary.
239  *
240  * If an _AnonUser object is returned, the user may only browse pages
241  * (and save prefs in a cookie).
242  *
243  * To disable access but provide prefs the global $ForbiddenUser class 
244  * is returned. (was previously false)
245  * 
246  */
247 function WikiUser ($UserName = '') {
248     global $ForbiddenUser, $HTTP_SESSION_VARS;
249
250     //Maybe: Check sessionvar for username & save username into
251     //sessionvar (may be more appropriate to do this in lib/main.php).
252     if ($UserName) {
253         $ForbiddenUser = new _ForbiddenUser($UserName);
254         // Found a user name.
255         return _determineAdminUserOrOtherUser($UserName);
256     }
257     elseif (!empty($HTTP_SESSION_VARS['userid'])) {
258         // Found a user name.
259         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
260         return _determineAdminUserOrOtherUser($_SESSION['userid']);
261     }
262     else {
263         // Check for autologin pref in cookie and possibly upgrade
264         // user object to another type.
265         $_AnonUser = new _AnonUser();
266         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
267             // Found a user name.
268             $ForbiddenUser = new _ForbiddenUser($UserName);
269             return _determineAdminUserOrOtherUser($UserName);
270         }
271         else {
272             $ForbiddenUser = new _ForbiddenUser();
273             if (_isAnonUserAllowed())
274                 return $_AnonUser;
275             return $ForbiddenUser; // User must sign in to browse pages.
276         }
277         return $ForbiddenUser;     // User must sign in with a password.
278     }
279     /*
280     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
281                   . "Unexpectedly, an appropriate user class could not be determined.");
282     return $ForbiddenUser; // Failsafe.
283     */
284 }
285
286 /**
287  * WikiUser.php use the name 'WikiUser'
288  */
289 function WikiUserClassname() {
290     return '_WikiUser';
291 }
292
293
294 /**
295  * Upgrade olduser by copying properties from user to olduser.
296  * We are not sure yet, for which php's a simple $this = $user works reliably,
297  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
298  * that's why try it the hard way.
299  */
300 function UpgradeUser ($user, $newuser) {
301     if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) {
302         // populate the upgraded class $newuser with the values from the current user object
303         //only _auth_level, _current_method, _current_index,
304         if (!empty($user->_level) and 
305             $user->_level > $newuser->_level)
306             $newuser->_level = $user->_level;
307         if (!empty($user->_current_index) and
308             $user->_current_index > $newuser->_current_index) {
309             $newuser->_current_index = $user->_current_index;
310             $newuser->_current_method = $user->_current_method;
311         }
312         if (!empty($user->_authmethod))
313             $newuser->_authmethod = $user->_authmethod;
314         $GLOBALS['request']->_user_class = get_class($newuser);
315         /*
316         foreach (get_object_vars($user) as $k => $v) {
317             if (!empty($v)) $olduser->$k = $v;  
318         }
319         */
320         $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
321         //$GLOBALS['request']->_user = $olduser;
322         return $newuser;
323     } else {
324         return false;
325     }
326 }
327
328 /**
329  * Probably not needed, since we use the various user objects methods so far.
330  * Anyway, here it is, looping through all available objects.
331  */
332 function UserExists ($UserName) {
333     global $request;
334     if (!($user = $request->getUser()))
335         $user = WikiUser($UserName);
336     if (!$user) 
337         return false;
338     if ($user->userExists($UserName)) {
339         $request->_user = $user;
340         return true;
341     }
342     if (isa($user,'_BogoUser'))
343         $user = new _PassUser($UserName,$user->_prefs);
344     $class = $user->nextClass();
345     if ($user = new $class($UserName, $user->_prefs)) {
346         return $user->userExists($UserName);
347     }
348     $request->_user = $GLOBALS['ForbiddenUser'];
349     return false;
350 }
351
352 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
353
354 /** 
355  * Base WikiUser class.
356  */
357 class _WikiUser
358 {
359      var $_userid = '';
360      var $_level = WIKIAUTH_ANON;
361      var $_prefs = false;
362      var $_HomePagehandle = false;
363
364     // constructor
365     function _WikiUser($UserName='', $prefs=false) {
366
367         $this->_userid = $UserName;
368         $this->_HomePagehandle = false;
369         if ($UserName) {
370             $this->hasHomePage();
371         }
372         if (empty($this->_prefs)) {
373             if ($prefs) $this->_prefs = $prefs;
374             else $this->getPreferences();
375         }
376     }
377
378     function UserName() {
379         if (!empty($this->_userid))
380             return $this->_userid;
381     }
382
383     function getPreferences() {
384         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
385                       . "New subclasses of _WikiUser must override this function.");
386         return false;
387     }
388
389     function setPreferences($prefs, $id_only) {
390         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." 
391                       . " "
392                       . "New subclasses of _WikiUser must override this function.");
393         return false;
394     }
395
396     function userExists() {
397         return $this->hasHomePage();
398     }
399
400     function checkPass($submitted_password) {
401         // By definition, an undefined user class cannot sign in.
402         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." 
403                       . " "
404                       . "New subclasses of _WikiUser must override this function.");
405         return false;
406     }
407
408     // returns page_handle to user's home page or false if none
409     function hasHomePage() {
410         if ($this->_userid) {
411             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
412                 return $this->_HomePagehandle->exists();
413             }
414             else {
415                 // check db again (maybe someone else created it since
416                 // we logged in.)
417                 global $request;
418                 $this->_HomePagehandle = $request->getPage($this->_userid);
419                 return $this->_HomePagehandle->exists();
420             }
421         }
422         // nope
423         return false;
424     }
425
426     // 
427     function createHomePage() {
428         global $request;
429         $versiondata = array('author' => _("The PhpWiki programming team"));
430         $request->_dbi->save("Automatically created users homepage to be able to store UserPreferences.",
431                              1, $versiondata);
432         $request->_dbi->touch();                             
433         $this->_HomePagehandle = $request->getPage($this->_userid);
434     }
435     
436     // innocent helper: case-insensitive position in _auth_methods
437     function array_position ($string, $array) {
438         $string = strtolower($string);
439         for ($found = 0; $found < count($array); $found++) {
440             if (strtolower($array[$found]) == $string)
441                 return $found;
442         }
443         return false;
444     }
445
446     function nextAuthMethodIndex() {
447         if (empty($this->_auth_methods)) 
448             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
449         if (empty($this->_current_index)) {
450             if (strtolower(get_class($this)) != '_passuser') {
451                 $this->_current_method = substr(get_class($this),1,-8);
452                 $this->_current_index = $this->array_position($this->_current_method,
453                                                               $this->_auth_methods);
454             } else {
455                 $this->_current_index = -1;
456             }
457         }
458         $this->_current_index++;
459         if ($this->_current_index >= count($this->_auth_methods))
460             return false;
461         $this->_current_method = $this->_auth_methods[$this->_current_index];
462         return $this->_current_index;
463     }
464
465     function AuthMethod($index = false) {
466         return $this->_auth_methods[ $index === false 
467                                      ? count($this->_auth_methods)-1 
468                                      : $index];
469     }
470
471     // upgrade the user object
472     function nextClass() {
473         $method = $this->AuthMethod($this->nextAuthMethodIndex());
474         include_once("lib/WikiUser/$method.php");
475         return "_".$method."PassUser";
476     }
477
478     //Fixme: for _HttpAuthPassUser
479     function PrintLoginForm (&$request, $args, $fail_message = false,
480                              $seperate_page = false) {
481         include_once('lib/Template.php');
482         // Call update_locale in case the system's default language is not 'en'.
483         // (We have no user pref for lang at this point yet, no one is logged in.)
484         if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
485             update_locale(DEFAULT_LANGUAGE);
486         $userid = $this->_userid;
487         $require_level = 0;
488         extract($args); // fixme
489
490         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
491
492         $pagename = $request->getArg('pagename');
493         $nocache = 1;
494         $login = Template('login',
495                           compact('pagename', 'userid', 'require_level',
496                                   'fail_message', 'pass_required', 'nocache'));
497         // check if the html template was already processed
498         $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
499         if ($seperate_page) {
500             $page = $request->getPage($pagename);
501             $revision = $page->getCurrentRevision();
502             return GeneratePage($login,_("Sign In"), $revision);
503         } else {
504             return $login->printExpansion();
505         }
506     }
507
508     /** Signed in but not password checked or empty password.
509      */
510     function isSignedIn() {
511         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
512     }
513
514     /** This is password checked for sure.
515      */
516     function isAuthenticated() {
517         //return isa($this,'_PassUser');
518         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
519         return $this->_level >= WIKIAUTH_BOGO;
520     }
521
522     function isAdmin () {
523         static $group; 
524         if ($this->_level == WIKIAUTH_ADMIN) return true;
525         if (!$this->isSignedIn()) return false;
526         if (!$this->isAuthenticated()) return false;
527
528         if (!$group) $group = &$GLOBALS['request']->getGroup();
529         return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
530     }
531
532     /** Name or IP for a signed user. UserName could come from a cookie e.g.
533      */
534     function getId () {
535         return ( $this->UserName()
536                  ? $this->UserName()
537                  : $GLOBALS['request']->get('REMOTE_ADDR') );
538     }
539
540     /** Name for an authenticated user. No IP here.
541      */
542     function getAuthenticatedId() {
543         return ( $this->isAuthenticated()
544                  ? $this->_userid
545                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
546     }
547
548     function hasAuthority ($require_level) {
549         return $this->_level >= $require_level;
550     }
551
552     /* This is quite restrictive and not according the login description online. 
553        Any word char (A-Za-z0-9_), ".", "@" and "-"
554        The backends may loosen this.
555     */
556     function isValidName ($userid = false) {
557         if (!$userid) $userid = $this->_userid;
558         return preg_match("/^[\w\.@\-]+$/", $userid) and strlen($userid) < 32;
559     }
560
561     /**
562      * Called on an auth_args POST request, such as login, logout or signin.
563      * TODO: Check BogoLogin users with empty password. (self-signed users)
564      */
565     function AuthCheck ($postargs) {
566         // Normalize args, and extract.
567         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
568                       'cancel');
569         foreach ($keys as $key)
570             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
571         extract($args);
572         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
573
574         if ($logout) { // Log out
575             if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
576                 $GLOBALS['request']->_user->logout();
577             }
578             $user = new _AnonUser();
579             $user->_userid = '';
580             $user->_level = WIKIAUTH_ANON;
581             return $user; 
582         } elseif ($cancel)
583             return false;        // User hit cancel button.
584         elseif (!$login && !$userid)
585             return false;       // Nothing to do?
586
587         if (!$this->isValidName($userid))
588             return _("Invalid username.");;
589
590         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
591         if ($authlevel <= 0) { // anon or forbidden
592             if ($passwd)
593                 return _("Invalid password.");
594             else
595                 return _("Invalid password or userid.");
596         } elseif ($authlevel < $require_level) { // auth ok, but not enough 
597             if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') 
598             {
599                 // upgrade class
600                 $class = "_" . $this->_current_method . "PassUser";
601                 include_once("lib/WikiUser/".$this->_current_method.".php");
602                 $user = new $class($userid,$this->_prefs);
603                 if (!check_php_version(5))
604                     eval("\$this = \$user;");
605                 // /*PHP5 patch*/$this = $user;
606                 $this->_level = $authlevel;
607                 return $user;
608             }
609             $this->_userid = $userid;
610             $this->_level = $authlevel;
611             return _("Insufficient permissions.");
612         }
613
614         // Successful login.
615         //$user = $GLOBALS['request']->_user;
616         if (!empty($this->_current_method) and 
617             strtolower(get_class($this)) == '_passuser') 
618         {
619             // upgrade class
620             $class = "_" . $this->_current_method . "PassUser";
621             include_once("lib/WikiUser/".$this->_current_method.".php");
622             $user = new $class($userid, $this->_prefs);
623             if (!check_php_version(5))
624                 eval("\$this = \$user;");
625             // /*PHP5 patch*/$this = $user;
626             $user->_level = $authlevel;
627             return $user;
628         }
629         $this->_userid = $userid;
630         $this->_level = $authlevel;
631         return $this;
632     }
633
634 }
635
636 /**
637  * Not authenticated in user, but he may be signed in. Basicly with view access only.
638  * prefs are stored in cookies, but only the userid.
639  */
640 class _AnonUser
641 extends _WikiUser
642 {
643     var $_level = WIKIAUTH_ANON;        // var in php-5.0.0RC1 deprecated
644
645     /** Anon only gets to load and save prefs in a cookie, that's it.
646      */
647     function getPreferences() {
648         global $request;
649
650         if (empty($this->_prefs))
651             $this->_prefs = new UserPreferences;
652         $UserName = $this->UserName();
653
654         // Try to read deprecated 1.3.x style cookies
655         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
656             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
657                 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.") 
658                               . "\n"
659                               . sprintf("%s='%s'", WIKI_NAME, $cookie)
660                               . "\n"
661                               . _("Default preferences will be used."),
662                               E_USER_NOTICE);
663             }
664             /**
665              * Only set if it matches the UserName who is
666              * signing in or if this really is an Anon login (no
667              * username). (Remember, _BogoUser and higher inherit this
668              * function too!).
669              */
670             if (! $UserName || $UserName == @$unboxedcookie['userid']) {
671                 $updated = $this->_prefs->updatePrefs($unboxedcookie);
672                 //$this->_prefs = new UserPreferences($unboxedcookie);
673                 $UserName = @$unboxedcookie['userid'];
674                 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
675                     $this->_userid = $UserName;
676                 else 
677                     $UserName = false;    
678             }
679             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
680             if (!headers_sent())
681                 $request->deleteCookieVar(WIKI_NAME);
682         }
683         // Try to read deprecated 1.3.4 style cookies
684         if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
685             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
686                 if (! $UserName || $UserName == $unboxedcookie['userid']) {
687                     $updated = $this->_prefs->updatePrefs($unboxedcookie);
688                     //$this->_prefs = new UserPreferences($unboxedcookie);
689                     $UserName = $unboxedcookie['userid'];
690                     if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
691                         $this->_userid = $UserName;
692                     else 
693                         $UserName = false;    
694                 }
695                 if (!headers_sent())
696                     $request->deleteCookieVar("WIKI_PREF2");
697             }
698         }
699         if (! $UserName ) {
700             // Try reading userid from old PhpWiki cookie formats:
701             if ($cookie = $request->cookies->get_old(getCookieName())) {
702                 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
703                     $UserName = $cookie;
704                 elseif (is_array($cookie) and !empty($cookie['userid']))
705                     $UserName = $cookie['userid'];
706             }
707             if (! $UserName and !headers_sent())
708                 $request->deleteCookieVar(getCookieName());
709             else
710                 $this->_userid = $UserName;
711         }
712
713         // initializeTheme() needs at least an empty object
714         /*
715          if (empty($this->_prefs))
716             $this->_prefs = new UserPreferences;
717         */
718         return $this->_prefs;
719     }
720
721     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
722      *
723      * Allow for multiple wikis in same domain. Encode only the
724      * _prefs array of the UserPreference object. Ideally the
725      * prefs array should just be imploded into a single string or
726      * something so it is completely human readable by the end
727      * user. In that case stricter error checking will be needed
728      * when loading the cookie.
729      */
730     function setPreferences($prefs, $id_only=false) {
731         if (!is_object($prefs)) {
732             if (is_object($this->_prefs)) {
733                 $updated = $this->_prefs->updatePrefs($prefs);
734                 $prefs =& $this->_prefs;
735             } else {
736                 // update the prefs values from scratch. This could leed to unnecessary
737                 // side-effects: duplicate emailVerified, ...
738                 $this->_prefs = new UserPreferences($prefs);
739                 $updated = true;
740             }
741         } else {
742             if (!isset($this->_prefs))
743                 $this->_prefs =& $prefs;
744             else
745                 $updated = $this->_prefs->isChanged($prefs);
746         }
747         if ($updated) {
748             if ($id_only and !headers_sent()) {
749                 global $request;
750                 // new 1.3.8 policy: no array cookies, only plain userid string as in 
751                 // the pre 1.3.x versions.
752                 // prefs should be stored besides the session in the homepagehandle or in a db.
753                 $request->setCookieVar(getCookieName(), $this->_userid,
754                                        COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
755                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
756                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
757             }
758         }
759         $packed = $prefs->store();
760         $unpacked = $prefs->unpack($packed);
761         if (count($unpacked)) {
762             foreach (array('_method','_select','_update','_insert') as $param) {
763                 if (!empty($this->_prefs->{$param}))
764                     $prefs->{$param} = $this->_prefs->{$param};
765             }
766             $this->_prefs = $prefs;
767         }
768         return $updated;
769     }
770
771     function userExists() {
772         return true;
773     }
774
775     function checkPass($submitted_password) {
776         return false;
777         // this might happen on a old-style signin button.
778
779         // By definition, the _AnonUser does not HAVE a password
780         // (compared to _BogoUser, who has an EMPTY password).
781         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
782                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
783                       . "New subclasses of _WikiUser must override this function.");
784         return false;
785     }
786
787 }
788
789 /** 
790  * Helper class to finish the PassUser auth loop. 
791  * This is added automatically to USER_AUTH_ORDER.
792  */
793 class _ForbiddenUser
794 extends _AnonUser
795 {
796     var $_level = WIKIAUTH_FORBIDDEN;
797
798     function checkPass($submitted_password) {
799         return WIKIAUTH_FORBIDDEN;
800     }
801
802     function userExists() {
803         if ($this->_HomePagehandle) return true;
804         return false;
805     }
806 }
807
808 /**
809  * Do NOT extend _BogoUser to other classes, for checkPass()
810  * security. (In case of defects in code logic of the new class!)
811  * The intermediate step between anon and passuser.
812  * We also have the _BogoLoginPassUser class with stricter 
813  * password checking, which fits into the auth loop.
814  * Note: This class is not called anymore by WikiUser()
815  */
816 class _BogoUser
817 extends _AnonUser
818 {
819     function userExists() {
820         if (isWikiWord($this->_userid)) {
821             $this->_level = WIKIAUTH_BOGO;
822             return true;
823         } else {
824             $this->_level = WIKIAUTH_ANON;
825             return false;
826         }
827     }
828
829     function checkPass($submitted_password) {
830         // By definition, BogoUser has an empty password.
831         $this->userExists();
832         return $this->_level;
833     }
834 }
835
836 class _PassUser
837 extends _AnonUser
838 /**
839  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
840  *
841  * The classes for all subsequent auth methods extend from this class. 
842  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
843  * the three auth method policies first-only, strict and stacked
844  * and the two methods for prefs: homepage or database, 
845  * if $DBAuthParams['pref_select'] is defined.
846  *
847  * Default is PersonalPage auth and prefs.
848  * 
849  * @author: Reini Urban
850  * @tables: pref
851  */
852 {
853     var $_auth_dbi, $_prefs;
854     var $_current_method, $_current_index;
855
856     // check and prepare the auth and pref methods only once
857     function _PassUser($UserName='', $prefs=false) {
858         //global $DBAuthParams, $DBParams;
859         if ($UserName) {
860             /*if (!$this->isValidName($UserName))
861                 return false;*/
862             $this->_userid = $UserName;
863             if ($this->hasHomePage())
864                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
865         }
866         $this->_authmethod = substr(get_class($this),1,-8);
867         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
868
869         // Check the configured Prefs methods
870         $dbi = $this->getAuthDbh();
871         $dbh = $GLOBALS['request']->getDbh();
872         if ( $dbi and !isset($this->_prefs->_select) and $dbh->getAuthParam('pref_select')) {
873             if (!$this->_prefs) {
874                 $this->_prefs = new UserPreferences();
875                 $need_pref = true;
876             }
877             $this->_prefs->_method = $dbh->getParam('dbtype');
878             $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
879             // read-only prefs?
880             if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
881                 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'), 
882                                                         array("userid", "pref_blob"));
883             }
884         } else {
885             if (!$this->_prefs) {
886                 $this->_prefs = new UserPreferences();
887                 $need_pref = true;
888             }
889             $this->_prefs->_method = 'HomePage';
890         }
891         
892         if (! $this->_prefs or isset($need_pref) ) {
893             if ($prefs) $this->_prefs = $prefs;
894             else $this->getPreferences();
895         }
896         
897         // Upgrade to the next parent _PassUser class. Avoid recursion.
898         if ( strtolower(get_class($this)) === '_passuser' ) {
899             //auth policy: Check the order of the configured auth methods
900             // 1. first-only: Upgrade the class here in the constructor
901             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as 
902             ///              in the previous PhpWiki releases (slow)
903             // 3. strict:    upgrade the class after checking the user existance in userExists()
904             // 4. stacked:   upgrade the class after the password verification in checkPass()
905             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
906             //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
907             if (defined('USER_AUTH_POLICY')) {
908                 // policy 1: only pre-define one method for all users
909                 if (USER_AUTH_POLICY === 'first-only') {
910                     $class = $this->nextClass();
911                     return new $class($UserName,$this->_prefs);
912                 }
913                 // Use the default behaviour from the previous versions:
914                 elseif (USER_AUTH_POLICY === 'old') {
915                     // Default: try to be smart
916                     // On php5 we can directly return and upgrade the Object,
917                     // before we have to upgrade it manually.
918                     if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
919                         include_once("lib/WikiUser/HttpAuth.php");
920                         if (check_php_version(5))
921                             return new _HttpAuthPassUser($UserName,$this->_prefs);
922                         else {
923                             $user = new _HttpAuthPassUser($UserName,$this->_prefs);
924                             eval("\$this = \$user;");
925                             // /*PHP5 patch*/$this = $user;
926                             return $user;
927                         }
928                     } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
929                               $dbh->getAuthParam('auth_check') and
930                               ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
931                         if (check_php_version(5))
932                             return new _DbPassUser($UserName,$this->_prefs);
933                         else {
934                             $user = new _DbPassUser($UserName,$this->_prefs);
935                             eval("\$this = \$user;");
936                             // /*PHP5 patch*/$this = $user;
937                             return $user;
938                         }
939                     } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
940                               defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and 
941                               function_exists('ldap_connect')) {
942                         include_once("lib/WikiUser/LDAP.php");
943                         if (check_php_version(5))
944                             return new _LDAPPassUser($UserName,$this->_prefs);
945                         else {
946                             $user = new _LDAPPassUser($UserName,$this->_prefs);
947                             eval("\$this = \$user;");
948                             // /*PHP5 patch*/$this = $user;
949                             return $user;
950                         }
951                     } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
952                               defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
953                         include_once("lib/WikiUser/IMAP.php");
954                         if (check_php_version(5))
955                             return new _IMAPPassUser($UserName,$this->_prefs);
956                         else {
957                             $user = new _IMAPPassUser($UserName,$this->_prefs);
958                             eval("\$this = \$user;");
959                             // /*PHP5 patch*/$this = $user;
960                             return $user;
961                         }
962                     } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
963                               defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
964                         include_once("lib/WikiUser/File.php");
965                         if (check_php_version(5))
966                             return new _FilePassUser($UserName, $this->_prefs);
967                         else {
968                             $user = new _FilePassUser($UserName, $this->_prefs);
969                             eval("\$this = \$user;");
970                             // /*PHP5 patch*/$this = $user;
971                             return $user;
972                         }
973                     } else {
974                         include_once("lib/WikiUser/PersonalPage.php");
975                         if (check_php_version(5))
976                             return new _PersonalPagePassUser($UserName,$this->_prefs);
977                         else {
978                             $user = new _PersonalPagePassUser($UserName,$this->_prefs);
979                             eval("\$this = \$user;");
980                             // /*PHP5 patch*/$this = $user;
981                             return $user;
982                         }
983                     }
984                 }
985                 else 
986                     // else use the page methods defined in _PassUser.
987                     return $this;
988             }
989         }
990     }
991
992     function getAuthDbh () {
993         global $request; //, $DBParams, $DBAuthParams;
994
995         $dbh = $request->getDbh();
996         // session restauration doesn't re-connect to the database automatically, 
997         // so dirty it here, to force a reconnect.
998         if (isset($this->_auth_dbi)) {
999             if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1000                 unset($this->_auth_dbi);
1001             if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1002                 unset($this->_auth_dbi);
1003         }
1004         if (empty($this->_auth_dbi)) {
1005             if ($dbh->getParam('dbtype') != 'SQL' 
1006                 and $dbh->getParam('dbtype') != 'ADODB'
1007                 and $dbh->getParam('dbtype') != 'PDO')
1008                 return false;
1009             if (empty($GLOBALS['DBAuthParams']))
1010                 return false;
1011             if (!$dbh->getAuthParam('auth_dsn')) {
1012                 $dbh = $request->getDbh(); // use phpwiki database 
1013             } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1014                 $dbh = $request->getDbh(); // same phpwiki database 
1015             } else { // use another external database handle. needs PHP >= 4.1
1016                 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1017                 $local_params['dsn'] = $local_params['auth_dsn'];
1018                 $dbh = WikiDB::open($local_params);
1019             }       
1020             $this->_auth_dbi =& $dbh->_backend->_dbh;    
1021         }
1022         return $this->_auth_dbi;
1023     }
1024
1025     function _normalize_stmt_var($var, $oldstyle = false) {
1026         static $valid_variables = array('userid','password','pref_blob','groupname');
1027         // old-style: "'$userid'"
1028         // new-style: '"\$userid"' or just "userid"
1029         $new = str_replace(array("'",'"','\$','$'),'',$var);
1030         if (!in_array($new, $valid_variables)) {
1031             trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1032             return false;
1033         }
1034         return !$oldstyle ? "'$".$new."'" : '\$'.$new;
1035     }
1036
1037     // TODO: use it again for the auth and member tables
1038     // sprintfstyle vs prepare style: %s or ?
1039     //   multiple vars should be executed via prepare(?,?)+execute, 
1040     //   single vars with execute(sprintf(quote(var)))
1041     // help with position independency
1042     function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) {
1043         global $request;
1044         $dbi = $request->getDbh();
1045         $this->getAuthDbh();
1046         // "'\$userid"' => %s
1047         // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1048         // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1049         $new = array();
1050         if (is_array($variables)) {
1051             //$sprintfstyle = false;
1052             for ($i=0; $i < count($variables); $i++) { 
1053                 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1054                 if (!$var)
1055                     trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1056                                           $variables[$i], $stmt), E_USER_WARNING);
1057                 $variables[$i] = $var;
1058                 if (!$var) $new[] = '';
1059                 else {
1060                     $s = "%" . ($i+1) . "s";    
1061                     $new[] = $sprintfstyle ? $s : "?";
1062                 }
1063             }
1064         } else {
1065             $var = $this->_normalize_stmt_var($variables, $oldstyle);
1066             if (!$var)
1067                 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1068                                       $variables, $stmt), E_USER_WARNING);
1069             $variables = $var;
1070             if (!$var) $new = ''; 
1071             else $new = $sprintfstyle ? '%s' : "?"; 
1072         }
1073         $prefix = $dbi->getParam('prefix');
1074         // probably prefix table names if in same database
1075         if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and 
1076             ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1077         {
1078             if (!stristr($stmt, $prefix)) {
1079                 $oldstmt = $stmt;
1080                 $stmt = str_replace(array(" user "," pref "," member "),
1081                                     array(" ".$prefix."user ",
1082                                           " ".$prefix."pref ",
1083                                           " ".$prefix."member "), $stmt);
1084                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1085                 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n  $oldstmt \n=> $stmt",
1086                               E_USER_WARNING);
1087             }
1088         }
1089         // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1090         // Simple sprintf-style.
1091         $new_stmt = str_replace($variables, $new, $stmt);
1092         if ($new_stmt == $stmt) {
1093             if ($oldstyle) {
1094                 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1095                                   $stmt), E_USER_WARNING);
1096             } else {
1097                 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1098                                   $stmt), E_USER_WARNING);
1099                 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1100             }
1101         }
1102         return $new_stmt;
1103     }
1104
1105     function getPreferences() {
1106         if (!empty($this->_prefs->_method)) {
1107             if ($this->_prefs->_method == 'ADODB') {
1108                 // FIXME: strange why this should be needed...
1109                 include_once("lib/WikiUser/Db.php");
1110                 include_once("lib/WikiUser/AdoDb.php");
1111                 _AdoDbPassUser::_AdoDbPassUser($this->_userid, $this->_prefs);
1112                 return _AdoDbPassUser::getPreferences();
1113             } elseif ($this->_prefs->_method == 'SQL') {
1114                 include_once("lib/WikiUser/Db.php");
1115                 include_once("lib/WikiUser/PearDb.php");
1116                 _PearDbPassUser::_PearDbPassUser($this->_userid, $this->_prefs);
1117                 return _PearDbPassUser::getPreferences();
1118             } elseif ($this->_prefs->_method == 'PDO') {
1119                 include_once("lib/WikiUser/Db.php");
1120                 include_once("lib/WikiUser/PdoDb.php");
1121                 _PdoDbPassUser::_PdoDbPassUser($this->_userid, $this->_prefs);
1122                 return _PdoDbPassUser::getPreferences();
1123             }
1124         }
1125
1126         // We don't necessarily have to read the cookie first. Since
1127         // the user has a password, the prefs stored in the homepage
1128         // cannot be arbitrarily altered by other Bogo users.
1129         _AnonUser::getPreferences();
1130         // User may have deleted cookie, retrieve from his
1131         // PersonalPage if there is one.
1132         if (!empty($this->_HomePagehandle)) {
1133             if ($restored_from_page = $this->_prefs->retrieve
1134                 ($this->_HomePagehandle->get('pref'))) {
1135                 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1136                 //$this->_prefs = new UserPreferences($restored_from_page);
1137                 return $this->_prefs;
1138             }
1139         }
1140         return $this->_prefs;
1141     }
1142
1143     function setPreferences($prefs, $id_only=false) {
1144         if (!empty($this->_prefs->_method)) {
1145             if ($this->_prefs->_method == 'ADODB') {
1146                 // FIXME: strange why this should be needed...
1147                 include_once("lib/WikiUser/Db.php");
1148                 include_once("lib/WikiUser/AdoDb.php");
1149                 _AdoDbPassUser::_AdoDbPassUser($this->_userid, $prefs);
1150                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1151             }
1152             elseif ($this->_prefs->_method == 'SQL') {
1153                 include_once("lib/WikiUser/Db.php");
1154                 include_once("lib/WikiUser/PearDb.php");
1155                 _PearDbPassUser::_PearDbPassUser($this->_userid, $prefs);
1156                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1157             }
1158             elseif ($this->_prefs->_method == 'PDO') {
1159                 include_once("lib/WikiUser/Db.php");
1160                 include_once("lib/WikiUser/PdoDb.php");
1161                 _PdoDbPassUser::_PdoDbPassUser($this->_userid, $prefs);
1162                 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1163             }
1164         }
1165         if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1166             // Encode only the _prefs array of the UserPreference object
1167             // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1168             if (empty($this->_HomePagehandle)) {
1169                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1170             }
1171             if (! $this->_HomePagehandle->exists() ) {
1172                 $this->createHomePage();
1173             }
1174             if (!empty($this->_HomePagehandle) and !$id_only) {
1175                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1176             }
1177         }
1178         return $updated;
1179     }
1180
1181     function mayChangePass() {
1182         return true;
1183     }
1184
1185     //The default method is getting the password from prefs. 
1186     // child methods obtain $stored_password from external auth.
1187     function userExists() {
1188         //if ($this->_HomePagehandle) return true;
1189         if (strtolower(get_class($this)) == "_passuser") {
1190             $class = $this->nextClass();
1191             $user = new $class($this->_userid, $this->_prefs);
1192         } else {
1193             $user = $this;
1194         }
1195         while ($user) {
1196             if (!check_php_version(5))
1197                 eval("\$this = \$user;");
1198             $user = UpgradeUser($this, $user);
1199             if ($user->userExists()) {
1200                 $user = UpgradeUser($this, $user);
1201                 return true;
1202             }
1203             // prevent endless loop. does this work on all PHP's?
1204             // it just has to set the classname, what it correctly does.
1205             $class = $user->nextClass();
1206             if ($class == "_ForbiddenPassUser")
1207                 return false;
1208         }
1209         return false;
1210     }
1211
1212     //The default method is getting the password from prefs. 
1213     // child methods obtain $stored_password from external auth.
1214     function checkPass($submitted_password) {
1215         $stored_password = $this->_prefs->get('passwd');
1216         if ($this->_checkPass($submitted_password, $stored_password)) {
1217             $this->_level = WIKIAUTH_USER;
1218             return $this->_level;
1219         } else {
1220             if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1221                 $this->_level = WIKIAUTH_FORBIDDEN;
1222                 return $this->_level;
1223             }
1224             return $this->_tryNextPass($submitted_password);
1225         }
1226     }
1227
1228
1229     function _checkPassLength($submitted_password) {
1230         if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1231             trigger_error(_("The length of the password is shorter than the system policy allows."));
1232             return false;
1233         }
1234         return true;
1235     }
1236
1237     /**
1238      * The basic password checker for all PassUser objects.
1239      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1240      * Empty passwords are always false!
1241      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1242      * @see UserPreferences::set
1243      *
1244      * DBPassUser password's have their own crypt definition.
1245      * That's why DBPassUser::checkPass() doesn't call this method, if 
1246      * the db password method is 'plain', which means that the DB SQL 
1247      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
1248      * don't store plain passwords in the DB.
1249      * 
1250      * TODO: remove crypt() function check from config.php:396 ??
1251      */
1252     function _checkPass($submitted_password, $stored_password) {
1253         if (!empty($submitted_password)) {
1254             // This works only on plaintext passwords.
1255             if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1256                 // With the EditMetaData plugin
1257                 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."));
1258                 return false;
1259             }
1260             if (!$this->_checkPassLength($submitted_password)) {
1261                 return false;
1262             }
1263             if (ENCRYPTED_PASSWD) {
1264                 // Verify against encrypted password.
1265                 if (function_exists('crypt')) {
1266                     if (crypt($submitted_password, $stored_password) == $stored_password )
1267                         return true; // matches encrypted password
1268                     else
1269                         return false;
1270                 }
1271                 else {
1272                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1273                                   . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1274                                   E_USER_WARNING);
1275                     return false;
1276                 }
1277             }
1278             else {
1279                 // Verify against cleartext password.
1280                 if ($submitted_password == $stored_password)
1281                     return true;
1282                 else {
1283                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1284                     if (function_exists('crypt')) {
1285                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1286                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1287                                           E_USER_WARNING);
1288                             return true;
1289                         }
1290                     }
1291                 }
1292             }
1293         }
1294         return false;
1295     }
1296
1297     /** The default method is storing the password in prefs. 
1298      *  Child methods (DB, File) may store in external auth also, but this 
1299      *  must be explicitly enabled.
1300      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1301      */
1302     function changePass($submitted_password) {
1303         $stored_password = $this->_prefs->get('passwd');
1304         // check if authenticated
1305         if (!$this->isAuthenticated()) return false;
1306         if (ENCRYPTED_PASSWD) {
1307             $submitted_password = crypt($submitted_password);
1308         }
1309         // check other restrictions, with side-effects only.
1310         $result = $this->_checkPass($submitted_password, $stored_password);
1311         if ($stored_password != $submitted_password) {
1312             $this->_prefs->set('passwd', $submitted_password);
1313             //update the storage (session, homepage, ...)
1314             $this->SetPreferences($this->_prefs);
1315             return true;
1316         }
1317         //Todo: return an error msg to the caller what failed? 
1318         // same password or no privilege
1319         return ENCRYPTED_PASSWD ? true : false;
1320     }
1321
1322     function _tryNextPass($submitted_password) {
1323         if (DEBUG & _DEBUG_LOGIN) {
1324             $class = strtolower(get_class($this));
1325             if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1326             $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1327         }
1328         if (USER_AUTH_POLICY === 'strict') {
1329             $class = $this->nextClass();
1330             if ($user = new $class($this->_userid,$this->_prefs)) {
1331                 if ($user->userExists()) {
1332                     return $user->checkPass($submitted_password);
1333                 }
1334             }
1335         }
1336         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1337             $class = $this->nextClass();
1338             if ($user = new $class($this->_userid,$this->_prefs))
1339                 return $user->checkPass($submitted_password);
1340         }
1341         return $this->_level;
1342     }
1343
1344     function _tryNextUser() {
1345         if (DEBUG & _DEBUG_LOGIN) {
1346             $class = strtolower(get_class($this));
1347             if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1348             $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1349         }
1350         if (USER_AUTH_POLICY === 'strict'
1351             or USER_AUTH_POLICY === 'stacked') {
1352             $class = $this->nextClass();
1353             while ($user = new $class($this->_userid, $this->_prefs)) {
1354                 if (!check_php_version(5))
1355                     eval("\$this = \$user;");
1356                 $user = UpgradeUser($this, $user);
1357                 if ($user->userExists()) {
1358                     $user = UpgradeUser($this, $user);
1359                     return true;
1360                 }
1361                 $class = $this->nextClass();
1362             }
1363         }
1364         return false;
1365     }
1366
1367 }
1368
1369 /**
1370  * Insert more auth classes here...
1371  * For example a customized db class for another db connection 
1372  * or a socket-based auth server.
1373  *
1374  */
1375
1376
1377 /**
1378  * For security, this class should not be extended. Instead, extend
1379  * from _PassUser (think of this as unix "root").
1380  *
1381  * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1382  * Other members of the Administrators group must raise their level otherwise somehow.
1383  * Currently every member is a AdminUser, which will not work for the various 
1384  * storage methods.
1385  */
1386 class _AdminUser
1387 extends _PassUser
1388 {
1389     function mayChangePass() {
1390         return false;
1391     }
1392     function checkPass($submitted_password) {
1393         if ($this->_userid == ADMIN_USER)
1394             $stored_password = ADMIN_PASSWD;
1395         else {
1396             // Should not happen! Only ADMIN_USER should use this class.
1397             // return $this->_tryNextPass($submitted_password); // ???
1398             // TODO: safety check if really member of the ADMIN group?
1399             $stored_password = $this->_pref->get('passwd');
1400         }
1401         if ($this->_checkPass($submitted_password, $stored_password)) {
1402             $this->_level = WIKIAUTH_ADMIN;
1403             if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1404                 // fake http auth
1405                 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1406             }
1407             return $this->_level;
1408         } else {
1409             return $this->_tryNextPass($submitted_password);
1410             //$this->_level = WIKIAUTH_ANON;
1411             //return $this->_level;
1412         }
1413     }
1414
1415     function storePass($submitted_password) {
1416         if ($this->_userid == ADMIN_USER)
1417             return false;
1418         else {
1419             // should not happen! only ADMIN_USER should use this class.
1420             return parent::storePass($submitted_password);
1421         }
1422     }
1423 }
1424
1425 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1426 /**
1427  * Various data classes for the preference types, 
1428  * to support get, set, sanify (range checking, ...)
1429  * update() will do the neccessary side-effects if a 
1430  * setting gets changed (theme, language, ...)
1431 */
1432
1433 class _UserPreference
1434 {
1435     var $default_value;
1436
1437     function _UserPreference ($default_value) {
1438         $this->default_value = $default_value;
1439     }
1440
1441     function sanify ($value) {
1442         return (string)$value;
1443     }
1444
1445     function get ($name) {
1446         if (isset($this->{$name}))
1447             return $this->{$name};
1448         else 
1449             return $this->default_value;
1450     }
1451
1452     function getraw ($name) {
1453         if (!empty($this->{$name}))
1454             return $this->{$name};
1455     }
1456
1457     // stores the value as $this->$name, and not as $this->value (clever?)
1458     function set ($name, $value) {
1459         $return = 0;
1460         $value = $this->sanify($value);
1461         if ($this->get($name) != $value) {
1462             $this->update($value);
1463             $return = 1;
1464         }
1465         if ($value != $this->default_value) {
1466             $this->{$name} = $value;
1467         } else {
1468             unset($this->{$name});
1469         }
1470         return $return;
1471     }
1472
1473     // default: no side-effects 
1474     function update ($value) {
1475         ;
1476     }
1477 }
1478
1479 class _UserPreference_numeric
1480 extends _UserPreference
1481 {
1482     function _UserPreference_numeric ($default, $minval = false,
1483                                       $maxval = false) {
1484         $this->_UserPreference((double)$default);
1485         $this->_minval = (double)$minval;
1486         $this->_maxval = (double)$maxval;
1487     }
1488
1489     function sanify ($value) {
1490         $value = (double)$value;
1491         if ($this->_minval !== false && $value < $this->_minval)
1492             $value = $this->_minval;
1493         if ($this->_maxval !== false && $value > $this->_maxval)
1494             $value = $this->_maxval;
1495         return $value;
1496     }
1497 }
1498
1499 class _UserPreference_int
1500 extends _UserPreference_numeric
1501 {
1502     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1503         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1504     }
1505
1506     function sanify ($value) {
1507         return (int)parent::sanify((int)$value);
1508     }
1509 }
1510
1511 class _UserPreference_bool
1512 extends _UserPreference
1513 {
1514     function _UserPreference_bool ($default = false) {
1515         $this->_UserPreference((bool)$default);
1516     }
1517
1518     function sanify ($value) {
1519         if (is_array($value)) {
1520             /* This allows for constructs like:
1521              *
1522              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1523              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1524              *
1525              * (If the checkbox is not checked, only the hidden input
1526              * gets sent. If the checkbox is sent, both inputs get
1527              * sent.)
1528              */
1529             foreach ($value as $val) {
1530                 if ($val)
1531                     return true;
1532             }
1533             return false;
1534         }
1535         return (bool) $value;
1536     }
1537 }
1538
1539 class _UserPreference_language
1540 extends _UserPreference
1541 {
1542     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1543         $this->_UserPreference($default);
1544     }
1545
1546     // FIXME: check for valid locale
1547     function sanify ($value) {
1548         // Revert to DEFAULT_LANGUAGE if user does not specify
1549         // language in UserPreferences or chooses <system language>.
1550         if ($value == '' or empty($value))
1551             $value = DEFAULT_LANGUAGE;
1552
1553         return (string) $value;
1554     }
1555     
1556     function update ($newvalue) {
1557         if (! $this->_init ) {
1558             // invalidate etag to force fresh output
1559             $GLOBALS['request']->setValidators(array('%mtime' => false));
1560             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1561         }
1562     }
1563 }
1564
1565 class _UserPreference_theme
1566 extends _UserPreference
1567 {
1568     function _UserPreference_theme ($default = THEME) {
1569         $this->_UserPreference($default);
1570     }
1571
1572     function sanify ($value) {
1573         if (!empty($value) and FindFile($this->_themefile($value)))
1574             return $value;
1575         return $this->default_value;
1576     }
1577
1578     function update ($newvalue) {
1579         global $WikiTheme;
1580         // invalidate etag to force fresh output
1581         if (! $this->_init )
1582             $GLOBALS['request']->setValidators(array('%mtime' => false));
1583         if ($newvalue)
1584             include_once($this->_themefile($newvalue));
1585         if (empty($WikiTheme))
1586             include_once($this->_themefile(THEME));
1587     }
1588
1589     function _themefile ($theme) {
1590         return "themes/$theme/themeinfo.php";
1591     }
1592 }
1593
1594 class _UserPreference_notify
1595 extends _UserPreference
1596 {
1597     function sanify ($value) {
1598         if (!empty($value))
1599             return $value;
1600         else
1601             return $this->default_value;
1602     }
1603
1604     /** update to global user prefs: side-effect on set notify changes
1605      * use a global_data notify hash:
1606      * notify = array('pagematch' => array(userid => ('email' => mail, 
1607      *                                                'verified' => 0|1),
1608      *                                     ...),
1609      *                ...);
1610      */
1611     function update ($value) {
1612         if (!empty($this->_init)) return;
1613         $dbh = $GLOBALS['request']->getDbh();
1614         $notify = $dbh->get('notify');
1615         if (empty($notify))
1616             $data = array();
1617         else 
1618             $data =& $notify;
1619         // expand to existing pages only or store matches?
1620         // for now we store (glob-style) matches which is easier for the user
1621         $pages = $this->_page_split($value);
1622         // Limitation: only current user.
1623         $user = $GLOBALS['request']->getUser();
1624         if (!$user or !method_exists($user,'UserName')) return;
1625         // This fails with php5 and a WIKI_ID cookie:
1626         $userid = $user->UserName();
1627         $email  = $user->_prefs->get('email');
1628         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1629         // check existing notify hash and possibly delete pages for email
1630         if (!empty($data)) {
1631             foreach ($data as $page => $users) {
1632                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1633                     unset($data[$page][$userid]);
1634                 }
1635                 if (count($data[$page]) == 0)
1636                     unset($data[$page]);
1637             }
1638         }
1639         // add the new pages
1640         if (!empty($pages)) {
1641             foreach ($pages as $page) {
1642                 if (!isset($data[$page]))
1643                     $data[$page] = array();
1644                 if (!isset($data[$page][$userid])) {
1645                     // should we really store the verification notice here or 
1646                     // check it dynamically at every page->save?
1647                     if ($verified) {
1648                         $data[$page][$userid] = array('email' => $email,
1649                                                       'verified' => $verified);
1650                     } else {
1651                         $data[$page][$userid] = array('email' => $email);
1652                     }
1653                 }
1654             }
1655         }
1656         // store users changes
1657         $dbh->set('notify',$data);
1658     }
1659
1660     /** split the user-given comma or whitespace delimited pagenames
1661      *  to array
1662      */
1663     function _page_split($value) {
1664         return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1665     }
1666 }
1667
1668 class _UserPreference_email
1669 extends _UserPreference
1670 {
1671     function sanify($value) {
1672         // check for valid email address
1673         if ($this->get('email') == $value and $this->getraw('emailVerified'))
1674             return $value;
1675         // hack!
1676         if ($value == 1 or $value === true)
1677             return $value;
1678         list($ok,$msg) = ValidateMail($value,'noconnect');
1679         if ($ok) {
1680             return $value;
1681         } else {
1682             trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
1683             return $this->default_value;
1684         }
1685     }
1686     
1687     /** Side-effect on email changes:
1688      * Send a verification mail or for now just a notification email.
1689      * For true verification (value = 2), we'd need a mailserver hook.
1690      */
1691     function update($value) {
1692         if (!empty($this->_init)) return;
1693         $verified = $this->getraw('emailVerified');
1694         // hack!
1695         if (($value == 1 or $value === true) and $verified)
1696             return;
1697         if (!empty($value) and !$verified) {
1698             list($ok,$msg) = ValidateMail($value);
1699             if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
1700                      sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1701                              WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) {
1702                 $this->set('emailVerified',1);
1703             } else {
1704                 trigger_error($msg, E_USER_WARNING);
1705             }
1706         }
1707     }
1708 }
1709
1710 /** Check for valid email address
1711     fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1712     Note: too strict, Bug #1053681
1713  */
1714 function ValidateMail($email, $noconnect=false) {
1715     global $EMailHosts;
1716     $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1717
1718     // if this check is too strict (like invalid mail addresses in a local network only)
1719     // uncomment the following line:
1720     //return array(true,"not validated");
1721     // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1722
1723     $result = array();
1724
1725     // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1726     // addresses, from the Perl module Mail::RFC822::Address, reduced to
1727     // accept single RFC822 addresses without comments only. (The original
1728     // accepts groups and properly commented addresses also.)
1729     $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1730
1731     $specials = '()<>@,;:\\\\".\\[\\]';
1732     $controls = '\\000-\\031';
1733
1734     $dtext = "[^\\[\\]\\r\\\\]";
1735     $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1736
1737     $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1738
1739     $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1740     $word = "(?:$atom|$quoted_string)";
1741     $localpart = "$word(?:\\.$lwsp*$word)*";
1742
1743     $sub_domain = "(?:$atom|$domain_literal)";
1744     $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1745
1746     $addr_spec = "$localpart\@$lwsp*$domain";
1747
1748     $phrase = "$word*";
1749     $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1750     $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1751     $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1752
1753     $rfc822re = "/$lwsp*$mailbox/";
1754     unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart, 
1755           $atom, $word, $quoted_string);
1756     unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1757
1758     if (!preg_match($rfc822re, $email)) {
1759         $result[0] = false;
1760         $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
1761         return $result;
1762     }
1763     if ($noconnect)
1764       return array(true, sprintf(_("E-Mail address '%s' is properly formatted"), $email));
1765
1766     list ( $Username, $Domain ) = split ("@", $email);
1767     //Todo: getmxrr workaround on windows or manual input field to verify it manually
1768     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. 
1769         $ConnectAddress = $MXHost[0];
1770     } else {
1771         $ConnectAddress = $Domain;
1772         if (isset($EMailHosts[ $Domain ])) {
1773             $ConnectAddress = $EMailHosts[ $Domain ];
1774         }
1775     }
1776     $Connect = @fsockopen ( $ConnectAddress, 25 );
1777     if ($Connect) {
1778         if (ereg("^220", $Out = fgets($Connect, 1024))) {
1779             fputs ($Connect, "HELO $HTTP_HOST\r\n");
1780             $Out = fgets ( $Connect, 1024 );
1781             fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
1782             $From = fgets ( $Connect, 1024 );
1783             fputs ($Connect, "RCPT TO: <".$email.">\r\n");
1784             $To = fgets ($Connect, 1024);
1785             fputs ($Connect, "QUIT\r\n");
1786             fclose($Connect);
1787             if (!ereg ("^250", $From)) {
1788                 $result[0]=false;
1789                 $result[1]="Server rejected address: ". $From;
1790                 return $result;
1791             }
1792             if (!ereg ( "^250", $To )) {
1793                 $result[0]=false;
1794                 $result[1]="Server rejected address: ". $To;
1795                 return $result;
1796             }
1797         } else {
1798             $result[0] = false;
1799             $result[1] = "No response from server";
1800             return $result;
1801           }
1802     }  else {
1803         $result[0]=false;
1804         $result[1]="Can not connect E-Mail server.";
1805         return $result;
1806     }
1807     $result[0]=true;
1808     $result[1]="E-Mail address '$email' appears to be valid.";
1809     return $result;
1810 } // end of function 
1811
1812 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1813
1814 /**
1815  * UserPreferences
1816  * 
1817  * This object holds the $request->_prefs subobjects.
1818  * A simple packed array of non-default values get's stored as cookie,
1819  * homepage, or database, which are converted to the array of 
1820  * ->_prefs objects.
1821  * We don't store the objects, because otherwise we will
1822  * not be able to upgrade any subobject. And it's a waste of space also.
1823  *
1824  */
1825 class UserPreferences
1826 {
1827     function UserPreferences($saved_prefs = false) {
1828         // userid stored too, to ensure the prefs are being loaded for
1829         // the correct (currently signing in) userid if stored in a
1830         // cookie.
1831         // Update: for db prefs we disallow passwd. 
1832         // userid is needed for pref reflexion. current pref must know its username, 
1833         // if some app needs prefs from different users, different from current user.
1834         $this->_prefs
1835             = array(
1836                     'userid'        => new _UserPreference(''),
1837                     'passwd'        => new _UserPreference(''),
1838                     'autologin'     => new _UserPreference_bool(),
1839                     //'emailVerified' => new _UserPreference_emailVerified(), 
1840                     //fixed: store emailVerified as email parameter, 1.3.8
1841                     'email'         => new _UserPreference_email(''),
1842                     'notifyPages'   => new _UserPreference_notify(''), // 1.3.8
1843                     'theme'         => new _UserPreference_theme(THEME),
1844                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
1845                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1846                                                                EDITWIDTH_MIN_COLS,
1847                                                                EDITWIDTH_MAX_COLS),
1848                     'noLinkIcons'   => new _UserPreference_bool(),    // 1.3.8 
1849                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1850                                                                EDITHEIGHT_MIN_ROWS,
1851                                                                EDITHEIGHT_MAX_ROWS),
1852                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1853                                                                    TIMEOFFSET_MIN_HOURS,
1854                                                                    TIMEOFFSET_MAX_HOURS),
1855                     'relativeDates' => new _UserPreference_bool(),
1856                     'googleLink'    => new _UserPreference_bool(), // 1.3.10
1857                     'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1858                     );
1859         // add custom theme-specific pref types:
1860         // FIXME: on theme changes the wiki_user session pref object will fail. 
1861         // We will silently ignore this.
1862         if (!empty($customUserPreferenceColumns))
1863             $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
1864 /*
1865         if (isset($this->_method) and $this->_method == 'SQL') {
1866             //unset($this->_prefs['userid']);
1867             unset($this->_prefs['passwd']);
1868         }
1869 */
1870         if (is_array($saved_prefs)) {
1871             foreach ($saved_prefs as $name => $value)
1872                 $this->set($name, $value);
1873         }
1874     }
1875
1876     function _getPref($name) {
1877         if ($name == 'emailVerified')
1878             $name = 'email';
1879         if (!isset($this->_prefs[$name])) {
1880             if ($name == 'passwd2') return false;
1881             if ($name == 'passwd') return false;
1882             trigger_error("$name: unknown preference", E_USER_NOTICE);
1883             return false;
1884         }
1885         return $this->_prefs[$name];
1886     }
1887     
1888     // get the value or default_value of the subobject
1889     function get($name) {
1890         if ($_pref = $this->_getPref($name))
1891             if ($name == 'emailVerified')
1892                 return $_pref->getraw($name);
1893             else
1894                 return $_pref->get($name);
1895         else
1896             return false;  
1897     }
1898
1899     // check and set the new value in the subobject
1900     function set($name, $value) {
1901         $pref = $this->_getPref($name);
1902         if ($pref === false)
1903             return false;
1904
1905         /* do it here or outside? */
1906         if ($name == 'passwd' and 
1907             defined('PASSWORD_LENGTH_MINIMUM') and 
1908             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1909             //TODO: How to notify the user?
1910             return false;
1911         }
1912         /*
1913         if ($name == 'theme' and $value == '')
1914            return true;
1915         */
1916         // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
1917         if ((!$value and $pref->default_value)
1918             or ($value and !isset($pref->{$name})) // bug #1355533
1919             or ($value and ($pref->{$name} != $pref->default_value)))
1920         {
1921             if ($name == 'emailVerified') $newvalue = $value;
1922             else $newvalue = $pref->sanify($value);
1923             $pref->set($name, $newvalue);
1924         }
1925         $this->_prefs[$name] =& $pref;
1926         return true;
1927     }
1928     /**
1929      * use init to avoid update on set
1930      */
1931     function updatePrefs($prefs, $init = false) {
1932         $count = 0;
1933         if ($init) $this->_init = $init;
1934         if (is_object($prefs)) {
1935             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
1936             $obj->_init = $init;
1937             if ($obj->get($type) !== $prefs->get($type)) {
1938                 if ($obj->set($type, $prefs->get($type)))
1939                     $count++;
1940             }
1941             foreach (array_keys($this->_prefs) as $type) {
1942                 $obj =& $this->_prefs[$type];
1943                 $obj->_init = $init;
1944                 if ($prefs->get($type) !== $obj->get($type)) {
1945                     // special systemdefault prefs: (probably not needed)
1946                     if ($type == 'theme' and $prefs->get($type) == '' and 
1947                         $obj->get($type) == THEME) continue;
1948                     if ($type == 'lang' and $prefs->get($type) == '' and 
1949                         $obj->get($type) == DEFAULT_LANGUAGE) continue;
1950                     if ($this->_prefs[$type]->set($type, $prefs->get($type)))
1951                         $count++;
1952                 }
1953             }
1954         } elseif (is_array($prefs)) {
1955             //unset($this->_prefs['userid']);
1956             /*
1957             if (isset($this->_method) and 
1958                  ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
1959                 unset($this->_prefs['passwd']);
1960             }
1961             */
1962             // emailVerified at first, the rest later
1963             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
1964             $obj->_init = $init;
1965             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
1966                 if ($obj->set($type,$prefs[$type]))
1967                     $count++;
1968             }
1969             foreach (array_keys($this->_prefs) as $type) {
1970                 $obj =& $this->_prefs[$type];
1971                 $obj->_init = $init;
1972                 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool")) 
1973                     $prefs[$type] = false;
1974                 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
1975                     $prefs[$type] = (int) $prefs[$type];
1976                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
1977                     // special systemdefault prefs:
1978                     if ($type == 'theme' and $prefs[$type] == '' and 
1979                         $obj->get($type) == THEME) continue;
1980                     if ($type == 'lang' and $prefs[$type] == '' and 
1981                         $obj->get($type) == DEFAULT_LANGUAGE) continue;
1982                     if ($obj->set($type,$prefs[$type]))
1983                         $count++;
1984                 }
1985             }
1986         }
1987         return $count;
1988     }
1989
1990     // For now convert just array of objects => array of values
1991     // Todo: the specialized subobjects must override this.
1992     function store() {
1993         $prefs = array();
1994         foreach ($this->_prefs as $name => $object) {
1995             if ($value = $object->getraw($name))
1996                 $prefs[$name] = $value;
1997             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
1998                 $prefs['emailVerified'] = $value;
1999             if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2000                 if (strlen($value) != strlen(crypt('test')))
2001                     $prefs['passwd'] = crypt($value);
2002                 else // already crypted
2003                     $prefs['passwd'] = $value;
2004             }
2005         }
2006         return $this->pack($prefs);
2007     }
2008
2009     // packed string or array of values => array of values
2010     // Todo: the specialized subobjects must override this.
2011     function retrieve($packed) {
2012         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2013             $packed = unserialize($packed);
2014         if (!is_array($packed)) return false;
2015         $prefs = array();
2016         foreach ($packed as $name => $packed_pref) {
2017             if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2018                 //legacy: check if it's an old array of objects
2019                 // Looks like a serialized object. 
2020                 // This might fail if the object definition does not exist anymore.
2021                 // object with ->$name and ->default_value vars.
2022                 $pref =  @unserialize($packed_pref);
2023                 if (empty($pref))
2024                     $pref = @unserialize(base64_decode($packed_pref));
2025                 $prefs[$name] = $pref->get($name);
2026             // fix old-style prefs
2027             } elseif (is_numeric($name) and is_array($packed_pref)) {
2028                 if (count($packed_pref) == 1) {
2029                     list($name,$value) = each($packed_pref);
2030                     $prefs[$name] = $value;
2031                 }
2032             } else {
2033                 $prefs[$name] = @unserialize($packed_pref);
2034                 if (empty($prefs[$name]))
2035                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
2036                 // patched by frederik@pandora.be
2037                 if (empty($prefs[$name]))
2038                     $prefs[$name] = $packed_pref;
2039             }
2040         }
2041         return $prefs;
2042     }
2043
2044     /**
2045      * Check if the given prefs object is different from the current prefs object
2046      */
2047     function isChanged($other) {
2048         foreach ($this->_prefs as $type => $obj) {
2049             if ($obj->get($type) !== $other->get($type))
2050                 return true;
2051         }
2052         return false;
2053     }
2054
2055     function defaultPreferences() {
2056         $prefs = array();
2057         foreach ($this->_prefs as $key => $obj) {
2058             $prefs[$key] = $obj->default_value;
2059         }
2060         return $prefs;
2061     }
2062     
2063     // array of objects
2064     function getAll() {
2065         return $this->_prefs;
2066     }
2067
2068     function pack($nonpacked) {
2069         return serialize($nonpacked);
2070     }
2071
2072     function unpack($packed) {
2073         if (!$packed)
2074             return false;
2075         //$packed = base64_decode($packed);
2076         if (substr($packed, 0, 2) == "O:") {
2077             // Looks like a serialized object
2078             return unserialize($packed);
2079         }
2080         if (substr($packed, 0, 2) == "a:") {
2081             return unserialize($packed);
2082         }
2083         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2084         //E_USER_WARNING);
2085         return false;
2086     }
2087
2088     function hash () {
2089         return wikihash($this->_prefs);
2090     }
2091 }
2092
2093 /** TODO: new pref storage classes
2094  *  These are currently user specific and should be rewritten to be pref specific.
2095  *  i.e. $this == $user->_prefs
2096  */
2097 /*
2098 class CookieUserPreferences
2099 extends UserPreferences
2100 {
2101     function CookieUserPreferences ($saved_prefs = false) {
2102         //_AnonUser::_AnonUser('',$saved_prefs);
2103         UserPreferences::UserPreferences($saved_prefs);
2104     }
2105 }
2106
2107 class PageUserPreferences
2108 extends UserPreferences
2109 {
2110     function PageUserPreferences ($saved_prefs = false) {
2111         UserPreferences::UserPreferences($saved_prefs);
2112     }
2113 }
2114
2115 class PearDbUserPreferences
2116 extends UserPreferences
2117 {
2118     function PearDbUserPreferences ($saved_prefs = false) {
2119         UserPreferences::UserPreferences($saved_prefs);
2120     }
2121 }
2122
2123 class AdoDbUserPreferences
2124 extends UserPreferences
2125 {
2126     function AdoDbUserPreferences ($saved_prefs = false) {
2127         UserPreferences::UserPreferences($saved_prefs);
2128     }
2129     function getPreferences() {
2130         // override the generic slow method here for efficiency
2131         _AnonUser::getPreferences();
2132         $this->getAuthDbh();
2133         if (isset($this->_select)) {
2134             $dbh = & $this->_auth_dbi;
2135             $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2136             if ($rs->EOF) {
2137                 $rs->Close();
2138             } else {
2139                 $prefs_blob = $rs->fields['pref_blob'];
2140                 $rs->Close();
2141                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2142                     $updated = $this->_prefs->updatePrefs($restored_from_db);
2143                     //$this->_prefs = new UserPreferences($restored_from_db);
2144                     return $this->_prefs;
2145                 }
2146             }
2147         }
2148         if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2149             if ($restored_from_page = $this->_prefs->retrieve
2150                 ($this->_HomePagehandle->get('pref'))) {
2151                 $updated = $this->_prefs->updatePrefs($restored_from_page);
2152                 //$this->_prefs = new UserPreferences($restored_from_page);
2153                 return $this->_prefs;
2154             }
2155         }
2156         return $this->_prefs;
2157     }
2158 }
2159 */
2160
2161 // $Log: not supported by cvs2svn $
2162 // Revision 1.142  2007/05/15 16:32:34  rurban
2163 // Refactor class upgrading at ->UserExists
2164 //
2165 // Revision 1.141  2007/05/13 18:31:24  rurban
2166 // Refactor UpgradeUser. Added EMailHosts
2167 //
2168 // Revision 1.140  2006/12/22 01:20:14  rurban
2169 // Automatically create a Users homepage, when no SQL method exists
2170 // not to rely on cookies.
2171 //
2172 // Revision 1.139  2006/09/03 09:55:37  rurban
2173 // Remove too early and too strict isValidName check in _PassUser. This really should be done in
2174 // the method, when we know it. This fixes NTLM auth. (userid=domain\user)
2175 //
2176 // Revision 1.138  2006/06/18 11:02:55  rurban
2177 // pref->value > -name, fix bug #1355533
2178 //
2179 // Revision 1.137  2006/05/03 06:05:37  rurban
2180 // Fix default preferences for editheight maxrows, by Manuel Vacelet.
2181 //
2182 // Revision 1.136  2006/04/16 11:07:48  rurban
2183 // Dont crypt the passwd twice on storing prefs. Patch by Thomas Harding.
2184 // Fixes bug #1327470
2185 //
2186 // Revision 1.135  2006/03/19 16:26:39  rurban
2187 // fix DBAUTH arguments to be position independent, fixes bug #1358973
2188 //
2189 // Revision 1.134  2006/03/19 15:01:00  rurban
2190 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2191 //
2192 // Revision 1.133  2006/03/07 18:39:21  rurban
2193 // add PdoDb, rename hash to wikihash (php-5.1), fix output of Homepage prefs update
2194 //
2195 // Revision 1.132  2006/03/04 13:19:12  rurban
2196 // fix for fatal error on empty pref value (sign out). Thanks to Jim Ford and Joel Schaubert. rename hash for php-5.1
2197 //
2198 // Revision 1.131  2005/10/12 06:16:48  rurban
2199 // add new _insert statement
2200 //
2201 // Revision 1.129  2005/06/10 06:10:35  rurban
2202 // ensure Update Preferences gets through
2203 //
2204 // Revision 1.128  2005/06/05 05:38:02  rurban
2205 // Default ENABLE_DOUBLECLICKEDIT = false. Moved to UserPreferences
2206 //
2207 // Revision 1.127  2005/04/02 18:01:41  uckelman
2208 // Fixed regex for RFC822 addresses.
2209 //
2210 // Revision 1.126  2005/02/28 20:30:46  rurban
2211 // some stupid code for _AdminUser (probably not needed)
2212 //
2213 // Revision 1.125  2005/02/08 13:25:50  rurban
2214 // encrypt password. fix strict logic.
2215 // both bugs reported by Mikhail Vladimirov
2216 //
2217 // Revision 1.124  2005/01/30 23:11:00  rurban
2218 // allow self-creating passuser on login
2219 //
2220 // Revision 1.123  2005/01/25 06:58:21  rurban
2221 // reformatting
2222 //
2223 // Revision 1.122  2005/01/08 22:51:56  rurban
2224 // remove deprecated workaround
2225 //
2226 // Revision 1.121  2004/12/19 00:58:01  rurban
2227 // Enforce PASSWORD_LENGTH_MINIMUM in almost all PassUser checks,
2228 // Provide an errormessage if so. Just PersonalPage and BogoLogin not.
2229 // Simplify httpauth logout handling and set sessions for all methods.
2230 // fix main.php unknown index "x" getLevelDescription() warning.
2231 //
2232 // Revision 1.120  2004/12/17 12:31:57  rurban
2233 // better logout, fake httpauth not yet
2234 //
2235 // Revision 1.119  2004/11/21 11:59:17  rurban
2236 // remove final \n to be ob_cache independent
2237 //
2238 // Revision 1.118  2004/11/19 19:22:03  rurban
2239 // ModeratePage part1: change status
2240 //
2241 // Revision 1.117  2004/11/10 15:29:21  rurban
2242 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
2243 // * ACCESS_LOG_SQL: fix cause request not yet initialized
2244 // * WikiDB: moved SQL specific methods upwards
2245 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
2246 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
2247 //
2248 // Revision 1.116  2004/11/05 21:03:27  rurban
2249 // new DEBUG flag: _DEBUG_LOGIN (64)
2250 //   verbose login debug-msg (settings and reason for failure)
2251 //
2252 // Revision 1.115  2004/11/05 20:53:35  rurban
2253 // login cleanup: better debug msg on failing login,
2254 // checked password less immediate login (bogo or anon),
2255 // checked olduser pref session error,
2256 // better PersonalPage without password warning on minimal password length=0
2257 //   (which is default now)
2258 //
2259 // Revision 1.114  2004/11/05 16:15:57  rurban
2260 // forgot the BogoLogin inclusion with the latest rewrite
2261 //
2262 // Revision 1.113  2004/11/03 17:13:49  rurban
2263 // make it easier to disable EmailVerification
2264 //   Bug #1053681
2265 //
2266 // Revision 1.112  2004/11/01 10:43:57  rurban
2267 // seperate PassUser methods into seperate dir (memory usage)
2268 // fix WikiUser (old) overlarge data session
2269 // remove wikidb arg from various page class methods, use global ->_dbi instead
2270 // ...
2271 //
2272 // Revision 1.111  2004/10/21 21:03:50  rurban
2273 // isAdmin must be signed and authenticated
2274 // comment out unused sections (memory)
2275 //
2276 // Revision 1.110  2004/10/14 19:19:33  rurban
2277 // loadsave: check if the dumped file will be accessible from outside.
2278 // and some other minor fixes. (cvsclient native not yet ready)
2279 //
2280 // Revision 1.109  2004/10/07 16:08:58  rurban
2281 // fixed broken FileUser session handling.
2282 //   thanks to Arnaud Fontaine for detecting this.
2283 // enable file user Administrator membership.
2284 //
2285 // Revision 1.108  2004/10/05 17:00:04  rurban
2286 // support paging for simple lists
2287 // fix RatingDb sql backend.
2288 // remove pages from AllPages (this is ListPages then)
2289 //
2290 // Revision 1.107  2004/10/04 23:42:15  rurban
2291 // HttpAuth admin group logic. removed old logs
2292 //
2293 // Revision 1.106  2004/07/01 08:49:38  rurban
2294 // obsolete php5-patch.php: minor php5 login problem though
2295 //
2296 // Revision 1.105  2004/06/29 06:48:03  rurban
2297 // Improve LDAP auth and GROUP_LDAP membership:
2298 //   no error message on false password,
2299 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2300 //   fixed two group queries (this -> user)
2301 // stdlib: ConvertOldMarkup still flawed
2302 //
2303 // Revision 1.104  2004/06/28 15:39:37  rurban
2304 // fixed endless recursion in WikiGroup: isAdmin()
2305 //
2306 // Revision 1.103  2004/06/28 15:01:07  rurban
2307 // fixed LDAP_SET_OPTION handling, LDAP error on connection problem
2308 //
2309 // Revision 1.102  2004/06/27 10:23:48  rurban
2310 // typo detected by Philippe Vanhaesendonck
2311 //
2312 // Revision 1.101  2004/06/25 14:29:19  rurban
2313 // WikiGroup refactoring:
2314 //   global group attached to user, code for not_current user.
2315 //   improved helpers for special groups (avoid double invocations)
2316 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2317 // fixed a XHTML validation error on userprefs.tmpl
2318 //
2319 // Revision 1.100  2004/06/21 06:29:35  rurban
2320 // formatting: linewrap only
2321 //
2322 // Revision 1.99  2004/06/20 15:30:05  rurban
2323 // get_class case-sensitivity issues
2324 //
2325 // Revision 1.98  2004/06/16 21:24:31  rurban
2326 // do not display no-connect warning: #2662
2327 //
2328 // Revision 1.97  2004/06/16 13:21:16  rurban
2329 // stabilize on failing ldap queries or bind
2330 //
2331 // Revision 1.96  2004/06/16 12:42:06  rurban
2332 // fix homepage prefs
2333 //
2334 // Revision 1.95  2004/06/16 10:38:58  rurban
2335 // Disallow refernces in calls if the declaration is a reference
2336 // ("allow_call_time_pass_reference clean").
2337 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
2338 //   but several external libraries may not.
2339 //   In detail these libs look to be affected (not tested):
2340 //   * Pear_DB odbc
2341 //   * adodb oracle
2342 //
2343 // Revision 1.94  2004/06/15 10:40:35  rurban
2344 // minor WikiGroup cleanup: no request param, start of current user independency
2345 //
2346 // Revision 1.93  2004/06/15 09:15:52  rurban
2347 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
2348 //   fix encrypted usage, actually store and retrieve them from db
2349 //   fix bogologin with passwd set.
2350 // fix php crashes with call-time pass-by-reference (references wrongly used
2351 //   in declaration AND call). This affected mainly Apache2 and IIS.
2352 //   (Thanks to John Cole to detect this!)
2353 //
2354 // Revision 1.92  2004/06/14 11:31:36  rurban
2355 // renamed global $Theme to $WikiTheme (gforge nameclash)
2356 // inherit PageList default options from PageList
2357 //   default sortby=pagename
2358 // use options in PageList_Selectable (limit, sortby, ...)
2359 // added action revert, with button at action=diff
2360 // added option regex to WikiAdminSearchReplace
2361 //
2362 // Revision 1.91  2004/06/08 14:57:43  rurban
2363 // stupid ldap bug detected by John Cole
2364 //
2365 // Revision 1.90  2004/06/08 09:31:15  rurban
2366 // fixed typo detected by lucidcarbon (line 1663 assertion)
2367 //
2368 // Revision 1.89  2004/06/06 16:58:51  rurban
2369 // added more required ActionPages for foreign languages
2370 // install now english ActionPages if no localized are found. (again)
2371 // fixed default anon user level to be 0, instead of -1
2372 //   (wrong "required administrator to view this page"...)
2373 //
2374 // Revision 1.88  2004/06/04 20:32:53  rurban
2375 // Several locale related improvements suggested by Pierrick Meignen
2376 // LDAP fix by John Cole
2377 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2378 //
2379 // Revision 1.87  2004/06/04 12:40:21  rurban
2380 // Restrict valid usernames to prevent from attacks against external auth or compromise
2381 // possible holes.
2382 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
2383 // Fxied more warnings
2384 //
2385 // Revision 1.86  2004/06/03 18:06:29  rurban
2386 // fix file locking issues (only needed on write)
2387 // fixed immediate LANG and THEME in-session updates if not stored in prefs
2388 // advanced editpage toolbars (search & replace broken)
2389 //
2390 // Revision 1.85  2004/06/03 12:46:03  rurban
2391 // fix signout, level must be 0 not -1
2392 //
2393 // Revision 1.84  2004/06/03 12:36:03  rurban
2394 // fix eval warning on signin
2395 //
2396 // Revision 1.83  2004/06/03 10:18:19  rurban
2397 // fix User locking issues, new config ENABLE_PAGEPERM
2398 //
2399 // Revision 1.82  2004/06/03 09:39:51  rurban
2400 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
2401 //
2402 // Revision 1.81  2004/06/02 18:01:45  rurban
2403 // init global FileFinder to add proper include paths at startup
2404 //   adds PHPWIKI_DIR if started from another dir, lib/pear also
2405 // fix slashify for Windows
2406 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
2407 //
2408 // Revision 1.80  2004/06/02 14:20:27  rurban
2409 // fix adodb DbPassUser login
2410 //
2411 // Revision 1.79  2004/06/01 15:27:59  rurban
2412 // AdminUser only ADMIN_USER not member of Administrators
2413 // some RateIt improvements by dfrankow
2414 // edit_toolbar buttons
2415 //
2416 // Revision 1.78  2004/05/27 17:49:06  rurban
2417 // renamed DB_Session to DbSession (in CVS also)
2418 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
2419 // remove leading slash in error message
2420 // added force_unlock parameter to File_Passwd (no return on stale locks)
2421 // fixed adodb session AffectedRows
2422 // added FileFinder helpers to unify local filenames and DATA_PATH names
2423 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
2424 //
2425 // Revision 1.77  2004/05/18 14:49:51  rurban
2426 // Simplified strings for easier translation
2427 //
2428 // Revision 1.76  2004/05/18 13:30:04  rurban
2429 // prevent from endless loop with oldstyle warnings
2430 //
2431 // Revision 1.75  2004/05/16 22:07:35  rurban
2432 // check more config-default and predefined constants
2433 // various PagePerm fixes:
2434 //   fix default PagePerms, esp. edit and view for Bogo and Password users
2435 //   implemented Creator and Owner
2436 //   BOGOUSERS renamed to BOGOUSER
2437 // fixed syntax errors in signin.tmpl
2438 //
2439 // Revision 1.74  2004/05/15 19:48:33  rurban
2440 // fix some too loose PagePerms for signed, but not authenticated users
2441 //  (admin, owner, creator)
2442 // no double login page header, better login msg.
2443 // moved action_pdf to lib/pdf.php
2444 //
2445 // Revision 1.73  2004/05/15 18:31:01  rurban
2446 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
2447 //
2448 // Revision 1.72  2004/05/12 10:49:55  rurban
2449 // require_once fix for those libs which are loaded before FileFinder and
2450 //   its automatic include_path fix, and where require_once doesn't grok
2451 //   dirname(__FILE__) != './lib'
2452 // upgrade fix with PearDB
2453 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2454 //
2455 // Revision 1.71  2004/05/10 12:34:47  rurban
2456 // stabilize DbAuthParam statement pre-prozessor:
2457 //   try old-style and new-style (double-)quoting
2458 //   reject unknown $variables
2459 //   use ->prepare() for all calls (again)
2460 //
2461 // Revision 1.70  2004/05/06 19:26:16  rurban
2462 // improve stability, trying to find the InlineParser endless loop on sf.net
2463 //
2464 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
2465 //
2466 // Revision 1.69  2004/05/06 13:56:40  rurban
2467 // Enable the Administrators group, and add the WIKIPAGE group default root page.
2468 //
2469 // Revision 1.68  2004/05/05 13:37:54  rurban
2470 // Support to remove all UserPreferences
2471 //
2472 // Revision 1.66  2004/05/03 21:44:24  rurban
2473 // fixed sf,net bug #947264: LDAP options are constants, not strings!
2474 //
2475 // Revision 1.65  2004/05/03 13:16:47  rurban
2476 // fixed UserPreferences update, esp for boolean and int
2477 //
2478 // Revision 1.64  2004/05/02 15:10:06  rurban
2479 // new finally reliable way to detect if /index.php is called directly
2480 //   and if to include lib/main.php
2481 // new global AllActionPages
2482 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
2483 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
2484 // PageGroupTestOne => subpages
2485 // renamed PhpWikiRss to PhpWikiRecentChanges
2486 // more docs, default configs, ...
2487 //
2488 // Revision 1.63  2004/05/01 15:59:29  rurban
2489 // more php-4.0.6 compatibility: superglobals
2490 //
2491 // Revision 1.62  2004/04/29 18:31:24  rurban
2492 // Prevent from warning where no db pref was previously stored.
2493 //
2494 // Revision 1.61  2004/04/29 17:18:19  zorloc
2495 // 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.
2496 //
2497 // Revision 1.60  2004/04/27 18:20:54  rurban
2498 // sf.net patch #940359 by rassie
2499 //
2500 // Revision 1.59  2004/04/26 12:35:21  rurban
2501 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
2502 // File_Passwd is already loaded
2503 //
2504 // Revision 1.58  2004/04/20 17:08:28  rurban
2505 // Some IniConfig fixes: prepend our private lib/pear dir
2506 //   switch from " to ' in the auth statements
2507 //   use error handling.
2508 // WikiUserNew changes for the new "'$variable'" syntax
2509 //   in the statements
2510 // TODO: optimization to put config vars into the session.
2511 //
2512 // Revision 1.57  2004/04/19 18:27:45  rurban
2513 // Prevent from some PHP5 warnings (ref args, no :: object init)
2514 //   php5 runs now through, just one wrong XmlElement object init missing
2515 // Removed unneccesary UpgradeUser lines
2516 // Changed WikiLink to omit version if current (RecentChanges)
2517 //
2518 // Revision 1.56  2004/04/19 09:13:24  rurban
2519 // new pref: googleLink
2520 //
2521 // Revision 1.54  2004/04/18 00:24:45  rurban
2522 // re-use our simple prepare: just for table prefix warnings
2523 //
2524 // Revision 1.53  2004/04/12 18:29:15  rurban
2525 // exp. Session auth for already authenticated users from another app
2526 //
2527 // Revision 1.52  2004/04/12 13:04:50  rurban
2528 // added auth_create: self-registering Db users
2529 // fixed IMAP auth
2530 // removed rating recommendations
2531 // ziplib reformatting
2532 //
2533 // Revision 1.51  2004/04/11 10:42:02  rurban
2534 // pgsrc/CreatePagePlugin
2535 //
2536 // Revision 1.50  2004/04/10 05:34:35  rurban
2537 // sf bug#830912
2538 //
2539 // Revision 1.49  2004/04/07 23:13:18  rurban
2540 // fixed pear/File_Passwd for Windows
2541 // fixed FilePassUser sessions (filehandle revive) and password update
2542 //
2543 // Revision 1.48  2004/04/06 20:00:10  rurban
2544 // Cleanup of special PageList column types
2545 // Added support of plugin and theme specific Pagelist Types
2546 // Added support for theme specific UserPreferences
2547 // Added session support for ip-based throttling
2548 //   sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
2549 // Enhanced postgres schema
2550 // Added DB_Session_dba support
2551 //
2552 // Revision 1.47  2004/04/02 15:06:55  rurban
2553 // fixed a nasty ADODB_mysql session update bug
2554 // improved UserPreferences layout (tabled hints)
2555 // fixed UserPreferences auth handling
2556 // improved auth stability
2557 // improved old cookie handling: fixed deletion of old cookies with paths
2558 //
2559 // Revision 1.46  2004/04/01 06:29:51  rurban
2560 // better wording
2561 // RateIt also for ADODB
2562 //
2563
2564 // Local Variables:
2565 // mode: php
2566 // tab-width: 8
2567 // c-basic-offset: 4
2568 // c-hanging-comment-ender-p: nil
2569 // indent-tabs-mode: nil
2570 // End:
2571 ?>