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