]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Add braces
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php
2 /* Copyright (C) 2004,2005,2006,2007,2009,2010 $ThePhpWikiProgrammingTeam
3  * Copyright (C) 2009-2010 Marc-Etienne Vargenau, Alcatel-Lucent
4  * Copyright (C) 2009-2010 Roger Guignard, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * This is a complete OOP rewrite of the old WikiUser code with various
25  * configurable external authentication methods.
26  *
27  * There's only one entry point, the function WikiUser which returns
28  * a WikiUser object, which contains the name, authlevel and user's preferences.
29  * This object might get upgraded during the login step and later also.
30  * There exist three preferences storage methods: cookie, homepage and db,
31  * and multiple password checking methods.
32  * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if
33  * ALLOW_USER_PASSWORDS is defined.
34  *
35  * Each user object must define the two preferences methods
36  *  getPreferences(), setPreferences(),
37  * and the following 1-4 auth methods
38  *  checkPass()  must be defined by all classes,
39  *  userExists() only if USER_AUTH_POLICY'=='strict'
40  *  mayChangePass()  only if the password is storable.
41  *  storePass()  only if the password is storable.
42  *
43  * WikiUser() given no name, returns an _AnonUser (anonymous user)
44  * object, who may or may not have a cookie.
45  * However, if the there's a cookie with the userid or a session,
46  * the user is upgraded to the matching user object.
47  * Given a user name, returns a _BogoUser object, who may or may not
48  * have a cookie and/or PersonalPage, one of the various _PassUser objects
49  * or an _AdminUser object.
50  * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might
51  * have stored a password or not. If so, his account is secure, if not
52  * anybody can use it, because the username is visible e.g. in RecentChanges.
53  *
54  * Takes care of passwords, all preference loading/storing in the
55  * user's page and any cookies. lib/main.php will query the user object to
56  * verify the password as appropriate.
57  *
58  * @author: Reini Urban (the tricky parts),
59  *          Carsten Klapp (started rolling the ball)
60  *
61  * Random architectural notes, sorted by date:
62  * 2004-01-25 rurban
63  * 1) Now a ForbiddenUser is returned instead of false.
64  * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
65  *    but may browse. Now with ALLOW_ANON_USER = false he may not browse,
66  *    which is needed to disable browse PagePermissions.
67  *    I added now ALLOW_ANON_EDIT = true to makes things clear.
68  *    (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
69  * 2004-02-27 rurban:
70  * 3) Removed pear prepare. Performance hog, and using integers as
71  *    handler doesn't help. Do simple sprintf as with adodb. And a prepare
72  *    in the object init is no advantage, because in the init loop a lot of
73  *    objects are tried, but not used.
74  * 4) Already gotten prefs are passed to the next object to avoid
75  *    duplicate getPreferences() calls.
76  * 2004-03-18 rurban
77  * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
78  *    So we cannot just discrimate with
79  *      if (!check_php_version(5))
80  *          $this = $user;
81  *    A /php5-patch.php is provided, which patches the src automatically
82  *    for php4 and php5. Default is php4.
83  *    Update: not needed anymore. we use eval to fool the load-time syntax checker.
84  * 2004-03-24 rurban
85  * 6) enforced new cookie policy: prefs don't get stored in cookies
86  *    anymore, only in homepage and/or database, but always in the
87  *    current session. old pref cookies will get deleted.
88  * 2004-04-04 rurban
89  * 7) Certain themes should be able to extend the predefined list
90  *    of preferences. Display/editing is done in the theme specific userprefs.tmpl,
91  *    but storage must be extended to the Get/SetPreferences methods.
92  *    <theme>/themeinfo.php must provide CustomUserPreferences:
93  *      A list of name => _UserPreference class pairs.
94  * 2010-06-07 rurban
95  *    Fixed a nasty recursion bug (i.e. php crash), when user = new class
96  *    which returned false, did not return false on php-4.4.7. Check for
97  *    a object member now.
98  */
99
100 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
101 define('WIKIAUTH_ANON', 0); // Not signed in.
102 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
103 define('WIKIAUTH_USER', 2); // Bogo user with a password.
104 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
105 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
106
107 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
108 //if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
109 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
110 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
111 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
112
113 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
114 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
115 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
116
117 define('TIMEOFFSET_MIN_HOURS', -26);
118 define('TIMEOFFSET_MAX_HOURS', 26);
119 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
120
121 /* EMAIL VERIFICATION
122  * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
123  * Provide some overrides here.
124  *    ( username @ ) domain => mail-domain
125  */
126 $EMailHosts = array('avl.com' => 'mail.avl.com');
127
128 /**
129  * There are be the following constants in config/config.ini to
130  * establish login parameters:
131  *
132  * ALLOW_ANON_USER         default true
133  * ALLOW_ANON_EDIT         default true
134  * ALLOW_BOGO_LOGIN        default true
135  * ALLOW_USER_PASSWORDS    default true
136  * PASSWORD_LENGTH_MINIMUM default 0
137  *
138  * To require user passwords for editing:
139  * ALLOW_ANON_USER  = true
140  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
141  * ALLOW_BOGO_LOGIN = false
142  * ALLOW_USER_PASSWORDS = true
143  *
144  * To establish a COMPLETELY private wiki, such as an internal
145  * corporate one:
146  * ALLOW_ANON_USER = false
147  * (and probably require user passwords as described above). In this
148  * case the user will be prompted to login immediately upon accessing
149  * any page.
150  *
151  * There are other possible combinations, but the typical wiki (such
152  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
153  * enabled.
154  *
155  */
156
157 // The last object in the row is the bad guy...
158 if (!is_array($USER_AUTH_ORDER))
159     $USER_AUTH_ORDER = array("Forbidden");
160 else
161     $USER_AUTH_ORDER[] = "Forbidden";
162
163 // Local convenience functions.
164 function _isAnonUserAllowed()
165 {
166     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
167 }
168
169 function _isBogoUserAllowed()
170 {
171     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
172 }
173
174 function _isUserPasswordsAllowed()
175 {
176     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
177 }
178
179 // Possibly upgrade userobject functions.
180 function _determineAdminUserOrOtherUser($UserName)
181 {
182     // Sanity check. User name is a condition of the definition of the
183     // _AdminUser, _BogoUser and _passuser.
184     if (!$UserName)
185         return $GLOBALS['ForbiddenUser'];
186
187     //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
188     //$group = &WikiGroup::getGroup($GLOBALS['request']);
189     if ($UserName == ADMIN_USER)
190         return new _AdminUser($UserName);
191     /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
192         return _determineBogoUserOrPassUser($UserName);
193     }
194     */
195     else
196         return _determineBogoUserOrPassUser($UserName);
197 }
198
199 function _determineBogoUserOrPassUser($UserName)
200 {
201     global $ForbiddenUser;
202
203     // Sanity check. User name is a condition of the definition of
204     // _BogoUser and _PassUser.
205     if (!$UserName)
206         return $ForbiddenUser;
207
208     // Check for password and possibly upgrade user object.
209     // $_BogoUser = new _BogoUser($UserName);
210     if (_isBogoUserAllowed() and isWikiWord($UserName)) {
211         include_once 'lib/WikiUser/BogoLogin.php';
212         $_BogoUser = new _BogoLoginPassUser($UserName);
213         if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
214             return $_BogoUser;
215     }
216     if (_isUserPasswordsAllowed()) {
217         // PassUsers override BogoUsers if a password is stored
218         if (isset($_BogoUser) and isset($_BogoUser->_prefs)
219             and $_BogoUser->_prefs->get('passwd')
220         )
221             return new _PassUser($UserName, $_BogoUser->_prefs);
222         else {
223             $_PassUser = new _PassUser($UserName,
224                 isset($_BogoUser) ? $_BogoUser->_prefs : false);
225             if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
226                 if (isset($GLOBALS['request']->_user_class))
227                     $class = $GLOBALS['request']->_user_class;
228                 elseif (strtolower(get_class($_PassUser)) == "_passuser")
229                     $class = $_PassUser->nextClass(); else
230                     $class = get_class($_PassUser);
231                 if ($user = new $class($UserName, $_PassUser->_prefs)
232                     and $user->_userid
233                 ) {
234                     return $user;
235                 } else {
236                     return $_PassUser;
237                 }
238             }
239         }
240     }
241     // No Bogo- or PassUser exists, or
242     // passwords are not allowed, and bogo is disallowed too.
243     // (Only the admin can sign in).
244     return $ForbiddenUser;
245 }
246
247 /**
248  * Primary WikiUser function, called by lib/main.php.
249  *
250  * This determines the user's type and returns an appropriate user
251  * object. lib/main.php then querys the resultant object for password
252  * validity as necessary.
253  *
254  * If an _AnonUser object is returned, the user may only browse pages
255  * (and save prefs in a cookie).
256  *
257  * To disable access but provide prefs the global $ForbiddenUser class
258  * is returned. (was previously false)
259  *
260  */
261 function WikiUser($UserName = '')
262 {
263     global $ForbiddenUser, $HTTP_SESSION_VARS;
264
265     //Maybe: Check sessionvar for username & save username into
266     //sessionvar (may be more appropriate to do this in lib/main.php).
267     if ($UserName) {
268         $ForbiddenUser = new _ForbiddenUser($UserName);
269         // Found a user name.
270         return _determineAdminUserOrOtherUser($UserName);
271     } elseif (!empty($HTTP_SESSION_VARS['userid'])) {
272         // Found a user name.
273         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
274         return _determineAdminUserOrOtherUser($_SESSION['userid']);
275     } else {
276         // Check for autologin pref in cookie and possibly upgrade
277         // user object to another type.
278         $_AnonUser = new _AnonUser();
279         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
280             // Found a user name.
281             $ForbiddenUser = new _ForbiddenUser($UserName);
282             return _determineAdminUserOrOtherUser($UserName);
283         } else {
284             $ForbiddenUser = new _ForbiddenUser();
285             if (_isAnonUserAllowed())
286                 return $_AnonUser;
287             return $ForbiddenUser; // User must sign in to browse pages.
288         }
289     }
290 }
291
292 /**
293  * WikiUser.php use the name 'WikiUser'
294  */
295 function WikiUserClassname()
296 {
297     return '_WikiUser';
298 }
299
300 /**
301  * Upgrade olduser by copying properties from user to olduser.
302  * We are not sure yet, for which php's a simple $this = $user works reliably,
303  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
304  * that's why try it the hard way.
305  */
306 function UpgradeUser($user, $newuser)
307 {
308     if (is_a($user, '_WikiUser') and is_a($newuser, '_WikiUser')) {
309         // populate the upgraded class $newuser with the values from the current user object
310         //only _auth_level, _current_method, _current_index,
311         if (!empty($user->_level) and
312             $user->_level > $newuser->_level
313         )
314             $newuser->_level = $user->_level;
315         if (!empty($user->_current_index) and
316             $user->_current_index > $newuser->_current_index
317         ) {
318             $newuser->_current_index = $user->_current_index;
319             $newuser->_current_method = $user->_current_method;
320         }
321         if (!empty($user->_authmethod))
322             $newuser->_authmethod = $user->_authmethod;
323         $GLOBALS['request']->_user_class = get_class($newuser);
324         /*
325         foreach (get_object_vars($user) as $k => $v) {
326             if (!empty($v)) $olduser->$k = $v;
327         }
328         */
329         $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
330         //$GLOBALS['request']->_user = $olduser;
331         return $newuser;
332     } else {
333         return false;
334     }
335 }
336
337 /**
338  * Probably not needed, since we use the various user objects methods so far.
339  * Anyway, here it is, looping through all available objects.
340  */
341 function UserExists($UserName)
342 {
343     global $request;
344     if (!($user = $request->getUser()))
345         $user = WikiUser($UserName);
346     if (!$user)
347         return false;
348     if ($user->userExists($UserName)) {
349         $request->_user = $user;
350         return true;
351     }
352     if (is_a($user, '_BogoUser'))
353         $user = new _PassUser($UserName, $user->_prefs);
354     $class = $user->nextClass();
355     if ($user = new $class($UserName, $user->_prefs)) {
356         return $user->userExists($UserName);
357     }
358     $request->_user = $GLOBALS['ForbiddenUser'];
359     return false;
360 }
361
362 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
363
364 /**
365  * Base WikiUser class.
366  */
367 class _WikiUser
368 {
369     public $_userid = '';
370     public $_level = WIKIAUTH_ANON;
371     public $_prefs = false;
372     public $_HomePagehandle = false;
373
374     // constructor
375     function _WikiUser($UserName = '', $prefs = false)
376     {
377
378         $this->_userid = $UserName;
379         $this->_HomePagehandle = false;
380         if ($UserName) {
381             $this->hasHomePage();
382         }
383         if (empty($this->_prefs)) {
384             if ($prefs) $this->_prefs = $prefs;
385             else $this->getPreferences();
386         }
387     }
388
389     function UserName()
390     {
391         if (!empty($this->_userid)) {
392             return $this->_userid;
393         } else {
394             return '';
395         }
396     }
397
398     function getPreferences()
399     {
400         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
401             . "New subclasses of _WikiUser must override this function.");
402         return false;
403     }
404
405     function setPreferences($prefs, $id_only)
406     {
407         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
408             . " "
409             . "New subclasses of _WikiUser must override this function.");
410         return false;
411     }
412
413     function userExists()
414     {
415         return $this->hasHomePage();
416     }
417
418     function checkPass($submitted_password)
419     {
420         // By definition, an undefined user class cannot sign in.
421         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
422             . " "
423             . "New subclasses of _WikiUser must override this function.");
424         return false;
425     }
426
427     // returns page_handle to user's home page or false if none
428     function hasHomePage()
429     {
430         if ($this->_userid) {
431             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
432                 return $this->_HomePagehandle->exists();
433             } else {
434                 // check db again (maybe someone else created it since
435                 // we logged in.)
436                 global $request;
437                 $this->_HomePagehandle = $request->getPage($this->_userid);
438                 return $this->_HomePagehandle->exists();
439             }
440         }
441         // nope
442         return false;
443     }
444
445     function createHomePage()
446     {
447         global $request;
448         $versiondata = array('author' => ADMIN_USER);
449         $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.") .
450                 "\n{{Template/UserPage}}",
451             1, $versiondata);
452         $request->_dbi->touch();
453         $this->_HomePagehandle = $request->getPage($this->_userid);
454     }
455
456     // innocent helper: case-insensitive position in _auth_methods
457     function array_position($string, $array)
458     {
459         $string = strtolower($string);
460         for ($found = 0; $found < count($array); $found++) {
461             if (strtolower($array[$found]) == $string)
462                 return $found;
463         }
464         return false;
465     }
466
467     function nextAuthMethodIndex()
468     {
469         if (empty($this->_auth_methods))
470             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
471         if (empty($this->_current_index)) {
472             if (strtolower(get_class($this)) != '_passuser') {
473                 $this->_current_method = substr(get_class($this), 1, -8);
474                 $this->_current_index = $this->array_position($this->_current_method,
475                     $this->_auth_methods);
476             } else {
477                 $this->_current_index = -1;
478             }
479         }
480         $this->_current_index++;
481         if ($this->_current_index >= count($this->_auth_methods))
482             return false;
483         $this->_current_method = $this->_auth_methods[$this->_current_index];
484         return $this->_current_index;
485     }
486
487     function AuthMethod($index = false)
488     {
489         return $this->_auth_methods[$index === false
490             ? count($this->_auth_methods) - 1
491             : $index];
492     }
493
494     // upgrade the user object
495     function nextClass()
496     {
497         $method = $this->AuthMethod($this->nextAuthMethodIndex());
498         include_once("lib/WikiUser/$method.php");
499         return "_" . $method . "PassUser";
500     }
501
502     //Fixme: for _HttpAuthPassUser
503     function PrintLoginForm(&$request, $args, $fail_message = false,
504                             $separate_page = false)
505     {
506         include_once 'lib/Template.php';
507         // Call update_locale in case the system's default language is not 'en'.
508         // (We have no user pref for lang at this point yet, no one is logged in.)
509         if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
510             update_locale(DEFAULT_LANGUAGE);
511         $userid = $this->_userid;
512         $require_level = 0;
513         extract($args); // fixme
514
515         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
516
517         $pagename = $request->getArg('pagename');
518         $nocache = 1;
519         $login = Template('login',
520             compact('pagename', 'userid', 'require_level',
521                 'fail_message', 'pass_required', 'nocache'));
522         // check if the html template was already processed
523         $separate_page = $separate_page ? true : !alreadyTemplateProcessed('html');
524         if ($separate_page) {
525             $page = $request->getPage($pagename);
526             $revision = $page->getCurrentRevision();
527             return GeneratePage($login, _("Sign In"), $revision);
528         } else {
529             return $login->printExpansion();
530         }
531     }
532
533     /** Signed in but not password checked or empty password.
534      */
535     function isSignedIn()
536     {
537         return (is_a($this, '_BogoUser') or is_a($this, '_PassUser'));
538     }
539
540     /** This is password checked for sure.
541      */
542     function isAuthenticated()
543     {
544         //return is_a($this,'_PassUser');
545         //return is_a($this,'_BogoUser') || is_a($this,'_PassUser');
546         return $this->_level >= WIKIAUTH_BOGO;
547     }
548
549     function isAdmin()
550     {
551         static $group;
552         if ($this->_level == WIKIAUTH_ADMIN) return true;
553         if (!$this->isSignedIn()) return false;
554         if (!$this->isAuthenticated()) return false;
555
556         if (!$group) $group = &$GLOBALS['request']->getGroup();
557         return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
558     }
559
560     /** Name or IP for a signed user. UserName could come from a cookie e.g.
561      */
562     function getId()
563     {
564         return ($this->UserName()
565             ? $this->UserName()
566             : $GLOBALS['request']->get('REMOTE_ADDR'));
567     }
568
569     /** Name for an authenticated user. No IP here.
570      */
571     function getAuthenticatedId()
572     {
573         return ($this->isAuthenticated()
574             ? $this->_userid
575             : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
576     }
577
578     function hasAuthority($require_level)
579     {
580         return $this->_level >= $require_level;
581     }
582
583     /* This is quite restrictive and not according the login description online.
584        Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
585        The backends may loosen or tighten this.
586     */
587     function isValidName($userid = false)
588     {
589         if (!$userid) $userid = $this->_userid;
590         if (!$userid) return false;
591         if (defined('FUSIONFORGE') and FUSIONFORGE) {
592             return true;
593         }
594         return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
595     }
596
597     /**
598      * Called on an auth_args POST request, such as login, logout or signin.
599      * TODO: Check BogoLogin users with empty password. (self-signed users)
600      */
601     function AuthCheck($postargs)
602     {
603         // Normalize args, and extract.
604         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
605             'cancel');
606         foreach ($keys as $key)
607             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
608         extract($args);
609         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
610
611         if ($logout) { // Log out
612             if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
613                 global $request;
614                 $zone_offset = Request_AccessLogEntry::_zone_offset();
615                 $ncsa_time = date("d/M/Y:H:i:s", time());
616                 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
617                     (string)$request->get('REMOTE_HOST'),
618                     (string)$request->_user->_userid,
619                     $ncsa_time, $zone_offset,
620                     "logout " . get_class($request->_user),
621                     "401",
622                     (string)$request->get('HTTP_REFERER'),
623                     (string)$request->get('HTTP_USER_AGENT')
624                 );
625                 if (($fp = fopen(LOGIN_LOG, "a"))) {
626                     flock($fp, LOCK_EX);
627                     fputs($fp, "$entry\n");
628                     fclose($fp);
629                 }
630                 //error_log("$entry\n", 3, LOGIN_LOG);
631             }
632             if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
633                 $GLOBALS['request']->_user->logout();
634             }
635             $user = new _AnonUser();
636             $user->_userid = '';
637             $user->_level = WIKIAUTH_ANON;
638             return $user;
639         } elseif ($cancel)
640             return false; // User hit cancel button.
641         elseif (!$login && !$userid)
642             return false; // Nothing to do?
643
644         if (!$this->isValidName($userid))
645             return _("Invalid username.");
646         ;
647
648         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
649
650         if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
651             global $request;
652             $zone_offset = Request_AccessLogEntry::_zone_offset();
653             $ncsa_time = date("d/M/Y:H:i:s", time());
654             $manglepasswd = $passwd;
655             for ($i = 0; $i < strlen($manglepasswd); $i++) {
656                 $c = substr($manglepasswd, $i, 1);
657                 if (ord($c) < 32) $manglepasswd[$i] = "<";
658                 elseif ($c == '*') $manglepasswd[$i] = "*"; elseif ($c == '?') $manglepasswd[$i] = "?"; elseif ($c == '(') $manglepasswd[$i] = "("; elseif ($c == ')') $manglepasswd[$i] = ")"; elseif ($c == "\\") $manglepasswd[$i] = "\\"; elseif (ord($c) < 127) $manglepasswd[$i] = "x"; elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
659             }
660             if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
661             $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
662                 $request->get('REMOTE_HOST'),
663                 (string)$request->_user->_userid,
664                 $ncsa_time, $zone_offset,
665                 "login $userid/$manglepasswd => $authlevel " . get_class($request->_user),
666                 $authlevel > 0 ? "200" : "403",
667                 (string)$request->get('HTTP_REFERER'),
668                 (string)$request->get('HTTP_USER_AGENT')
669             );
670             if (($fp = fopen(LOGIN_LOG, "a"))) {
671                 flock($fp, LOCK_EX);
672                 fputs($fp, "$entry\n");
673                 fclose($fp);
674             }
675             //error_log("$entry\n", 3, LOGIN_LOG);
676         }
677
678         if ($authlevel <= 0) { // anon or forbidden
679             if ($passwd)
680                 return _("Invalid password.");
681             else
682                 return _("Invalid password or userid.");
683         } elseif ($authlevel < $require_level) { // auth ok, but not enough
684             if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') {
685                 // upgrade class
686                 $class = "_" . $this->_current_method . "PassUser";
687                 include_once 'lib/WikiUser/' . $this->_current_method . '.php';
688                 $user = new $class($userid, $this->_prefs);
689                 $this->_level = $authlevel;
690                 return $user;
691             }
692             $this->_userid = $userid;
693             $this->_level = $authlevel;
694             return _("Insufficient permissions.");
695         }
696
697         // Successful login.
698         //$user = $GLOBALS['request']->_user;
699         if (!empty($this->_current_method) and
700             strtolower(get_class($this)) == '_passuser'
701         ) {
702             // upgrade class
703             $class = "_" . $this->_current_method . "PassUser";
704             include_once 'lib/WikiUser/' . $this->_current_method . '.php';
705             $user = new $class($userid, $this->_prefs);
706             $user->_level = $authlevel;
707             return $user;
708         }
709         $this->_userid = $userid;
710         $this->_level = $authlevel;
711         return $this;
712     }
713
714 }
715
716 /**
717  * Not authenticated in user, but he may be signed in. Basicly with view access only.
718  * prefs are stored in cookies, but only the userid.
719  */
720 class _AnonUser
721     extends _WikiUser
722 {
723     public $_level = WIKIAUTH_ANON;
724
725     /** Anon only gets to load and save prefs in a cookie, that's it.
726      */
727     function getPreferences()
728     {
729         global $request;
730
731         if (empty($this->_prefs))
732             $this->_prefs = new UserPreferences;
733         $UserName = $this->UserName();
734
735         // Try to read deprecated 1.3.x style cookies
736         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
737             if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
738                 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
739                         . "\n"
740                         . sprintf("%s='%s'", WIKI_NAME, $cookie)
741                         . "\n"
742                         . _("Default preferences will be used."),
743                     E_USER_NOTICE);
744             }
745             /**
746              * Only set if it matches the UserName who is
747              * signing in or if this really is an Anon login (no
748              * username). (Remember, _BogoUser and higher inherit this
749              * function too!).
750              */
751             if (!$UserName || $UserName == @$unboxedcookie['userid']) {
752                 $this->_prefs->updatePrefs($unboxedcookie);
753                 $UserName = @$unboxedcookie['userid'];
754                 if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
755                     $this->_userid = $UserName;
756                 else
757                     $UserName = false;
758             }
759             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
760             if (!headers_sent())
761                 $request->deleteCookieVar(WIKI_NAME);
762         }
763         // Try to read deprecated 1.3.4 style cookies
764         if (!$UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
765             if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
766                 if (!$UserName || $UserName == $unboxedcookie['userid']) {
767                     $this->_prefs->updatePrefs($unboxedcookie);
768                     $UserName = $unboxedcookie['userid'];
769                     if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
770                         $this->_userid = $UserName;
771                     else
772                         $UserName = false;
773                 }
774                 if (!headers_sent())
775                     $request->deleteCookieVar("WIKI_PREF2");
776             }
777         }
778         if (!$UserName) {
779             // Try reading userid from old PhpWiki cookie formats:
780             if ($cookie = $request->cookies->get_old(getCookieName())) {
781                 if (is_string($cookie) and (substr($cookie, 0, 2) != 's:'))
782                     $UserName = $cookie;
783                 elseif (is_array($cookie) and !empty($cookie['userid']))
784                     $UserName = $cookie['userid'];
785             }
786             if (!$UserName and !headers_sent())
787                 $request->deleteCookieVar(getCookieName());
788             else
789                 $this->_userid = $UserName;
790         }
791
792         // initializeTheme() needs at least an empty object
793         /*
794          if (empty($this->_prefs))
795             $this->_prefs = new UserPreferences;
796         */
797         return $this->_prefs;
798     }
799
800     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
801      *
802      * Allow for multiple wikis in same domain. Encode only the
803      * _prefs array of the UserPreference object. Ideally the
804      * prefs array should just be imploded into a single string or
805      * something so it is completely human readable by the end
806      * user. In that case stricter error checking will be needed
807      * when loading the cookie.
808      */
809     function setPreferences($prefs, $id_only = false)
810     {
811         if (!is_object($prefs)) {
812             if (is_object($this->_prefs)) {
813                 $updated = $this->_prefs->updatePrefs($prefs);
814                 $prefs =& $this->_prefs;
815             } else {
816                 // update the prefs values from scratch. This could lead to unnecessary
817                 // side-effects: duplicate emailVerified, ...
818                 $this->_prefs = new UserPreferences($prefs);
819                 $updated = true;
820             }
821         } else {
822             if (!isset($this->_prefs))
823                 $this->_prefs =& $prefs;
824             else
825                 $updated = $this->_prefs->isChanged($prefs);
826         }
827         if ($updated) {
828             if ($id_only and !headers_sent()) {
829                 global $request;
830                 // new 1.3.8 policy: no array cookies, only plain userid string as in
831                 // the pre 1.3.x versions.
832                 // prefs should be stored besides the session in the homepagehandle or in a db.
833                 $request->setCookieVar(getCookieName(), $this->_userid,
834                     COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
835                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
836                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
837             }
838         }
839         if (is_object($prefs)) {
840             $packed = $prefs->store();
841             $unpacked = $prefs->unpack($packed);
842             if (count($unpacked)) {
843                 foreach (array('_method', '_select', '_update', '_insert') as $param) {
844                     if (!empty($this->_prefs->{$param}))
845                         $prefs->{$param} = $this->_prefs->{$param};
846                 }
847                 $this->_prefs = $prefs;
848             }
849         }
850         return $updated;
851     }
852
853     function userExists()
854     {
855         return true;
856     }
857
858     function checkPass($submitted_password)
859     {
860         return false;
861     }
862
863 }
864
865 /**
866  * Helper class to finish the PassUser auth loop.
867  * This is added automatically to USER_AUTH_ORDER.
868  */
869 class _ForbiddenUser
870     extends _AnonUser
871 {
872     public $_level = WIKIAUTH_FORBIDDEN;
873
874     function checkPass($submitted_password)
875     {
876         return WIKIAUTH_FORBIDDEN;
877     }
878
879     function userExists()
880     {
881         if ($this->_HomePagehandle) return true;
882         return false;
883     }
884 }
885
886 /**
887  * Do NOT extend _BogoUser to other classes, for checkPass()
888  * security. (In case of defects in code logic of the new class!)
889  * The intermediate step between anon and passuser.
890  * We also have the _BogoLoginPassUser class with stricter
891  * password checking, which fits into the auth loop.
892  * Note: This class is not called anymore by WikiUser()
893  */
894 class _BogoUser
895     extends _AnonUser
896 {
897     function userExists()
898     {
899         if (isWikiWord($this->_userid)) {
900             $this->_level = WIKIAUTH_BOGO;
901             return true;
902         } else {
903             $this->_level = WIKIAUTH_ANON;
904             return false;
905         }
906     }
907
908     function checkPass($submitted_password)
909     {
910         // By definition, BogoUser has an empty password.
911         $this->userExists();
912         return $this->_level;
913     }
914 }
915
916 class _PassUser
917     extends _AnonUser
918     /**
919      * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
920      *
921      * The classes for all subsequent auth methods extend from this class.
922      * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
923      * the three auth method policies first-only, strict and stacked
924      * and the two methods for prefs: homepage or database,
925      * if $DBAuthParams['pref_select'] is defined.
926      *
927      * Default is PersonalPage auth and prefs.
928      *
929      * @author: Reini Urban
930      * @tables: pref
931      */
932 {
933     public $_auth_dbi, $_prefs;
934     public $_current_method, $_current_index;
935
936     // check and prepare the auth and pref methods only once
937     function _PassUser($UserName = '', $prefs = false)
938     {
939         //global $DBAuthParams, $DBParams;
940         if ($UserName) {
941             /*if (!$this->isValidName($UserName))
942                 return false;*/
943             $this->_userid = $UserName;
944             if ($this->hasHomePage())
945                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
946         }
947         $this->_authmethod = substr(get_class($this), 1, -8);
948         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
949
950         // Check the configured Prefs methods
951         $dbi = $this->getAuthDbh();
952         $dbh = $GLOBALS['request']->getDbh();
953         if ($dbi
954             and !$dbh->readonly
955                 and !isset($this->_prefs->_select)
956                     and $dbh->getAuthParam('pref_select')
957         ) {
958             if (!$this->_prefs) {
959                 $this->_prefs = new UserPreferences();
960                 $need_pref = true;
961             }
962             $this->_prefs->_method = $dbh->getParam('dbtype');
963             $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
964             // read-only prefs?
965             if (!isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
966                 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
967                     array("userid", "pref_blob"));
968             }
969         } else {
970             if (!$this->_prefs) {
971                 $this->_prefs = new UserPreferences();
972                 $need_pref = true;
973             }
974             $this->_prefs->_method = 'HomePage';
975         }
976
977         if (!$this->_prefs or isset($need_pref)) {
978             if ($prefs) $this->_prefs = $prefs;
979             else $this->getPreferences();
980         }
981
982         // Upgrade to the next parent _PassUser class. Avoid recursion.
983         if (strtolower(get_class($this)) === '_passuser') {
984             //auth policy: Check the order of the configured auth methods
985             // 1. first-only: Upgrade the class here in the constructor
986             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as
987             ///              in the previous PhpWiki releases (slow)
988             // 3. strict:    upgrade the class after checking the user existance in userExists()
989             // 4. stacked:   upgrade the class after the password verification in checkPass()
990             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
991             //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
992             if (defined('USER_AUTH_POLICY')) {
993                 // policy 1: only pre-define one method for all users
994                 if (USER_AUTH_POLICY === 'first-only') {
995                     $class = $this->nextClass();
996                     return new $class($UserName, $this->_prefs);
997                 } // Use the default behaviour from the previous versions:
998                 elseif (USER_AUTH_POLICY === 'old') {
999                     // Default: try to be smart
1000                     // On php5 we can directly return and upgrade the Object,
1001                     // before we have to upgrade it manually.
1002                     if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
1003                         include_once 'lib/WikiUser/HttpAuth.php';
1004                         return new _HttpAuthPassUser($UserName, $this->_prefs);
1005                     } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1006                         $dbh->getAuthParam('auth_check') and
1007                             ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))
1008                     ) {
1009                         return new _DbPassUser($UserName, $this->_prefs);
1010                     } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1011                         defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN')
1012                     ) {
1013                         include_once 'lib/WikiUser/LDAP.php';
1014                         return new _LDAPPassUser($UserName, $this->_prefs);
1015                     } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1016                         defined('IMAP_AUTH_HOST')
1017                     ) {
1018                         include_once 'lib/WikiUser/IMAP.php';
1019                             return new _IMAPPassUser($UserName, $this->_prefs);
1020                     } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1021                         defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)
1022                     ) {
1023                         include_once 'lib/WikiUser/File.php';
1024                         return new _FilePassUser($UserName, $this->_prefs);
1025                     } else {
1026                         include_once 'lib/WikiUser/PersonalPage.php';
1027                         return new _PersonalPagePassUser($UserName, $this->_prefs);
1028                     }
1029                 } else
1030                     // else use the page methods defined in _PassUser.
1031                     return $this;
1032             }
1033         }
1034     }
1035
1036     function getAuthDbh()
1037     {
1038         global $request; //, $DBParams, $DBAuthParams;
1039
1040         $dbh = $request->getDbh();
1041         // session restauration doesn't re-connect to the database automatically,
1042         // so dirty it here, to force a reconnect.
1043         if (isset($this->_auth_dbi)) {
1044             if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1045                 unset($this->_auth_dbi);
1046             if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1047                 unset($this->_auth_dbi);
1048         }
1049         if (empty($this->_auth_dbi)) {
1050             if ($dbh->getParam('dbtype') != 'SQL'
1051                 and $dbh->getParam('dbtype') != 'ADODB'
1052                     and $dbh->getParam('dbtype') != 'PDO'
1053             )
1054                 return false;
1055             if (empty($GLOBALS['DBAuthParams']))
1056                 return false;
1057             if (!$dbh->getAuthParam('auth_dsn')) {
1058                 $dbh = $request->getDbh(); // use phpwiki database
1059             } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1060                 $dbh = $request->getDbh(); // same phpwiki database
1061             } else { // use another external database handle. needs PHP >= 4.1
1062                 $local_params = array_merge($GLOBALS['DBParams'], $GLOBALS['DBAuthParams']);
1063                 $local_params['dsn'] = $local_params['auth_dsn'];
1064                 $dbh = WikiDB::open($local_params);
1065             }
1066             $this->_auth_dbi =& $dbh->_backend->_dbh;
1067         }
1068         return $this->_auth_dbi;
1069     }
1070
1071     function _normalize_stmt_var($var, $oldstyle = false)
1072     {
1073         static $valid_variables = array('userid', 'password', 'pref_blob', 'groupname');
1074         // old-style: "'$userid'"
1075         // new-style: '"\$userid"' or just "userid"
1076         $new = str_replace(array("'", '"', '\$', '$'), '', $var);
1077         if (!in_array($new, $valid_variables)) {
1078             trigger_error("Unknown DBAuthParam statement variable: " . $new, E_USER_ERROR);
1079             return false;
1080         }
1081         return !$oldstyle ? "'$" . $new . "'" : '\$' . $new;
1082     }
1083
1084     // TODO: use it again for the auth and member tables
1085     // sprintfstyle vs prepare style: %s or ?
1086     //   multiple vars should be executed via prepare(?,?)+execute,
1087     //   single vars with execute(sprintf(quote(var)))
1088     // help with position independency
1089     function prepare($stmt, $variables, $oldstyle = false, $sprintfstyle = true)
1090     {
1091         global $request;
1092         $dbi = $request->getDbh();
1093         $this->getAuthDbh();
1094         // "'\$userid"' => %s
1095         // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1096         // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1097         $new = array();
1098         if (is_array($variables)) {
1099             //$sprintfstyle = false;
1100             for ($i = 0; $i < count($variables); $i++) {
1101                 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1102                 if (!$var)
1103                     trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1104                         $variables[$i], $stmt), E_USER_WARNING);
1105                 $variables[$i] = $var;
1106                 if (!$var) $new[] = '';
1107                 else {
1108                     $s = "%" . ($i + 1) . "s";
1109                     $new[] = $sprintfstyle ? $s : "?";
1110                 }
1111             }
1112         } else {
1113             $var = $this->_normalize_stmt_var($variables, $oldstyle);
1114             if (!$var)
1115                 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1116                     $variables, $stmt), E_USER_WARNING);
1117             $variables = $var;
1118             if (!$var) $new = '';
1119             else $new = $sprintfstyle ? '%s' : "?";
1120         }
1121         $prefix = $dbi->getParam('prefix');
1122         // probably prefix table names if in same database
1123         if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1124             ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn'))
1125         ) {
1126             if (!stristr($stmt, $prefix)) {
1127                 $oldstmt = $stmt;
1128                 $stmt = str_replace(array(" user ", " pref ", " member "),
1129                     array(" " . $prefix . "user ",
1130                         " " . $prefix . "pref ",
1131                         " " . $prefix . "member "), $stmt);
1132                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1133                 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n  $oldstmt \n=> $stmt",
1134                     E_USER_WARNING);
1135             }
1136         }
1137         // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1138         // Simple sprintf-style.
1139         $new_stmt = str_replace($variables, $new, $stmt);
1140         if ($new_stmt == $stmt) {
1141             if ($oldstyle) {
1142                 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1143                     $stmt), E_USER_WARNING);
1144             } else {
1145                 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1146                     $stmt), E_USER_WARNING);
1147                 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1148             }
1149         }
1150         return $new_stmt;
1151     }
1152
1153     function getPreferences()
1154     {
1155         if (!empty($this->_prefs->_method)) {
1156             if ($this->_prefs->_method == 'ADODB') {
1157                 // FIXME: strange why this should be needed...
1158                 include_once 'lib/WikiUser/Db.php';
1159                 include_once 'lib/WikiUser/AdoDb.php';
1160                 return _AdoDbPassUser::getPreferences();
1161             } elseif ($this->_prefs->_method == 'SQL') {
1162                 include_once 'lib/WikiUser/Db.php';
1163                 include_once 'lib/WikiUser/PearDb.php';
1164                 return _PearDbPassUser::getPreferences();
1165             } elseif ($this->_prefs->_method == 'PDO') {
1166                 include_once 'lib/WikiUser/Db.php';
1167                 include_once 'lib/WikiUser/PdoDb.php';
1168                 return _PdoDbPassUser::getPreferences();
1169             }
1170         }
1171
1172         // We don't necessarily have to read the cookie first. Since
1173         // the user has a password, the prefs stored in the homepage
1174         // cannot be arbitrarily altered by other Bogo users.
1175         _AnonUser::getPreferences();
1176         // User may have deleted cookie, retrieve from his
1177         // PersonalPage if there is one.
1178         if (!empty($this->_HomePagehandle)) {
1179             if ($restored_from_page = $this->_prefs->retrieve
1180             ($this->_HomePagehandle->get('pref'))
1181             ) {
1182                 $this->_prefs->updatePrefs($restored_from_page, 'init');
1183                 return $this->_prefs;
1184             }
1185         }
1186         return $this->_prefs;
1187     }
1188
1189     function setPreferences($prefs, $id_only = false)
1190     {
1191         if (!empty($this->_prefs->_method)) {
1192             if ($this->_prefs->_method == 'ADODB') {
1193                 // FIXME: strange why this should be needed...
1194                 include_once 'lib/WikiUser/Db.php';
1195                 include_once 'lib/WikiUser/AdoDb.php';
1196                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1197             } elseif ($this->_prefs->_method == 'SQL') {
1198                 include_once 'lib/WikiUser/Db.php';
1199                 include_once 'lib/WikiUser/PearDb.php';
1200                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1201             } elseif ($this->_prefs->_method == 'PDO') {
1202                 include_once 'lib/WikiUser/Db.php';
1203                 include_once 'lib/WikiUser/PdoDb.php';
1204                 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1205             }
1206         }
1207         if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1208             // Encode only the _prefs array of the UserPreference object
1209             // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1210             if (empty($this->_HomePagehandle)) {
1211                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1212             }
1213             if (!$this->_HomePagehandle->exists()) {
1214                 $this->createHomePage();
1215             }
1216             if (!empty($this->_HomePagehandle) and !$id_only) {
1217                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1218             }
1219         }
1220         return $updated;
1221     }
1222
1223     function mayChangePass()
1224     {
1225         return true;
1226     }
1227
1228     //The default method is getting the password from prefs.
1229     // child methods obtain $stored_password from external auth.
1230     function userExists()
1231     {
1232         //if ($this->_HomePagehandle) return true;
1233         if (strtolower(get_class($this)) == "_passuser") {
1234             $class = $this->nextClass();
1235             $user = new $class($this->_userid, $this->_prefs);
1236         } else {
1237             $user = $this;
1238         }
1239         /* new user => false does not return false, but the _userid is empty then */
1240         while ($user and $user->_userid) {
1241             $user = UpgradeUser($this, $user);
1242             if ($user->userExists()) {
1243                 $user = UpgradeUser($this, $user);
1244                 return true;
1245             }
1246             // prevent endless loop. does this work on all PHP's?
1247             // it just has to set the classname, what it correctly does.
1248             $class = $user->nextClass();
1249             if ($class == "_ForbiddenPassUser")
1250                 return false;
1251         }
1252         return false;
1253     }
1254
1255     //The default method is getting the password from prefs.
1256     // child methods obtain $stored_password from external auth.
1257     function checkPass($submitted_password)
1258     {
1259         $stored_password = $this->_prefs->get('passwd');
1260         if ($this->_checkPass($submitted_password, $stored_password)) {
1261             $this->_level = WIKIAUTH_USER;
1262             return $this->_level;
1263         } else {
1264             if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1265                 $this->_level = WIKIAUTH_FORBIDDEN;
1266                 return $this->_level;
1267             }
1268             return $this->_tryNextPass($submitted_password);
1269         }
1270     }
1271
1272     function _checkPassLength($submitted_password)
1273     {
1274         if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1275             trigger_error(_("The length of the password is shorter than the system policy allows."));
1276             return false;
1277         }
1278         return true;
1279     }
1280
1281     /**
1282      * The basic password checker for all PassUser objects.
1283      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1284      * Empty passwords are always false!
1285      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1286      * @see UserPreferences::set
1287      *
1288      * DBPassUser password's have their own crypt definition.
1289      * That's why DBPassUser::checkPass() doesn't call this method, if
1290      * the db password method is 'plain', which means that the DB SQL
1291      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1292      * don't store plain passwords in the DB.
1293      *
1294      * TODO: remove crypt() function check from config.php:396 ??
1295      */
1296     function _checkPass($submitted_password, $stored_password)
1297     {
1298         if (!empty($submitted_password)) {
1299             // This works only on plaintext passwords.
1300             if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1301                 // With the EditMetaData plugin
1302                 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."));
1303                 return false;
1304             }
1305             if (!$this->_checkPassLength($submitted_password)) {
1306                 return false;
1307             }
1308             if (ENCRYPTED_PASSWD) {
1309                 // Verify against encrypted password.
1310                 if (crypt($submitted_password, $stored_password) == $stored_password)
1311                     return true; // matches encrypted password
1312                 else
1313                     return false;
1314             } else {
1315                 // Verify against cleartext password.
1316                 if ($submitted_password == $stored_password)
1317                     return true;
1318                 else {
1319                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1320                     if (crypt($submitted_password, $stored_password) == $stored_password) {
1321                         trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1322                             E_USER_WARNING);
1323                         return true;
1324                     }
1325                 }
1326             }
1327         }
1328         return false;
1329     }
1330
1331     /** The default method is storing the password in prefs.
1332      *  Child methods (DB, File) may store in external auth also, but this
1333      *  must be explicitly enabled.
1334      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1335      */
1336     function changePass($submitted_password)
1337     {
1338         $stored_password = $this->_prefs->get('passwd');
1339         // check if authenticated
1340         if (!$this->isAuthenticated()) return false;
1341         if (ENCRYPTED_PASSWD) {
1342             $submitted_password = crypt($submitted_password);
1343         }
1344         // check other restrictions, with side-effects only.
1345         $result = $this->_checkPass($submitted_password, $stored_password);
1346         if ($stored_password != $submitted_password) {
1347             $this->_prefs->set('passwd', $submitted_password);
1348             //update the storage (session, homepage, ...)
1349             $this->SetPreferences($this->_prefs);
1350             return true;
1351         }
1352         //Todo: return an error msg to the caller what failed?
1353         // same password or no privilege
1354         return ENCRYPTED_PASSWD ? true : false;
1355     }
1356
1357     function _tryNextPass($submitted_password)
1358     {
1359         if (DEBUG & _DEBUG_LOGIN) {
1360             $class = strtolower(get_class($this));
1361             if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1362             $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1363         }
1364         if (USER_AUTH_POLICY === 'strict') {
1365             $class = $this->nextClass();
1366             if ($user = new $class($this->_userid, $this->_prefs)) {
1367                 if ($user->userExists()) {
1368                     return $user->checkPass($submitted_password);
1369                 }
1370             }
1371         }
1372         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1373             $class = $this->nextClass();
1374             if ($user = new $class($this->_userid, $this->_prefs))
1375                 return $user->checkPass($submitted_password);
1376         }
1377         return $this->_level;
1378     }
1379
1380     function _tryNextUser()
1381     {
1382         if (DEBUG & _DEBUG_LOGIN) {
1383             $class = strtolower(get_class($this));
1384             if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1385             $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1386         }
1387         if (USER_AUTH_POLICY === 'strict'
1388             or USER_AUTH_POLICY === 'stacked'
1389         ) {
1390             $class = $this->nextClass();
1391             while ($user = new $class($this->_userid, $this->_prefs)) {
1392                 $user = UpgradeUser($this, $user);
1393                 if ($user->userExists()) {
1394                     $user = UpgradeUser($this, $user);
1395                     return true;
1396                 }
1397                 if ($class == "_ForbiddenPassUser") return false;
1398                 $class = $this->nextClass();
1399             }
1400         }
1401         return false;
1402     }
1403
1404 }
1405
1406 /**
1407  * Insert more auth classes here...
1408  * For example a customized db class for another db connection
1409  * or a socket-based auth server.
1410  *
1411  */
1412
1413 /**
1414  * For security, this class should not be extended. Instead, extend
1415  * from _PassUser (think of this as unix "root").
1416  *
1417  * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1418  * Other members of the Administrators group must raise their level otherwise somehow.
1419  * Currently every member is a AdminUser, which will not work for the various
1420  * storage methods.
1421  */
1422 class _AdminUser
1423     extends _PassUser
1424 {
1425     function mayChangePass()
1426     {
1427         return false;
1428     }
1429
1430     function checkPass($submitted_password)
1431     {
1432         if ($this->_userid == ADMIN_USER)
1433             $stored_password = ADMIN_PASSWD;
1434         else {
1435             // Should not happen! Only ADMIN_USER should use this class.
1436             // return $this->_tryNextPass($submitted_password); // ???
1437             // TODO: safety check if really member of the ADMIN group?
1438             $stored_password = $this->_pref->get('passwd');
1439         }
1440         if ($this->_checkPass($submitted_password, $stored_password)) {
1441             $this->_level = WIKIAUTH_ADMIN;
1442             if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1443                 // fake http auth
1444                 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1445             }
1446             return $this->_level;
1447         } else {
1448             return $this->_tryNextPass($submitted_password);
1449             //$this->_level = WIKIAUTH_ANON;
1450             //return $this->_level;
1451         }
1452     }
1453
1454     function storePass($submitted_password)
1455     {
1456         if ($this->_userid == ADMIN_USER)
1457             return false;
1458         else {
1459             // should not happen! only ADMIN_USER should use this class.
1460             return parent::storePass($submitted_password);
1461         }
1462     }
1463 }
1464
1465 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1466 /**
1467  * Various data classes for the preference types,
1468  * to support get, set, sanify (range checking, ...)
1469  * update() will do the neccessary side-effects if a
1470  * setting gets changed (theme, language, ...)
1471  */
1472
1473 class _UserPreference
1474 {
1475     public $default_value;
1476
1477     function _UserPreference($default_value)
1478     {
1479         $this->default_value = $default_value;
1480     }
1481
1482     function sanify($value)
1483     {
1484         return (string)$value;
1485     }
1486
1487     function get($name)
1488     {
1489         if (isset($this->{$name}))
1490             return $this->{$name};
1491         else
1492             return $this->default_value;
1493     }
1494
1495     function getraw($name)
1496     {
1497         if (!empty($this->{$name})) {
1498             return $this->{$name};
1499         } else {
1500             return '';
1501         }
1502     }
1503
1504     // stores the value as $this->$name, and not as $this->value (clever?)
1505     function set($name, $value)
1506     {
1507         $return = 0;
1508         $value = $this->sanify($value);
1509         if ($this->get($name) != $value) {
1510             $this->update($value);
1511             $return = 1;
1512         }
1513         if ($value != $this->default_value) {
1514             $this->{$name} = $value;
1515         } else {
1516             unset($this->{$name});
1517         }
1518         return $return;
1519     }
1520
1521     // default: no side-effects
1522     function update($value)
1523     {
1524         ;
1525     }
1526 }
1527
1528 class _UserPreference_numeric
1529     extends _UserPreference
1530 {
1531     function _UserPreference_numeric($default, $minval = false,
1532                                      $maxval = false)
1533     {
1534         $this->_UserPreference((double)$default);
1535         $this->_minval = (double)$minval;
1536         $this->_maxval = (double)$maxval;
1537     }
1538
1539     function sanify($value)
1540     {
1541         $value = (double)$value;
1542         if ($this->_minval !== false && $value < $this->_minval)
1543             $value = $this->_minval;
1544         if ($this->_maxval !== false && $value > $this->_maxval)
1545             $value = $this->_maxval;
1546         return $value;
1547     }
1548 }
1549
1550 class _UserPreference_int
1551     extends _UserPreference_numeric
1552 {
1553     function _UserPreference_int($default, $minval = false, $maxval = false)
1554     {
1555         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1556     }
1557
1558     function sanify($value)
1559     {
1560         return (int)parent::sanify((int)$value);
1561     }
1562 }
1563
1564 class _UserPreference_bool
1565     extends _UserPreference
1566 {
1567     function _UserPreference_bool($default = false)
1568     {
1569         $this->_UserPreference((bool)$default);
1570     }
1571
1572     function sanify($value)
1573     {
1574         if (is_array($value)) {
1575             /* This allows for constructs like:
1576              *
1577              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1578              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1579              *
1580              * (If the checkbox is not checked, only the hidden input
1581              * gets sent. If the checkbox is sent, both inputs get
1582              * sent.)
1583              */
1584             foreach ($value as $val) {
1585                 if ($val)
1586                     return true;
1587             }
1588             return false;
1589         }
1590         return (bool)$value;
1591     }
1592 }
1593
1594 class _UserPreference_language
1595     extends _UserPreference
1596 {
1597     function _UserPreference_language($default = DEFAULT_LANGUAGE)
1598     {
1599         $this->_UserPreference($default);
1600     }
1601
1602     // FIXME: check for valid locale
1603     function sanify($value)
1604     {
1605         // Revert to DEFAULT_LANGUAGE if user does not specify
1606         // language in UserPreferences or chooses <system language>.
1607         if ($value == '' or empty($value))
1608             $value = DEFAULT_LANGUAGE;
1609
1610         return (string)$value;
1611     }
1612
1613     function update($newvalue)
1614     {
1615         if (!$this->_init) {
1616             // invalidate etag to force fresh output
1617             $GLOBALS['request']->setValidators(array('%mtime' => false));
1618             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1619         }
1620     }
1621 }
1622
1623 class _UserPreference_theme
1624     extends _UserPreference
1625 {
1626     function _UserPreference_theme($default = THEME)
1627     {
1628         $this->_UserPreference($default);
1629     }
1630
1631     function sanify($value)
1632     {
1633         if (!empty($value) and FindFile($this->_themefile($value)))
1634             return $value;
1635         return $this->default_value;
1636     }
1637
1638     function update($newvalue)
1639     {
1640         global $WikiTheme;
1641         // invalidate etag to force fresh output
1642         if (!$this->_init)
1643             $GLOBALS['request']->setValidators(array('%mtime' => false));
1644         if ($newvalue)
1645             include_once($this->_themefile($newvalue));
1646         if (empty($WikiTheme))
1647             include_once($this->_themefile(THEME));
1648     }
1649
1650     function _themefile($theme)
1651     {
1652         return "themes/$theme/themeinfo.php";
1653     }
1654 }
1655
1656 class _UserPreference_notify
1657     extends _UserPreference
1658 {
1659     function sanify($value)
1660     {
1661         if (!empty($value))
1662             return $value;
1663         else
1664             return $this->default_value;
1665     }
1666
1667     /** update to global user prefs: side-effect on set notify changes
1668      * use a global_data notify hash:
1669      * notify = array('pagematch' => array(userid => ('email' => mail,
1670      *                                                'verified' => 0|1),
1671      *                                     ...),
1672      *                ...);
1673      */
1674     function update($value)
1675     {
1676         if (!empty($this->_init)) return;
1677         $dbh = $GLOBALS['request']->getDbh();
1678         $notify = $dbh->get('notify');
1679         if (empty($notify))
1680             $data = array();
1681         else
1682             $data =& $notify;
1683         // expand to existing pages only or store matches?
1684         // for now we store (glob-style) matches which is easier for the user
1685         $pages = $this->_page_split($value);
1686         // Limitation: only current user.
1687         $user = $GLOBALS['request']->getUser();
1688         if (!$user or !method_exists($user, 'UserName')) return;
1689         // This fails with php5 and a WIKI_ID cookie:
1690         $userid = $user->UserName();
1691         $email = $user->_prefs->get('email');
1692         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1693         // check existing notify hash and possibly delete pages for email
1694         if (!empty($data)) {
1695             foreach ($data as $page => $users) {
1696                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1697                     unset($data[$page][$userid]);
1698                 }
1699                 if (count($data[$page]) == 0)
1700                     unset($data[$page]);
1701             }
1702         }
1703         // add the new pages
1704         if (!empty($pages)) {
1705             foreach ($pages as $page) {
1706                 if (!isset($data[$page]))
1707                     $data[$page] = array();
1708                 if (!isset($data[$page][$userid])) {
1709                     // should we really store the verification notice here or
1710                     // check it dynamically at every page->save?
1711                     if ($verified) {
1712                         $data[$page][$userid] = array('email' => $email,
1713                             'verified' => $verified);
1714                     } else {
1715                         $data[$page][$userid] = array('email' => $email);
1716                     }
1717                 }
1718             }
1719         }
1720         // store users changes
1721         $dbh->set('notify', $data);
1722     }
1723
1724     /** split the user-given comma or whitespace delimited pagenames
1725      *  to array
1726      */
1727     function _page_split($value)
1728     {
1729         return preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
1730     }
1731 }
1732
1733 class _UserPreference_email
1734     extends _UserPreference
1735 {
1736     function get($name)
1737     {
1738         // get e-mail address from FusionForge
1739         if ((defined('FUSIONFORGE') and FUSIONFORGE) && session_loggedin()) {
1740             $user = session_get_user();
1741             return $user->getEmail();
1742         } else {
1743             parent::get($name);
1744         }
1745     }
1746
1747     function sanify($value)
1748     {
1749         // e-mail address is already checked by FusionForge
1750         if (defined('FUSIONFORGE') and FUSIONFORGE) {
1751             return $value;
1752         }
1753         // check for valid email address
1754         if ($this->get('email') == $value and $this->getraw('emailVerified')) {
1755             return $value;
1756         }
1757         // hack!
1758         if ($value == 1 or $value === true) {
1759             return $value;
1760         }
1761         list($ok, $msg) = ValidateMail($value, 'noconnect');
1762         if ($ok) {
1763             return $value;
1764         } else {
1765             trigger_error("E-mail Validation Error: " . $msg, E_USER_WARNING);
1766             return $this->default_value;
1767         }
1768     }
1769
1770     /** Side-effect on email changes:
1771      * Send a verification mail or for now just a notification email.
1772      * For true verification (value = 2), we'd need a mailserver hook.
1773      */
1774     function update($value)
1775     {
1776         // e-mail address is already checked by FusionForge
1777         if (defined('FUSIONFORGE') and FUSIONFORGE) {
1778             return;
1779         }
1780         if (!empty($this->_init)) {
1781             return;
1782         }
1783         $verified = $this->getraw('emailVerified');
1784         // hack!
1785         if (($value == 1 or $value === true) and $verified) {
1786             return;
1787         }
1788         if (!empty($value) and !$verified) {
1789             list($ok, $msg) = ValidateMail($value);
1790             if ($ok and mail($value, "[" . WIKI_NAME . "] " . _("E-mail address confirmation"),
1791                 sprintf(_("Welcome to %s!\nYour e-mail account is verified and\nwill be used to send page change notifications.\nSee %s"),
1792                     WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'), '', true)))
1793             ) {
1794                 $this->set('emailVerified', 1);
1795             } else {
1796                 trigger_error($msg, E_USER_WARNING);
1797             }
1798         }
1799     }
1800 }
1801
1802 /** Check for valid email address
1803 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1804 Note: too strict, Bug #1053681
1805  */
1806 function ValidateMail($email, $noconnect = false)
1807 {
1808     global $EMailHosts;
1809     $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1810
1811     // if this check is too strict (like invalid mail addresses in a local network only)
1812     // uncomment the following line:
1813     //return array(true,"not validated");
1814     // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1815
1816     $result = array();
1817
1818     // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1819     // addresses, from the Perl module Mail::RFC822::Address, reduced to
1820     // accept single RFC822 addresses without comments only. (The original
1821     // accepts groups and properly commented addresses also.)
1822     $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1823
1824     $specials = '()<>@,;:\\\\".\\[\\]';
1825     $controls = '\\000-\\031';
1826
1827     $dtext = "[^\\[\\]\\r\\\\]";
1828     $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1829
1830     $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1831
1832     $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1833     $word = "(?:$atom|$quoted_string)";
1834     $localpart = "$word(?:\\.$lwsp*$word)*";
1835
1836     $sub_domain = "(?:$atom|$domain_literal)";
1837     $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1838
1839     $addr_spec = "$localpart\@$lwsp*$domain";
1840
1841     $phrase = "$word*";
1842     $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1843     $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1844     $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1845
1846     $rfc822re = "/$lwsp*$mailbox/";
1847     unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1848     $atom, $word, $quoted_string);
1849     unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1850
1851     if (!preg_match($rfc822re, $email)) {
1852         $result[0] = false;
1853         $result[1] = sprintf(_("E-mail address “%s” is not properly formatted"), $email);
1854         return $result;
1855     }
1856     if ($noconnect)
1857         return array(true, sprintf(_("E-mail address “%s” is properly formatted"), $email));
1858
1859     list ($Username, $Domain) = explode("@", $email);
1860     //Todo: getmxrr workaround on Windows or manual input field to verify it manually
1861     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1862         $ConnectAddress = $MXHost[0];
1863     } else {
1864         $ConnectAddress = $Domain;
1865         if (isset($EMailHosts[$Domain])) {
1866             $ConnectAddress = $EMailHosts[$Domain];
1867         }
1868     }
1869     $Connect = @fsockopen($ConnectAddress, 25);
1870     if ($Connect) {
1871         if (ereg("^220", $Out = fgets($Connect, 1024))) {
1872             fputs($Connect, "HELO $HTTP_HOST\r\n");
1873             $Out = fgets($Connect, 1024);
1874             fputs($Connect, "MAIL FROM: <" . $email . ">\r\n");
1875             $From = fgets($Connect, 1024);
1876             fputs($Connect, "RCPT TO: <" . $email . ">\r\n");
1877             $To = fgets($Connect, 1024);
1878             fputs($Connect, "QUIT\r\n");
1879             fclose($Connect);
1880             if (!ereg("^250", $From)) {
1881                 $result[0] = false;
1882                 $result[1] = "Server rejected address: " . $From;
1883                 return $result;
1884             }
1885             if (!ereg("^250", $To)) {
1886                 $result[0] = false;
1887                 $result[1] = "Server rejected address: " . $To;
1888                 return $result;
1889             }
1890         } else {
1891             $result[0] = false;
1892             $result[1] = "No response from server";
1893             return $result;
1894         }
1895     } else {
1896         $result[0] = false;
1897         $result[1] = "Cannot connect e-mail server.";
1898         return $result;
1899     }
1900     $result[0] = true;
1901     $result[1] = "E-mail address '$email' appears to be valid.";
1902     return $result;
1903 } // end of function
1904
1905 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1906
1907 /**
1908  * UserPreferences
1909  *
1910  * This object holds the $request->_prefs subobjects.
1911  * A simple packed array of non-default values get's stored as cookie,
1912  * homepage, or database, which are converted to the array of
1913  * ->_prefs objects.
1914  * We don't store the objects, because otherwise we will
1915  * not be able to upgrade any subobject. And it's a waste of space also.
1916  *
1917  */
1918 class UserPreferences
1919 {
1920     public $notifyPagesAll;
1921
1922     function __construct($saved_prefs = false)
1923     {
1924         // userid stored too, to ensure the prefs are being loaded for
1925         // the correct (currently signing in) userid if stored in a
1926         // cookie.
1927         // Update: for db prefs we disallow passwd.
1928         // userid is needed for pref reflexion. current pref must know its username,
1929         // if some app needs prefs from different users, different from current user.
1930         $this->_prefs
1931             = array(
1932             'userid' => new _UserPreference(''),
1933             'passwd' => new _UserPreference(''),
1934             'autologin' => new _UserPreference_bool(),
1935             //'emailVerified' => new _UserPreference_emailVerified(),
1936             //fixed: store emailVerified as email parameter, 1.3.8
1937             'email' => new _UserPreference_email(''),
1938             'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1939             'theme' => new _UserPreference_theme(THEME),
1940             'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1941             'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1942                 EDITWIDTH_MIN_COLS,
1943                 EDITWIDTH_MAX_COLS),
1944             'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1945             'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1946                 EDITHEIGHT_MIN_ROWS,
1947                 EDITHEIGHT_MAX_ROWS),
1948             'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1949                 TIMEOFFSET_MIN_HOURS,
1950                 TIMEOFFSET_MAX_HOURS),
1951             'ownModifications' => new _UserPreference_bool(),
1952             'majorModificationsOnly' => new _UserPreference_bool(),
1953             'relativeDates' => new _UserPreference_bool(),
1954             'googleLink' => new _UserPreference_bool(), // 1.3.10
1955             'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1956         );
1957
1958         // This should be probably be done with $customUserPreferenceColumns
1959         // For now, we use FUSIONFORGE define
1960         if (defined('FUSIONFORGE') and FUSIONFORGE) {
1961             $fusionforgeprefs = array(
1962                 'pageTrail' => new _UserPreference_bool(),
1963                 'diffMenuItem' => new _UserPreference_bool(),
1964                 'pageInfoMenuItem' => new _UserPreference_bool(),
1965                 'pdfMenuItem' => new _UserPreference_bool(),
1966                 'lockMenuItem' => new _UserPreference_bool(),
1967                 'chownMenuItem' => new _UserPreference_bool(),
1968                 'setaclMenuItem' => new _UserPreference_bool(),
1969                 'removeMenuItem' => new _UserPreference_bool(),
1970                 'renameMenuItem' => new _UserPreference_bool(),
1971                 'revertMenuItem' => new _UserPreference_bool(),
1972                 'backLinksMenuItem' => new _UserPreference_bool(),
1973                 'watchPageMenuItem' => new _UserPreference_bool(),
1974                 'recentChangesMenuItem' => new _UserPreference_bool(),
1975                 'randomPageMenuItem' => new _UserPreference_bool(),
1976                 'likePagesMenuItem' => new _UserPreference_bool(),
1977                 'specialPagesMenuItem' => new _UserPreference_bool(),
1978             );
1979             $this->_prefs = array_merge($this->_prefs, $fusionforgeprefs);
1980         }
1981
1982         // add custom theme-specific pref types:
1983         // FIXME: on theme changes the wiki_user session pref object will fail.
1984         // We will silently ignore this.
1985         if (!empty($customUserPreferenceColumns))
1986             $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
1987         /*
1988                 if (isset($this->_method) and $this->_method == 'SQL') {
1989                     //unset($this->_prefs['userid']);
1990                     unset($this->_prefs['passwd']);
1991                 }
1992         */
1993         if (is_array($saved_prefs)) {
1994             foreach ($saved_prefs as $name => $value)
1995                 $this->set($name, $value);
1996         }
1997     }
1998
1999     function __clone()
2000     {
2001         foreach ($this as $key => $val) {
2002             if (is_object($val) || (is_array($val))) {
2003                 $this->{$key} = unserialize(serialize($val));
2004             }
2005         }
2006     }
2007
2008     function _getPref($name)
2009     {
2010         if ($name == 'emailVerified')
2011             $name = 'email';
2012         if (!isset($this->_prefs[$name])) {
2013             if ($name == 'passwd2') return false;
2014             if ($name == 'passwd') return false;
2015             trigger_error("$name: unknown preference", E_USER_NOTICE);
2016             return false;
2017         }
2018         return $this->_prefs[$name];
2019     }
2020
2021     // get the value or default_value of the subobject
2022     function get($name)
2023     {
2024         if ($_pref = $this->_getPref($name))
2025             if ($name == 'emailVerified')
2026                 return $_pref->getraw($name);
2027             else
2028                 return $_pref->get($name);
2029         else
2030             return false;
2031     }
2032
2033     // check and set the new value in the subobject
2034     function set($name, $value)
2035     {
2036         $pref = $this->_getPref($name);
2037         if ($pref === false)
2038             return false;
2039
2040         /* do it here or outside? */
2041         if ($name == 'passwd' and
2042             defined('PASSWORD_LENGTH_MINIMUM') and
2043                 strlen($value) <= PASSWORD_LENGTH_MINIMUM
2044         ) {
2045             //TODO: How to notify the user?
2046             return false;
2047         }
2048         /*
2049         if ($name == 'theme' and $value == '')
2050            return true;
2051         */
2052         // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2053         if ((!$value and $pref->default_value)
2054             or ($value and !isset($pref->{$name})) // bug #1355533
2055             or ($value and ($pref->{$name} != $pref->default_value))
2056         ) {
2057             if ($name == 'emailVerified') $newvalue = $value;
2058             else $newvalue = $pref->sanify($value);
2059             $pref->set($name, $newvalue);
2060         }
2061         $this->_prefs[$name] =& $pref;
2062         return true;
2063     }
2064
2065     /**
2066      * use init to avoid update on set
2067      */
2068     function updatePrefs($prefs, $init = false)
2069     {
2070         $count = 0;
2071         if ($init) $this->_init = $init;
2072         if (is_object($prefs)) {
2073             $type = 'emailVerified';
2074             $obj =& $this->_prefs['email'];
2075             $obj->_init = $init;
2076             if ($obj->get($type) !== $prefs->get($type)) {
2077                 if ($obj->set($type, $prefs->get($type)))
2078                     $count++;
2079             }
2080             foreach (array_keys($this->_prefs) as $type) {
2081                 $obj =& $this->_prefs[$type];
2082                 $obj->_init = $init;
2083                 if ($prefs->get($type) !== $obj->get($type)) {
2084                     // special systemdefault prefs: (probably not needed)
2085                     if ($type == 'theme' and $prefs->get($type) == '' and
2086                         $obj->get($type) == THEME
2087                     ) continue;
2088                     if ($type == 'lang' and $prefs->get($type) == '' and
2089                         $obj->get($type) == DEFAULT_LANGUAGE
2090                     ) continue;
2091                     if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2092                         $count++;
2093                 }
2094             }
2095         } elseif (is_array($prefs)) {
2096             //unset($this->_prefs['userid']);
2097             /*
2098         if (isset($this->_method) and
2099              ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2100                 unset($this->_prefs['passwd']);
2101         }
2102         */
2103             // emailVerified at first, the rest later
2104             $type = 'emailVerified';
2105             $obj =& $this->_prefs['email'];
2106             $obj->_init = $init;
2107             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2108                 if ($obj->set($type, $prefs[$type]))
2109                     $count++;
2110             }
2111             foreach (array_keys($this->_prefs) as $type) {
2112                 $obj =& $this->_prefs[$type];
2113                 $obj->_init = $init;
2114                 if (!isset($prefs[$type]) and is_a($obj, "_UserPreference_bool"))
2115                     $prefs[$type] = false;
2116                 if (isset($prefs[$type]) and is_a($obj, "_UserPreference_int"))
2117                     $prefs[$type] = (int)$prefs[$type];
2118                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2119                     // special systemdefault prefs:
2120                     if ($type == 'theme' and $prefs[$type] == '' and
2121                         $obj->get($type) == THEME
2122                     ) continue;
2123                     if ($type == 'lang' and $prefs[$type] == '' and
2124                         $obj->get($type) == DEFAULT_LANGUAGE
2125                     ) continue;
2126                     if ($obj->set($type, $prefs[$type]))
2127                         $count++;
2128                 }
2129             }
2130         }
2131         return $count;
2132     }
2133
2134     // For now convert just array of objects => array of values
2135     // Todo: the specialized subobjects must override this.
2136     function store()
2137     {
2138         $prefs = array();
2139         foreach ($this->_prefs as $name => $object) {
2140             if ($value = $object->getraw($name))
2141                 $prefs[$name] = $value;
2142             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2143                 $prefs['emailVerified'] = $value;
2144             if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2145                 if (strlen($value) != strlen(crypt('test')))
2146                     $prefs['passwd'] = crypt($value);
2147                 else // already crypted
2148                     $prefs['passwd'] = $value;
2149             }
2150         }
2151
2152         if (defined('FUSIONFORGE') and FUSIONFORGE) {
2153             // Merge current notifyPages with notifyPagesAll
2154             // notifyPages are pages to notify in the current project
2155             // while $notifyPagesAll is used to store all the monitored pages.
2156             if (isset($prefs['notifyPages'])) {
2157                 $this->notifyPagesAll[PAGE_PREFIX] = $prefs['notifyPages'];
2158                 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2159             }
2160         }
2161
2162         return $this->pack($prefs);
2163     }
2164
2165     // packed string or array of values => array of values
2166     // Todo: the specialized subobjects must override this.
2167     function retrieve($packed)
2168     {
2169         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2170             $packed = unserialize($packed);
2171         if (!is_array($packed)) return false;
2172         $prefs = array();
2173         foreach ($packed as $name => $packed_pref) {
2174             if (is_string($packed_pref)
2175                 and isSerialized($packed_pref)
2176                     and substr($packed_pref, 0, 2) == "O:"
2177             ) {
2178                 //legacy: check if it's an old array of objects
2179                 // Looks like a serialized object.
2180                 // This might fail if the object definition does not exist anymore.
2181                 // object with ->$name and ->default_value vars.
2182                 $pref = @unserialize($packed_pref);
2183                 if (is_object($pref))
2184                     $prefs[$name] = $pref->get($name);
2185                 // fix old-style prefs
2186             } elseif (is_numeric($name) and is_array($packed_pref)) {
2187                 if (count($packed_pref) == 1) {
2188                     list($name, $value) = each($packed_pref);
2189                     $prefs[$name] = $value;
2190                 }
2191             } else {
2192                 if (isSerialized($packed_pref))
2193                     $prefs[$name] = @unserialize($packed_pref);
2194                 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2195                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
2196                 // patched by frederik@pandora.be
2197                 if (empty($prefs[$name]))
2198                     $prefs[$name] = $packed_pref;
2199             }
2200         }
2201
2202         if (defined('FUSIONFORGE') and FUSIONFORGE) {
2203             // Restore notifyPages from notifyPagesAll
2204             // notifyPages are pages to notify in the current project
2205             // while $notifyPagesAll is used to store all the monitored pages.
2206             if (isset($prefs['notifyPages'])) {
2207                 $this->notifyPagesAll = $prefs['notifyPages'];
2208                 if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
2209                     $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
2210                 } else {
2211                     $prefs['notifyPages'] = '';
2212                 }
2213             }
2214         }
2215
2216         return $prefs;
2217     }
2218
2219     /**
2220      * Check if the given prefs object is different from the current prefs object
2221      */
2222     function isChanged($other)
2223     {
2224         foreach ($this->_prefs as $type => $obj) {
2225             if ($obj->get($type) !== $other->get($type))
2226                 return true;
2227         }
2228         return false;
2229     }
2230
2231     function defaultPreferences()
2232     {
2233         $prefs = array();
2234         foreach ($this->_prefs as $key => $obj) {
2235             $prefs[$key] = $obj->default_value;
2236         }
2237         return $prefs;
2238     }
2239
2240     // array of objects
2241     function getAll()
2242     {
2243         return $this->_prefs;
2244     }
2245
2246     function pack($nonpacked)
2247     {
2248         return serialize($nonpacked);
2249     }
2250
2251     function unpack($packed)
2252     {
2253         if (!$packed)
2254             return false;
2255         //$packed = base64_decode($packed);
2256         if (substr($packed, 0, 2) == "O:") {
2257             // Looks like a serialized object
2258             return unserialize($packed);
2259         }
2260         if (substr($packed, 0, 2) == "a:") {
2261             return unserialize($packed);
2262         }
2263         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2264         //E_USER_WARNING);
2265         return false;
2266     }
2267
2268     function hash()
2269     {
2270         return wikihash($this->_prefs);
2271     }
2272 }
2273
2274 // Local Variables:
2275 // mode: php
2276 // tab-width: 8
2277 // c-basic-offset: 4
2278 // c-hanging-comment-ender-p: nil
2279 // indent-tabs-mode: nil
2280 // End: