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