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
6 * This file is part of PhpWiki.
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.
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.
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.
24 * This is a complete OOP rewrite of the old WikiUser code with various
25 * configurable external authentication methods.
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.
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.
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.
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.
58 * @author: Reini Urban (the tricky parts),
59 * Carsten Klapp (started rolling the ball)
61 * Random architectural notes, sorted by date:
63 * 1) Now a ForbiddenUser is returned instead of false.
64 * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
65 * but may browse. Now with ALLOW_ANON_USER = false he may not browse,
66 * which is needed to disable browse PagePermissions.
67 * I added now ALLOW_ANON_EDIT = true to makes things clear.
68 * (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
70 * 3) Removed pear prepare. Performance hog, and using integers as
71 * handler doesn't help. Do simple sprintf as with adodb. And a prepare
72 * in the object init is no advantage, because in the init loop a lot of
73 * objects are tried, but not used.
74 * 4) Already gotten prefs are passed to the next object to avoid
75 * duplicate getPreferences() calls.
77 * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
78 * So we cannot just discrimate with
79 * if (!check_php_version(5))
81 * A /php5-patch.php is provided, which patches the src automatically
82 * for php4 and php5. Default is php4.
83 * Update: not needed anymore. we use eval to fool the load-time syntax checker.
85 * 6) enforced new cookie policy: prefs don't get stored in cookies
86 * anymore, only in homepage and/or database, but always in the
87 * current session. old pref cookies will get deleted.
89 * 7) Certain themes should be able to extend the predefined list
90 * of preferences. Display/editing is done in the theme specific userprefs.tmpl,
91 * but storage must be extended to the Get/SetPreferences methods.
92 * <theme>/themeinfo.php must provide CustomUserPreferences:
93 * A list of name => _UserPreference class pairs.
95 * Fixed a nasty recursion bug (i.e. php crash), when user = new class
96 * which returned false, did not return false on php-4.4.7. Check for
97 * a object member now.
100 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
101 define('WIKIAUTH_ANON', 0); // Not signed in.
102 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
103 define('WIKIAUTH_USER', 2); // Bogo user with a password.
104 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
105 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
107 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
108 //if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
109 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
110 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
111 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
113 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
114 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
115 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
117 define('TIMEOFFSET_MIN_HOURS', -26);
118 define('TIMEOFFSET_MAX_HOURS', 26);
119 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
121 /* EMAIL VERIFICATION
122 * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
123 * Provide some overrides here.
124 * ( username @ ) domain => mail-domain
126 $EMailHosts = array('avl.com' => 'mail.avl.com');
129 * There are be the following constants in config/config.ini to
130 * establish login parameters:
132 * ALLOW_ANON_USER default true
133 * ALLOW_ANON_EDIT default true
134 * ALLOW_BOGO_LOGIN default true
135 * ALLOW_USER_PASSWORDS default true
136 * PASSWORD_LENGTH_MINIMUM default 0
138 * To require user passwords for editing:
139 * ALLOW_ANON_USER = true
140 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
141 * ALLOW_BOGO_LOGIN = false
142 * ALLOW_USER_PASSWORDS = true
144 * To establish a COMPLETELY private wiki, such as an internal
146 * ALLOW_ANON_USER = false
147 * (and probably require user passwords as described above). In this
148 * case the user will be prompted to login immediately upon accessing
151 * There are other possible combinations, but the typical wiki (such
152 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
157 // The last object in the row is the bad guy...
158 if (!is_array($USER_AUTH_ORDER))
159 $USER_AUTH_ORDER = array("Forbidden");
161 $USER_AUTH_ORDER[] = "Forbidden";
163 // Local convenience functions.
164 function _isAnonUserAllowed()
166 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
169 function _isBogoUserAllowed()
171 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
174 function _isUserPasswordsAllowed()
176 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
179 // Possibly upgrade userobject functions.
180 function _determineAdminUserOrOtherUser($UserName)
182 // Sanity check. User name is a condition of the definition of the
183 // _AdminUser, _BogoUser and _passuser.
185 return $GLOBALS['ForbiddenUser'];
187 //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
188 if ($UserName == ADMIN_USER)
189 return new _AdminUser($UserName);
191 return _determineBogoUserOrPassUser($UserName);
194 function _determineBogoUserOrPassUser($UserName)
196 global $ForbiddenUser;
198 * @var WikiRequest $request
202 // Sanity check. User name is a condition of the definition of
203 // _BogoUser and _PassUser.
205 return $ForbiddenUser;
207 // Check for password and possibly upgrade user object.
208 // $_BogoUser = new _BogoUser($UserName);
209 if (_isBogoUserAllowed() and isWikiWord($UserName)) {
210 include_once 'lib/WikiUser/BogoLogin.php';
211 $_BogoUser = new _BogoLoginPassUser($UserName);
212 if ($_BogoUser->userExists() or $request->getArg('auth'))
215 if (_isUserPasswordsAllowed()) {
216 // PassUsers override BogoUsers if a password is stored
217 if (isset($_BogoUser) and isset($_BogoUser->_prefs)
218 and $_BogoUser->_prefs->get('passwd')
220 return new _PassUser($UserName, $_BogoUser->_prefs);
222 $_PassUser = new _PassUser($UserName,
223 isset($_BogoUser) ? $_BogoUser->_prefs : false);
224 if ($_PassUser->userExists() or $request->getArg('auth')) {
225 if (isset($request->_user_class))
226 $class = $request->_user_class;
227 elseif (strtolower(get_class($_PassUser)) == "_passuser")
228 $class = $_PassUser->nextClass(); else
229 $class = get_class($_PassUser);
230 if ($user = new $class($UserName, $_PassUser->_prefs)
240 // No Bogo- or PassUser exists, or
241 // passwords are not allowed, and bogo is disallowed too.
242 // (Only the admin can sign in).
243 return $ForbiddenUser;
247 * Primary WikiUser function, called by lib/main.php.
249 * This determines the user's type and returns an appropriate user
250 * object. lib/main.php then querys the resultant object for password
251 * validity as necessary.
253 * If an _AnonUser object is returned, the user may only browse pages
254 * (and save prefs in a cookie).
256 * To disable access but provide prefs the global $ForbiddenUser class
257 * is returned. (was previously false)
260 function WikiUser($UserName = '')
262 global $ForbiddenUser, $HTTP_SESSION_VARS;
264 //Maybe: Check sessionvar for username & save username into
265 //sessionvar (may be more appropriate to do this in lib/main.php).
267 $ForbiddenUser = new _ForbiddenUser($UserName);
268 // Found a user name.
269 return _determineAdminUserOrOtherUser($UserName);
270 } elseif (!empty($HTTP_SESSION_VARS['userid'])) {
271 // Found a user name.
272 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
273 return _determineAdminUserOrOtherUser($_SESSION['userid']);
275 // Check for autologin pref in cookie and possibly upgrade
276 // user object to another type.
277 $_AnonUser = new _AnonUser();
278 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
279 // Found a user name.
280 $ForbiddenUser = new _ForbiddenUser($UserName);
281 return _determineAdminUserOrOtherUser($UserName);
283 $ForbiddenUser = new _ForbiddenUser();
284 if (_isAnonUserAllowed())
286 return $ForbiddenUser; // User must sign in to browse pages.
292 * WikiUser.php use the name 'WikiUser'
294 function WikiUserClassname()
300 * Upgrade olduser by copying properties from user to olduser.
301 * We are not sure yet, for which php's a simple $this = $user works reliably,
302 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
303 * that's why try it the hard way.
305 function UpgradeUser($user, $newuser)
308 * @var WikiRequest $request
312 if (is_a($user, '_WikiUser') and is_a($newuser, '_WikiUser')) {
313 // populate the upgraded class $newuser with the values from the current user object
314 //only _auth_level, _current_method, _current_index,
315 if (!empty($user->_level) and
316 $user->_level > $newuser->_level
318 $newuser->_level = $user->_level;
319 if (!empty($user->_current_index) and
320 $user->_current_index > $newuser->_current_index
322 $newuser->_current_index = $user->_current_index;
323 $newuser->_current_method = $user->_current_method;
325 if (!empty($user->_authmethod))
326 $newuser->_authmethod = $user->_authmethod;
327 $request->_user_class = get_class($newuser);
329 foreach (get_object_vars($user) as $k => $v) {
330 if (!empty($v)) $olduser->$k = $v;
333 $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
334 //$request->_user = $olduser;
341 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
344 * Base WikiUser class.
346 abstract class _WikiUser
348 public $_userid = '';
349 public $_level = WIKIAUTH_ANON;
350 public $_prefs = false;
351 public $_HomePagehandle = false;
352 public $_auth_methods;
353 public $_current_method;
354 public $_current_index;
357 function _WikiUser($UserName = '', $prefs = false)
360 $this->_userid = $UserName;
361 $this->_HomePagehandle = false;
363 $this->hasHomePage();
365 if (empty($this->_prefs)) {
366 if ($prefs) $this->_prefs = $prefs;
367 else $this->getPreferences();
373 if (!empty($this->_userid)) {
374 return $this->_userid;
380 abstract function getPreferences();
382 abstract function setPreferences($prefs, $id_only);
384 function userExists()
386 return $this->hasHomePage();
389 abstract function checkPass($submitted_password);
391 // returns page_handle to user's home page or false if none
392 function hasHomePage()
394 if ($this->_userid) {
395 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
396 return $this->_HomePagehandle->exists();
398 // check db again (maybe someone else created it since
401 $this->_HomePagehandle = $request->getPage($this->_userid);
402 return $this->_HomePagehandle->exists();
409 function createHomePage()
412 * @var WikiRequest $request
416 $versiondata = array('author' => ADMIN_USER);
417 $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.") .
418 "\n{{Template/UserPage}}",
420 $request->_dbi->touch();
421 $this->_HomePagehandle = $request->getPage($this->_userid);
424 // innocent helper: case-insensitive position in _auth_methods
425 function array_position($string, $array)
427 $string = strtolower($string);
428 for ($found = 0; $found < count($array); $found++) {
429 if (strtolower($array[$found]) == $string)
435 function nextAuthMethodIndex()
437 if (empty($this->_auth_methods))
438 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
439 if (empty($this->_current_index)) {
440 if (strtolower(get_class($this)) != '_passuser') {
441 $this->_current_method = substr(get_class($this), 1, -8);
442 $this->_current_index = $this->array_position($this->_current_method,
443 $this->_auth_methods);
445 $this->_current_index = -1;
448 $this->_current_index++;
449 if ($this->_current_index >= count($this->_auth_methods))
451 $this->_current_method = $this->_auth_methods[$this->_current_index];
452 return $this->_current_index;
455 function AuthMethod($index = false)
457 return $this->_auth_methods[$index === false
458 ? count($this->_auth_methods) - 1
462 // upgrade the user object
465 $method = $this->AuthMethod($this->nextAuthMethodIndex());
466 include_once("lib/WikiUser/$method.php");
467 return "_" . $method . "PassUser";
470 //Fixme: for _HttpAuthPassUser
471 function PrintLoginForm(&$request, $args, $fail_message = '', $separate_page = false)
473 include_once 'lib/Template.php';
474 // Call update_locale in case the system's default language is not 'en'.
475 // (We have no user pref for lang at this point yet, no one is logged in.)
476 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
477 update_locale(DEFAULT_LANGUAGE);
478 $userid = $this->_userid;
480 extract($args); // fixme
482 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
484 $pagename = $request->getArg('pagename');
486 $login = Template('login',
487 compact('pagename', 'userid', 'require_level',
488 'fail_message', 'pass_required', 'nocache'));
489 // check if the html template was already processed
490 $separate_page = $separate_page ? true : !alreadyTemplateProcessed('html');
491 if ($separate_page) {
492 $page = $request->getPage($pagename);
493 $revision = $page->getCurrentRevision();
494 GeneratePage($login, _("Sign In"), $revision);
496 $login->printExpansion();
500 /** Signed in but not password checked or empty password.
502 function isSignedIn()
504 return (is_a($this, '_BogoUser') or is_a($this, '_PassUser'));
507 /** This is password checked for sure.
509 function isAuthenticated()
511 //return is_a($this,'_PassUser');
512 //return is_a($this,'_BogoUser') || is_a($this,'_PassUser');
513 return $this->_level >= WIKIAUTH_BOGO;
519 * @var WikiRequest $request
525 if ($this->_level == WIKIAUTH_ADMIN) return true;
526 if (!$this->isSignedIn()) return false;
527 if (!$this->isAuthenticated()) return false;
530 $group = &$request->getGroup();
531 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
534 /** Name or IP for a signed user. UserName could come from a cookie e.g.
539 * @var WikiRequest $request
543 return ($this->UserName()
545 : $request->get('REMOTE_ADDR'));
548 /** Name for an authenticated user. No IP here.
550 function getAuthenticatedId()
552 return ($this->isAuthenticated()
554 : ''); // $request->get('REMOTE_ADDR') );
557 function hasAuthority($require_level)
559 return $this->_level >= $require_level;
562 /* This is quite restrictive and not according the login description online.
563 Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
564 The backends may loosen or tighten this.
566 function isValidName($userid = false)
568 if (!$userid) $userid = $this->_userid;
569 if (!$userid) return false;
570 if (defined('FUSIONFORGE') && FUSIONFORGE) {
573 return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
577 * Called on an auth_args POST request, such as login, logout or signin.
578 * TODO: Check BogoLogin users with empty password. (self-signed users)
580 function AuthCheck($postargs)
582 // Normalize args, and extract.
583 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
585 foreach ($keys as $key)
586 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
588 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
590 if ($logout) { // Log out
591 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
593 * @var WikiRequest $request
597 $zone_offset = Request_AccessLogEntry::_zone_offset();
598 $ncsa_time = date("d/M/Y:H:i:s", time());
599 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
600 (string)$request->get('REMOTE_HOST'),
601 (string)$request->_user->_userid,
602 $ncsa_time, $zone_offset,
603 "logout " . get_class($request->_user),
605 (string)$request->get('HTTP_REFERER'),
606 (string)$request->get('HTTP_USER_AGENT')
608 if (($fp = fopen(LOGIN_LOG, "a"))) {
610 fputs($fp, "$entry\n");
613 //error_log("$entry\n", 3, LOGIN_LOG);
615 if (method_exists($request->_user, "logout")) { //_HttpAuthPassUser
616 $request->_user->logout();
618 $user = new _AnonUser();
620 $user->_level = WIKIAUTH_ANON;
623 return false; // User hit cancel button.
624 elseif (!$login && !$userid)
625 return false; // Nothing to do?
627 if (!$this->isValidName($userid))
628 return _("Invalid username.");
631 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
633 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
635 * @var WikiRequest $request
639 $zone_offset = Request_AccessLogEntry::_zone_offset();
640 $ncsa_time = date("d/M/Y:H:i:s", time());
641 $manglepasswd = $passwd;
642 for ($i = 0; $i < strlen($manglepasswd); $i++) {
643 $c = substr($manglepasswd, $i, 1);
644 if (ord($c) < 32) $manglepasswd[$i] = "<";
645 elseif ($c == '*') $manglepasswd[$i] = "*"; elseif ($c == '?') $manglepasswd[$i] = "?"; elseif ($c == '(') $manglepasswd[$i] = "("; elseif ($c == ')') $manglepasswd[$i] = ")"; elseif ($c == "\\") $manglepasswd[$i] = "\\"; elseif (ord($c) < 127) $manglepasswd[$i] = "x"; elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
647 if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
648 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
649 $request->get('REMOTE_HOST'),
650 (string)$request->_user->_userid,
651 $ncsa_time, $zone_offset,
652 "login $userid/$manglepasswd => $authlevel " . get_class($request->_user),
653 $authlevel > 0 ? "200" : "403",
654 (string)$request->get('HTTP_REFERER'),
655 (string)$request->get('HTTP_USER_AGENT')
657 if (($fp = fopen(LOGIN_LOG, "a"))) {
659 fputs($fp, "$entry\n");
662 //error_log("$entry\n", 3, LOGIN_LOG);
665 if ($authlevel <= 0) { // anon or forbidden
667 return _("Invalid password.");
669 return _("Invalid password or userid.");
670 } elseif ($authlevel < $require_level) { // auth ok, but not enough
671 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') {
673 $class = "_" . $this->_current_method . "PassUser";
674 include_once 'lib/WikiUser/' . $this->_current_method . '.php';
675 $user = new $class($userid, $this->_prefs);
676 $this->_level = $authlevel;
679 $this->_userid = $userid;
680 $this->_level = $authlevel;
681 return _("Insufficient permissions.");
685 //$user = $request->_user;
686 if (!empty($this->_current_method) and
687 strtolower(get_class($this)) == '_passuser'
690 $class = "_" . $this->_current_method . "PassUser";
691 include_once 'lib/WikiUser/' . $this->_current_method . '.php';
692 $user = new $class($userid, $this->_prefs);
693 $user->_level = $authlevel;
696 $this->_userid = $userid;
697 $this->_level = $authlevel;
704 * Not authenticated in user, but he may be signed in. Basicly with view access only.
705 * prefs are stored in cookies, but only the userid.
710 public $_level = WIKIAUTH_ANON;
712 /** Anon only gets to load and save prefs in a cookie, that's it.
714 function getPreferences()
717 * @var WikiRequest $request
721 if (empty($this->_prefs))
722 $this->_prefs = new UserPreferences;
723 $UserName = $this->UserName();
725 // Try to read deprecated 1.3.x style cookies
726 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
727 if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
728 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
730 . sprintf("%s='%s'", WIKI_NAME, $cookie)
732 . _("Default preferences will be used."),
736 * Only set if it matches the UserName who is
737 * signing in or if this really is an Anon login (no
738 * username). (Remember, _BogoUser and higher inherit this
741 if (!$UserName || $UserName == @$unboxedcookie['userid']) {
742 $this->_prefs->updatePrefs($unboxedcookie);
743 $UserName = @$unboxedcookie['userid'];
744 if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
745 $this->_userid = $UserName;
749 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
751 $request->deleteCookieVar(WIKI_NAME);
753 // Try to read deprecated 1.3.4 style cookies
754 if (!$UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
755 if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
756 if (!$UserName || $UserName == $unboxedcookie['userid']) {
757 $this->_prefs->updatePrefs($unboxedcookie);
758 $UserName = $unboxedcookie['userid'];
759 if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
760 $this->_userid = $UserName;
765 $request->deleteCookieVar("WIKI_PREF2");
769 // Try reading userid from old PhpWiki cookie formats:
770 if ($cookie = $request->cookies->get_old(getCookieName())) {
771 if (is_string($cookie) and (substr($cookie, 0, 2) != 's:'))
773 elseif (is_array($cookie) and !empty($cookie['userid']))
774 $UserName = $cookie['userid'];
776 if (!$UserName and !headers_sent())
777 $request->deleteCookieVar(getCookieName());
779 $this->_userid = $UserName;
782 // initializeTheme() needs at least an empty object
784 if (empty($this->_prefs))
785 $this->_prefs = new UserPreferences;
787 return $this->_prefs;
790 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
792 * Allow for multiple wikis in same domain. Encode only the
793 * _prefs array of the UserPreference object. Ideally the
794 * prefs array should just be imploded into a single string or
795 * something so it is completely human readable by the end
796 * user. In that case stricter error checking will be needed
797 * when loading the cookie.
799 function setPreferences($prefs, $id_only = false)
801 if (!is_object($prefs)) {
802 if (is_object($this->_prefs)) {
803 $updated = $this->_prefs->updatePrefs($prefs);
804 $prefs =& $this->_prefs;
806 // update the prefs values from scratch. This could lead to unnecessary
807 // side-effects: duplicate emailVerified, ...
808 $this->_prefs = new UserPreferences($prefs);
812 if (!isset($this->_prefs))
813 $this->_prefs =& $prefs;
815 $updated = $this->_prefs->isChanged($prefs);
818 if ($id_only and !headers_sent()) {
820 * @var WikiRequest $request
824 // new 1.3.8 policy: no array cookies, only plain userid string as in
825 // the pre 1.3.x versions.
826 // prefs should be stored besides the session in the homepagehandle or in a db.
827 $request->setCookieVar(getCookieName(), $this->_userid,
828 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
829 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
830 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
833 if (is_object($prefs)) {
834 $packed = $prefs->store();
835 $unpacked = $prefs->unpack($packed);
836 if (count($unpacked)) {
837 foreach (array('_method', '_select', '_update', '_insert') as $param) {
838 if (!empty($this->_prefs->{$param}))
839 $prefs->{$param} = $this->_prefs->{$param};
841 $this->_prefs = $prefs;
847 function userExists()
852 function checkPass($submitted_password)
860 * Helper class to finish the PassUser auth loop.
861 * This is added automatically to USER_AUTH_ORDER.
866 public $_level = WIKIAUTH_FORBIDDEN;
868 function checkPass($submitted_password)
870 return WIKIAUTH_FORBIDDEN;
873 function userExists()
875 if ($this->_HomePagehandle) return true;
881 * Do NOT extend _BogoUser to other classes, for checkPass()
882 * security. (In case of defects in code logic of the new class!)
883 * The intermediate step between anon and passuser.
884 * We also have the _BogoLoginPassUser class with stricter
885 * password checking, which fits into the auth loop.
886 * Note: This class is not called anymore by WikiUser()
891 function userExists()
893 if (isWikiWord($this->_userid)) {
894 $this->_level = WIKIAUTH_BOGO;
897 $this->_level = WIKIAUTH_ANON;
902 function checkPass($submitted_password)
904 // By definition, BogoUser has an empty password.
906 return $this->_level;
913 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
915 * The classes for all subsequent auth methods extend from this class.
916 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
917 * the three auth method policies first-only, strict and stacked
918 * and the two methods for prefs: homepage or database,
919 * if $DBAuthParams['pref_select'] is defined.
921 * Default is PersonalPage auth and prefs.
923 * @author: Reini Urban
929 * @var UserPreferences $_prefs
932 public $_current_method;
933 public $_current_index;
935 // check and prepare the auth and pref methods only once
936 function _PassUser($UserName = '', $prefs = false)
939 * @var WikiRequest $request
944 $this->_userid = $UserName;
945 if ($this->hasHomePage())
946 $this->_HomePagehandle = $request->getPage($this->_userid);
948 $this->_authmethod = substr(get_class($this), 1, -8);
949 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
951 // Check the configured Prefs methods
952 $dbi = $this->getAuthDbh();
953 $dbh = $request->getDbh();
956 and !isset($this->_prefs->_select)
957 and $dbh->getAuthParam('pref_select')
959 if (!$this->_prefs) {
960 $this->_prefs = new UserPreferences();
963 $this->_prefs->_method = $dbh->getParam('dbtype');
964 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
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"));
971 if (!$this->_prefs) {
972 $this->_prefs = new UserPreferences();
975 $this->_prefs->_method = 'HomePage';
978 if (!$this->_prefs or isset($need_pref)) {
979 if ($prefs) $this->_prefs = $prefs;
980 else $this->getPreferences();
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'))
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')
1014 include_once 'lib/WikiUser/LDAP.php';
1015 return new _LDAPPassUser($UserName, $this->_prefs);
1016 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1017 defined('IMAP_AUTH_HOST')
1019 include_once 'lib/WikiUser/IMAP.php';
1020 return new _IMAPPassUser($UserName, $this->_prefs);
1021 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1022 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)
1024 include_once 'lib/WikiUser/File.php';
1025 return new _FilePassUser($UserName, $this->_prefs);
1027 include_once 'lib/WikiUser/PersonalPage.php';
1028 return new _PersonalPagePassUser($UserName, $this->_prefs);
1031 // else use the page methods defined in _PassUser.
1038 function getAuthDbh()
1041 * @var WikiRequest $request
1045 $dbh = $request->getDbh();
1046 // session restoration doesn't re-connect to the database automatically,
1047 // so dirty it here, to force a reconnect.
1048 if (isset($this->_auth_dbi)) {
1049 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1050 unset($this->_auth_dbi);
1051 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1052 unset($this->_auth_dbi);
1054 if (empty($this->_auth_dbi)) {
1055 if ($dbh->getParam('dbtype') != 'SQL'
1056 and $dbh->getParam('dbtype') != 'ADODB'
1057 and $dbh->getParam('dbtype') != 'PDO'
1060 if (empty($GLOBALS['DBAuthParams']))
1062 if (!$dbh->getAuthParam('auth_dsn')) {
1063 $dbh = $request->getDbh(); // use phpwiki database
1064 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1065 $dbh = $request->getDbh(); // same phpwiki database
1066 } else { // use another external database handle. needs PHP >= 4.1
1067 $local_params = array_merge($GLOBALS['DBParams'], $GLOBALS['DBAuthParams']);
1068 $local_params['dsn'] = $local_params['auth_dsn'];
1069 $dbh = WikiDB::open($local_params);
1071 $this->_auth_dbi =& $dbh->_backend->_dbh;
1073 return $this->_auth_dbi;
1076 function _normalize_stmt_var($var, $oldstyle = false)
1078 static $valid_variables = array('userid', 'password', 'pref_blob', 'groupname');
1079 // old-style: "'$userid'"
1080 // new-style: '"\$userid"' or just "userid"
1081 $new = str_replace(array("'", '"', '\$', '$'), '', $var);
1082 if (!in_array($new, $valid_variables)) {
1083 trigger_error("Unknown DBAuthParam statement variable: " . $new, E_USER_ERROR);
1086 return !$oldstyle ? "'$" . $new . "'" : '\$' . $new;
1089 // TODO: use it again for the auth and member tables
1090 // sprintf style vs prepare style: %s or ?
1091 // multiple vars should be executed via prepare(?,?)+execute,
1092 // single vars with execute(sprintf(quote(var)))
1093 // help with position independence
1094 function prepare($stmt, $variables, $oldstyle = false, $sprintfstyle = true)
1097 * @var WikiRequest $request
1101 $dbi = $request->getDbh();
1102 $this->getAuthDbh();
1103 // "'\$userid"' => %s
1104 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1105 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1107 if (is_array($variables)) {
1108 //$sprintfstyle = false;
1109 for ($i = 0; $i < count($variables); $i++) {
1110 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1112 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1113 $variables[$i], $stmt), E_USER_WARNING);
1114 $variables[$i] = $var;
1115 if (!$var) $new[] = '';
1117 $s = "%" . ($i + 1) . "s";
1118 $new[] = $sprintfstyle ? $s : "?";
1122 $var = $this->_normalize_stmt_var($variables, $oldstyle);
1124 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1125 $variables, $stmt), E_USER_WARNING);
1127 if (!$var) $new = '';
1128 else $new = $sprintfstyle ? '%s' : "?";
1130 $prefix = $dbi->getParam('prefix');
1131 // probably prefix table names if in same database
1132 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1133 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn'))
1135 if (!stristr($stmt, $prefix)) {
1137 $stmt = str_replace(array(" user ", " pref ", " member "),
1138 array(" " . $prefix . "user ",
1139 " " . $prefix . "pref ",
1140 " " . $prefix . "member "), $stmt);
1141 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1142 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt",
1146 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1147 // Simple sprintf-style.
1148 $new_stmt = str_replace($variables, $new, $stmt);
1149 if ($new_stmt == $stmt) {
1151 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1152 $stmt), E_USER_WARNING);
1154 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1155 $stmt), E_USER_WARNING);
1156 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1162 function getPreferences()
1164 if (!empty($this->_prefs->_method)) {
1165 if ($this->_prefs->_method == 'ADODB') {
1166 // FIXME: strange why this should be needed...
1167 include_once 'lib/WikiUser/Db.php';
1168 include_once 'lib/WikiUser/AdoDb.php';
1169 return _AdoDbPassUser::getPreferences();
1170 } elseif ($this->_prefs->_method == 'SQL') {
1171 include_once 'lib/WikiUser/Db.php';
1172 include_once 'lib/WikiUser/PearDb.php';
1173 return _PearDbPassUser::getPreferences();
1174 } elseif ($this->_prefs->_method == 'PDO') {
1175 include_once 'lib/WikiUser/Db.php';
1176 include_once 'lib/WikiUser/PdoDb.php';
1177 return _PdoDbPassUser::getPreferences();
1181 // We don't necessarily have to read the cookie first. Since
1182 // the user has a password, the prefs stored in the homepage
1183 // cannot be arbitrarily altered by other Bogo users.
1184 _AnonUser::getPreferences();
1185 // User may have deleted cookie, retrieve from his
1186 // PersonalPage if there is one.
1187 if (!empty($this->_HomePagehandle)) {
1188 if ($restored_from_page = $this->_prefs->retrieve
1189 ($this->_HomePagehandle->get('pref'))
1191 $this->_prefs->updatePrefs($restored_from_page, 'init');
1192 return $this->_prefs;
1195 return $this->_prefs;
1198 function setPreferences($prefs, $id_only = false)
1201 * @var WikiRequest $request
1205 if (!empty($this->_prefs->_method)) {
1206 if ($this->_prefs->_method == 'ADODB') {
1207 // FIXME: strange why this should be needed...
1208 include_once 'lib/WikiUser/Db.php';
1209 include_once 'lib/WikiUser/AdoDb.php';
1210 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1211 } elseif ($this->_prefs->_method == 'SQL') {
1212 include_once 'lib/WikiUser/Db.php';
1213 include_once 'lib/WikiUser/PearDb.php';
1214 return _PearDbPassUser::setPreferences($prefs, $id_only);
1215 } elseif ($this->_prefs->_method == 'PDO') {
1216 include_once 'lib/WikiUser/Db.php';
1217 include_once 'lib/WikiUser/PdoDb.php';
1218 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1221 if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1222 // Encode only the _prefs array of the UserPreference object
1223 // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1224 if (empty($this->_HomePagehandle)) {
1225 $this->_HomePagehandle = $request->getPage($this->_userid);
1227 if (!$this->_HomePagehandle->exists()) {
1228 $this->createHomePage();
1230 if (!empty($this->_HomePagehandle) and !$id_only) {
1231 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1237 function mayChangePass()
1242 //The default method is getting the password from prefs.
1243 // child methods obtain $stored_password from external auth.
1244 function userExists()
1246 //if ($this->_HomePagehandle) return true;
1247 if (strtolower(get_class($this)) == "_passuser") {
1248 $class = $this->nextClass();
1249 $user = new $class($this->_userid, $this->_prefs);
1253 /* new user => false does not return false, but the _userid is empty then */
1254 while ($user and $user->_userid) {
1255 $user = UpgradeUser($this, $user);
1256 if ($user->userExists()) {
1257 UpgradeUser($this, $user);
1260 // prevent endless loop. does this work on all PHP's?
1261 // it just has to set the classname, what it correctly does.
1262 $class = $user->nextClass();
1263 if ($class == "_ForbiddenPassUser")
1269 //The default method is getting the password from prefs.
1270 // child methods obtain $stored_password from external auth.
1271 function checkPass($submitted_password)
1273 $stored_password = $this->_prefs->get('passwd');
1274 if ($this->_checkPass($submitted_password, $stored_password)) {
1275 $this->_level = WIKIAUTH_USER;
1276 return $this->_level;
1278 if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1279 $this->_level = WIKIAUTH_FORBIDDEN;
1280 return $this->_level;
1282 return $this->_tryNextPass($submitted_password);
1286 function _checkPassLength($submitted_password)
1288 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1289 trigger_error(_("The length of the password is shorter than the system policy allows."));
1296 * The basic password checker for all PassUser objects.
1297 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1298 * Empty passwords are always false!
1299 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1300 * @see UserPreferences::set
1302 * DBPassUser password's have their own crypt definition.
1303 * That's why DBPassUser::checkPass() doesn't call this method, if
1304 * the db password method is 'plain', which means that the DB SQL
1305 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1306 * don't store plain passwords in the DB.
1308 * TODO: remove crypt() function check from config.php:396 ??
1310 function _checkPass($submitted_password, $stored_password)
1312 if (!empty($submitted_password)) {
1313 // This works only on plaintext passwords.
1314 if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1315 // With the EditMetaData plugin
1316 trigger_error(_("The length of the stored password is shorter than the system policy allows. Sorry, you cannot login.\n You have to ask the System Administrator to reset your password."));
1319 if (!$this->_checkPassLength($submitted_password)) {
1322 if (ENCRYPTED_PASSWD) {
1323 // Verify against encrypted password.
1324 if (crypt($submitted_password, $stored_password) == $stored_password)
1325 return true; // matches encrypted password
1329 // Verify against cleartext password.
1330 if ($submitted_password == $stored_password)
1333 // Check whether we forgot to enable ENCRYPTED_PASSWD
1334 if (crypt($submitted_password, $stored_password) == $stored_password) {
1335 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1345 /** The default method is storing the password in prefs.
1346 * Child methods (DB, File) may store in external auth also, but this
1347 * must be explicitly enabled.
1348 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1350 function changePass($submitted_password)
1352 $stored_password = $this->_prefs->get('passwd');
1353 // check if authenticated
1354 if (!$this->isAuthenticated()) return false;
1355 if (ENCRYPTED_PASSWD) {
1356 $submitted_password = crypt($submitted_password);
1358 // check other restrictions, with side-effects only.
1359 $result = $this->_checkPass($submitted_password, $stored_password);
1360 if ($stored_password != $submitted_password) {
1361 $this->_prefs->set('passwd', $submitted_password);
1362 //update the storage (session, homepage, ...)
1363 $this->SetPreferences($this->_prefs);
1366 //Todo: return an error msg to the caller what failed?
1367 // same password or no privilege
1368 return ENCRYPTED_PASSWD ? true : false;
1371 function _tryNextPass($submitted_password)
1373 if (DEBUG & _DEBUG_LOGIN) {
1374 $class = strtolower(get_class($this));
1375 if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1376 $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1378 if (USER_AUTH_POLICY === 'strict') {
1379 $class = $this->nextClass();
1380 if ($user = new $class($this->_userid, $this->_prefs)) {
1381 if ($user->userExists()) {
1382 return $user->checkPass($submitted_password);
1386 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1387 $class = $this->nextClass();
1388 if ($user = new $class($this->_userid, $this->_prefs))
1389 return $user->checkPass($submitted_password);
1391 return $this->_level;
1394 function _tryNextUser()
1396 if (DEBUG & _DEBUG_LOGIN) {
1397 $class = strtolower(get_class($this));
1398 if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1399 $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1401 if (USER_AUTH_POLICY === 'strict'
1402 or USER_AUTH_POLICY === 'stacked'
1404 $class = $this->nextClass();
1405 while ($user = new $class($this->_userid, $this->_prefs)) {
1406 $user = UpgradeUser($this, $user);
1407 if ($user->userExists()) {
1408 UpgradeUser($this, $user);
1411 if ($class == "_ForbiddenPassUser") return false;
1412 $class = $this->nextClass();
1421 * Insert more auth classes here...
1422 * For example a customized db class for another db connection
1423 * or a socket-based auth server.
1428 * For security, this class should not be extended. Instead, extend
1429 * from _PassUser (think of this as unix "root").
1431 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1432 * Other members of the Administrators group must raise their level otherwise somehow.
1433 * Currently every member is a AdminUser, which will not work for the various
1439 function mayChangePass()
1444 function checkPass($submitted_password)
1446 if ($this->_userid == ADMIN_USER)
1447 $stored_password = ADMIN_PASSWD;
1449 // Should not happen! Only ADMIN_USER should use this class.
1450 // return $this->_tryNextPass($submitted_password); // ???
1451 // TODO: safety check if really member of the ADMIN group?
1452 $stored_password = $this->_pref->get('passwd');
1454 if ($this->_checkPass($submitted_password, $stored_password)) {
1455 $this->_level = WIKIAUTH_ADMIN;
1456 if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1458 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1460 return $this->_level;
1462 return $this->_tryNextPass($submitted_password);
1463 //$this->_level = WIKIAUTH_ANON;
1464 //return $this->_level;
1468 function storePass($submitted_password)
1470 if ($this->_userid == ADMIN_USER)
1473 // should not happen! only ADMIN_USER should use this class.
1474 return parent::storePass($submitted_password);
1479 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1481 * Various data classes for the preference types,
1482 * to support get, set, sanify (range checking, ...)
1483 * update() will do the neccessary side-effects if a
1484 * setting gets changed (theme, language, ...)
1487 class _UserPreference
1489 public $default_value;
1491 function _UserPreference($default_value)
1493 $this->default_value = $default_value;
1496 function sanify($value)
1498 return (string)$value;
1503 if (isset($this->{$name}))
1504 return $this->{$name};
1506 return $this->default_value;
1509 function getraw($name)
1511 if (!empty($this->{$name})) {
1512 return $this->{$name};
1518 // stores the value as $this->$name, and not as $this->value (clever?)
1519 function set($name, $value)
1522 $value = $this->sanify($value);
1523 if ($this->get($name) != $value) {
1524 $this->update($value);
1527 if ($value != $this->default_value) {
1528 $this->{$name} = $value;
1530 unset($this->{$name});
1535 // default: no side-effects
1536 function update($value)
1542 class _UserPreference_numeric
1543 extends _UserPreference
1545 function _UserPreference_numeric($default, $minval = false,
1548 $this->_UserPreference((double)$default);
1549 $this->_minval = (double)$minval;
1550 $this->_maxval = (double)$maxval;
1553 function sanify($value)
1555 $value = (double)$value;
1556 if ($this->_minval !== false && $value < $this->_minval)
1557 $value = $this->_minval;
1558 if ($this->_maxval !== false && $value > $this->_maxval)
1559 $value = $this->_maxval;
1564 class _UserPreference_int
1565 extends _UserPreference_numeric
1567 function _UserPreference_int($default, $minval = false, $maxval = false)
1569 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1572 function sanify($value)
1574 return (int)parent::sanify((int)$value);
1578 class _UserPreference_bool
1579 extends _UserPreference
1581 function _UserPreference_bool($default = false)
1583 $this->_UserPreference((bool)$default);
1586 function sanify($value)
1588 if (is_array($value)) {
1589 /* This allows for constructs like:
1591 * <input type="hidden" name="pref[boolPref][]" value="0" />
1592 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1594 * (If the checkbox is not checked, only the hidden input
1595 * gets sent. If the checkbox is sent, both inputs get
1598 foreach ($value as $val) {
1604 return (bool)$value;
1608 class _UserPreference_language
1609 extends _UserPreference
1611 function _UserPreference_language($default = DEFAULT_LANGUAGE)
1613 $this->_UserPreference($default);
1616 // FIXME: check for valid locale
1617 function sanify($value)
1619 // Revert to DEFAULT_LANGUAGE if user does not specify
1620 // language in UserPreferences or chooses <system language>.
1621 if ($value == '' or empty($value))
1622 $value = DEFAULT_LANGUAGE;
1624 return (string)$value;
1627 function update($newvalue)
1630 * @var WikiRequest $request
1634 if (!$this->_init) {
1635 // invalidate etag to force fresh output
1636 $request->setValidators(array('%mtime' => false));
1637 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1642 class _UserPreference_theme
1643 extends _UserPreference
1645 function _UserPreference_theme($default = THEME)
1647 $this->_UserPreference($default);
1650 function sanify($value)
1652 if (!empty($value) and FindFile($this->_themefile($value)))
1654 return $this->default_value;
1657 function update($newvalue)
1661 * @var WikiRequest $request
1665 // invalidate etag to force fresh output
1667 $request->setValidators(array('%mtime' => false));
1669 include_once($this->_themefile($newvalue));
1670 if (empty($WikiTheme))
1671 include_once($this->_themefile(THEME));
1674 function _themefile($theme)
1676 return "themes/$theme/themeinfo.php";
1680 class _UserPreference_notify
1681 extends _UserPreference
1683 function sanify($value)
1688 return $this->default_value;
1691 /** update to global user prefs: side-effect on set notify changes
1692 * use a global_data notify hash:
1693 * notify = array('pagematch' => array(userid => ('email' => mail,
1694 * 'verified' => 0|1),
1698 function update($value)
1701 * @var WikiRequest $request
1705 if (!empty($this->_init)) return;
1706 $dbh = $request->getDbh();
1707 $notify = $dbh->get('notify');
1712 // expand to existing pages only or store matches?
1713 // for now we store (glob-style) matches which is easier for the user
1714 $pages = $this->_page_split($value);
1715 // Limitation: only current user.
1716 $user = $request->getUser();
1717 if (!$user or !method_exists($user, 'UserName')) return;
1718 // This fails with php5 and a WIKI_ID cookie:
1719 $userid = $user->UserName();
1720 $email = $user->_prefs->get('email');
1721 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1722 // check existing notify hash and possibly delete pages for email
1723 if (!empty($data)) {
1724 foreach ($data as $page => $users) {
1725 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1726 unset($data[$page][$userid]);
1728 if (count($data[$page]) == 0)
1729 unset($data[$page]);
1732 // add the new pages
1733 if (!empty($pages)) {
1734 foreach ($pages as $page) {
1735 if (!isset($data[$page]))
1736 $data[$page] = array();
1737 if (!isset($data[$page][$userid])) {
1738 // should we really store the verification notice here or
1739 // check it dynamically at every page->save?
1741 $data[$page][$userid] = array('email' => $email,
1742 'verified' => $verified);
1744 $data[$page][$userid] = array('email' => $email);
1749 // store users changes
1750 $dbh->set('notify', $data);
1753 /** split the user-given comma or whitespace delimited pagenames
1756 function _page_split($value)
1758 return preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
1762 class _UserPreference_email
1763 extends _UserPreference
1767 // get e-mail address from FusionForge
1768 if ((defined('FUSIONFORGE') && FUSIONFORGE) && session_loggedin()) {
1769 $user = session_get_user();
1770 return $user->getEmail();
1772 return parent::get($name);
1776 function sanify($value)
1778 // e-mail address is already checked by FusionForge
1779 if (defined('FUSIONFORGE') && FUSIONFORGE) {
1782 // check for valid email address
1783 if ($this->get('email') == $value and $this->getraw('emailVerified')) {
1787 if ($value == 1 or $value === true) {
1790 list($ok, $msg) = ValidateMail($value, 'noconnect');
1794 trigger_error("E-mail Validation Error: " . $msg, E_USER_WARNING);
1795 return $this->default_value;
1799 /** Side-effect on email changes:
1800 * Send a verification mail or for now just a notification email.
1801 * For true verification (value = 2), we'd need a mailserver hook.
1803 function update($value)
1806 * @var WikiRequest $request
1810 // e-mail address is already checked by FusionForge
1811 if (defined('FUSIONFORGE') && FUSIONFORGE) {
1814 if (!empty($this->_init)) {
1817 $verified = $this->getraw('emailVerified');
1819 if (($value == 1 or $value === true) and $verified) {
1822 if (!empty($value) and !$verified) {
1823 list($ok, $msg) = ValidateMail($value);
1824 if ($ok and mail($value, "[" . WIKI_NAME . "] " . _("E-mail address confirmation"),
1825 sprintf(_("Welcome to %s!\nYour e-mail account is verified and\nwill be used to send page change notifications.\nSee %s"),
1826 WIKI_NAME, WikiURL($request->getArg('pagename'), '', true)))
1828 $this->set('emailVerified', 1);
1830 trigger_error($msg, E_USER_WARNING);
1836 /** Check for valid email address
1837 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1838 Note: too strict, Bug #1053681
1840 function ValidateMail($email, $noconnect = false)
1844 * @var WikiRequest $request
1848 $HTTP_HOST = $request->get('HTTP_HOST');
1850 // if this check is too strict (like invalid mail addresses in a local network only)
1851 // uncomment the following line:
1852 //return array(true,"not validated");
1853 // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1857 // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1858 // addresses, from the Perl module Mail::RFC822::Address, reduced to
1859 // accept single RFC822 addresses without comments only. (The original
1860 // accepts groups and properly commented addresses also.)
1861 $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1863 $specials = '()<>@,;:\\\\".\\[\\]';
1864 $controls = '\\000-\\031';
1866 $dtext = "[^\\[\\]\\r\\\\]";
1867 $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1869 $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1871 $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1872 $word = "(?:$atom|$quoted_string)";
1873 $localpart = "$word(?:\\.$lwsp*$word)*";
1875 $sub_domain = "(?:$atom|$domain_literal)";
1876 $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1878 $addr_spec = "$localpart\@$lwsp*$domain";
1881 $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1882 $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1883 $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1885 $rfc822re = "/$lwsp*$mailbox/";
1886 unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1887 $atom, $word, $quoted_string);
1888 unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1890 if (!preg_match($rfc822re, $email)) {
1892 $result[1] = sprintf(_("E-mail address “%s” is not properly formatted"), $email);
1896 return array(true, sprintf(_("E-mail address “%s” is properly formatted"), $email));
1898 list ($Username, $Domain) = explode("@", $email);
1899 //Todo: getmxrr workaround on Windows or manual input field to verify it manually
1900 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1901 $ConnectAddress = $MXHost[0];
1903 $ConnectAddress = $Domain;
1904 if (isset($EMailHosts[$Domain])) {
1905 $ConnectAddress = $EMailHosts[$Domain];
1908 $Connect = @fsockopen($ConnectAddress, 25);
1910 if (ereg("^220", $Out = fgets($Connect, 1024))) {
1911 fputs($Connect, "HELO $HTTP_HOST\r\n");
1912 $Out = fgets($Connect, 1024);
1913 fputs($Connect, "MAIL FROM: <" . $email . ">\r\n");
1914 $From = fgets($Connect, 1024);
1915 fputs($Connect, "RCPT TO: <" . $email . ">\r\n");
1916 $To = fgets($Connect, 1024);
1917 fputs($Connect, "QUIT\r\n");
1919 if (!ereg("^250", $From)) {
1921 $result[1] = "Server rejected address: " . $From;
1924 if (!ereg("^250", $To)) {
1926 $result[1] = "Server rejected address: " . $To;
1931 $result[1] = "No response from server";
1936 $result[1] = "Cannot connect e-mail server.";
1940 $result[1] = "E-mail address '$email' appears to be valid.";
1942 } // end of function
1944 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1949 * This object holds the $request->_prefs subobjects.
1950 * A simple packed array of non-default values get's stored as cookie,
1951 * homepage, or database, which are converted to the array of
1953 * We don't store the objects, because otherwise we will
1954 * not be able to upgrade any subobject. And it's a waste of space also.
1957 class UserPreferences
1959 public $notifyPagesAll;
1966 function __construct($saved_prefs = false)
1968 // userid stored too, to ensure the prefs are being loaded for
1969 // the correct (currently signing in) userid if stored in a
1971 // Update: for db prefs we disallow passwd.
1972 // userid is needed for pref reflexion. current pref must know its username,
1973 // if some app needs prefs from different users, different from current user.
1976 'userid' => new _UserPreference(''),
1977 'passwd' => new _UserPreference(''),
1978 'autologin' => new _UserPreference_bool(),
1979 //'emailVerified' => new _UserPreference_emailVerified(),
1980 //fixed: store emailVerified as email parameter, 1.3.8
1981 'email' => new _UserPreference_email(''),
1982 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1983 'theme' => new _UserPreference_theme(THEME),
1984 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1985 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1987 EDITWIDTH_MAX_COLS),
1988 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1989 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1990 EDITHEIGHT_MIN_ROWS,
1991 EDITHEIGHT_MAX_ROWS),
1992 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1993 TIMEOFFSET_MIN_HOURS,
1994 TIMEOFFSET_MAX_HOURS),
1995 'ownModifications' => new _UserPreference_bool(),
1996 'majorModificationsOnly' => new _UserPreference_bool(),
1997 'relativeDates' => new _UserPreference_bool(),
1998 'googleLink' => new _UserPreference_bool(), // 1.3.10
1999 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
2002 // This should be probably be done with $customUserPreferenceColumns
2003 // For now, we use FUSIONFORGE define
2004 if (defined('FUSIONFORGE') && FUSIONFORGE) {
2005 $fusionforgeprefs = array(
2006 'pageTrail' => new _UserPreference_bool(),
2007 'diffMenuItem' => new _UserPreference_bool(),
2008 'pageInfoMenuItem' => new _UserPreference_bool(),
2009 'pdfMenuItem' => new _UserPreference_bool(),
2010 'lockMenuItem' => new _UserPreference_bool(),
2011 'chownMenuItem' => new _UserPreference_bool(),
2012 'setaclMenuItem' => new _UserPreference_bool(),
2013 'removeMenuItem' => new _UserPreference_bool(),
2014 'renameMenuItem' => new _UserPreference_bool(),
2015 'revertMenuItem' => new _UserPreference_bool(),
2016 'backLinksMenuItem' => new _UserPreference_bool(),
2017 'watchPageMenuItem' => new _UserPreference_bool(),
2018 'recentChangesMenuItem' => new _UserPreference_bool(),
2019 'randomPageMenuItem' => new _UserPreference_bool(),
2020 'likePagesMenuItem' => new _UserPreference_bool(),
2021 'specialPagesMenuItem' => new _UserPreference_bool(),
2023 $this->_prefs = array_merge($this->_prefs, $fusionforgeprefs);
2026 // add custom theme-specific pref types:
2027 // FIXME: on theme changes the wiki_user session pref object will fail.
2028 // We will silently ignore this.
2029 if (!empty($customUserPreferenceColumns))
2030 $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
2032 if (isset($this->_method) and $this->_method == 'SQL') {
2033 //unset($this->_prefs['userid']);
2034 unset($this->_prefs['passwd']);
2037 if (is_array($saved_prefs)) {
2038 foreach ($saved_prefs as $name => $value)
2039 $this->set($name, $value);
2045 foreach ($this as $key => $val) {
2046 if (is_object($val) || (is_array($val))) {
2047 $this->{$key} = unserialize(serialize($val));
2052 function _getPref($name)
2054 if ($name == 'emailVerified')
2056 if (!isset($this->_prefs[$name])) {
2057 if ($name == 'passwd2') return false;
2058 if ($name == 'passwd') return false;
2059 trigger_error("$name: unknown preference", E_USER_NOTICE);
2062 return $this->_prefs[$name];
2065 // get the value or default_value of the subobject
2068 if ($_pref = $this->_getPref($name))
2069 if ($name == 'emailVerified')
2070 return $_pref->getraw($name);
2072 return $_pref->get($name);
2077 // check and set the new value in the subobject
2078 function set($name, $value)
2080 $pref = $this->_getPref($name);
2081 if ($pref === false)
2084 /* do it here or outside? */
2085 if ($name == 'passwd' and
2086 defined('PASSWORD_LENGTH_MINIMUM') and
2087 strlen($value) <= PASSWORD_LENGTH_MINIMUM
2089 //TODO: How to notify the user?
2093 if ($name == 'theme' and $value == '')
2096 // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2097 if ((!$value and $pref->default_value)
2098 or ($value and !isset($pref->{$name})) // bug #1355533
2099 or ($value and ($pref->{$name} != $pref->default_value))
2101 if ($name == 'emailVerified') $newvalue = $value;
2102 else $newvalue = $pref->sanify($value);
2103 $pref->set($name, $newvalue);
2105 $this->_prefs[$name] =& $pref;
2110 * use init to avoid update on set
2112 function updatePrefs($prefs, $init = false)
2116 $this->_init = $init;
2117 if (is_object($prefs)) {
2118 $type = 'emailVerified';
2119 $obj =& $this->_prefs['email'];
2120 $obj->_init = $init;
2121 if ($obj->get($type) !== $prefs->get($type)) {
2122 if ($obj->set($type, $prefs->get($type)))
2125 foreach (array_keys($this->_prefs) as $type) {
2126 $obj =& $this->_prefs[$type];
2127 $obj->_init = $init;
2128 if ($prefs->get($type) !== $obj->get($type)) {
2129 // special systemdefault prefs: (probably not needed)
2130 if ($type == 'theme' and $prefs->get($type) == '' and
2131 $obj->get($type) == THEME
2133 if ($type == 'lang' and $prefs->get($type) == '' and
2134 $obj->get($type) == DEFAULT_LANGUAGE
2136 if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2140 } elseif (is_array($prefs)) {
2141 //unset($this->_prefs['userid']);
2143 if (isset($this->_method) and
2144 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2145 unset($this->_prefs['passwd']);
2148 // emailVerified at first, the rest later
2149 $type = 'emailVerified';
2150 $obj =& $this->_prefs['email'];
2151 $obj->_init = $init;
2152 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2153 if ($obj->set($type, $prefs[$type]))
2156 foreach (array_keys($this->_prefs) as $type) {
2157 $obj =& $this->_prefs[$type];
2158 $obj->_init = $init;
2159 if (!isset($prefs[$type]) and is_a($obj, "_UserPreference_bool"))
2160 $prefs[$type] = false;
2161 if (isset($prefs[$type]) and is_a($obj, "_UserPreference_int"))
2162 $prefs[$type] = (int)$prefs[$type];
2163 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2164 // special systemdefault prefs:
2165 if ($type == 'theme' and $prefs[$type] == '' and
2166 $obj->get($type) == THEME
2168 if ($type == 'lang' and $prefs[$type] == '' and
2169 $obj->get($type) == DEFAULT_LANGUAGE
2171 if ($obj->set($type, $prefs[$type]))
2179 // For now convert just array of objects => array of values
2180 // Todo: the specialized subobjects must override this.
2184 foreach ($this->_prefs as $name => $object) {
2185 if ($value = $object->getraw($name))
2186 $prefs[$name] = $value;
2187 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2188 $prefs['emailVerified'] = $value;
2189 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2190 if (strlen($value) != strlen(crypt('test')))
2191 $prefs['passwd'] = crypt($value);
2192 else // already crypted
2193 $prefs['passwd'] = $value;
2197 if (defined('FUSIONFORGE') && FUSIONFORGE) {
2198 // Merge current notifyPages with notifyPagesAll
2199 // notifyPages are pages to notify in the current project
2200 // while $notifyPagesAll is used to store all the monitored pages.
2201 if (isset($prefs['notifyPages'])) {
2202 global $page_prefix;
2203 $this->notifyPagesAll[$page_prefix] = $prefs['notifyPages'];
2204 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2208 return $this->pack($prefs);
2211 // packed string or array of values => array of values
2212 // Todo: the specialized subobjects must override this.
2213 function retrieve($packed)
2215 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2216 $packed = unserialize($packed);
2217 if (!is_array($packed)) return false;
2219 foreach ($packed as $name => $packed_pref) {
2220 if (is_string($packed_pref)
2221 and isSerialized($packed_pref)
2222 and substr($packed_pref, 0, 2) == "O:"
2224 //legacy: check if it's an old array of objects
2225 // Looks like a serialized object.
2226 // This might fail if the object definition does not exist anymore.
2227 // object with ->$name and ->default_value vars.
2228 $pref = @unserialize($packed_pref);
2229 if (is_object($pref))
2230 $prefs[$name] = $pref->get($name);
2231 // fix old-style prefs
2232 } elseif (is_numeric($name) and is_array($packed_pref)) {
2233 if (count($packed_pref) == 1) {
2234 list($name, $value) = each($packed_pref);
2235 $prefs[$name] = $value;
2238 if (isSerialized($packed_pref))
2239 $prefs[$name] = @unserialize($packed_pref);
2240 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2241 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2242 // patched by frederik@pandora.be
2243 if (empty($prefs[$name]))
2244 $prefs[$name] = $packed_pref;
2248 if (defined('FUSIONFORGE') && FUSIONFORGE) {
2249 // Restore notifyPages from notifyPagesAll
2250 // notifyPages are pages to notify in the current project
2251 // while $notifyPagesAll is used to store all the monitored pages.
2252 if (isset($prefs['notifyPages'])) {
2253 $this->notifyPagesAll = $prefs['notifyPages'];
2254 global $page_prefix;
2255 if (isset($this->notifyPagesAll[$page_prefix])) {
2256 $prefs['notifyPages'] = $this->notifyPagesAll[$page_prefix];
2258 $prefs['notifyPages'] = '';
2267 * Check if the given prefs object is different from the current prefs object
2269 function isChanged($other)
2271 foreach ($this->_prefs as $type => $obj) {
2272 if ($obj->get($type) !== $other->get($type))
2278 function defaultPreferences()
2281 foreach ($this->_prefs as $key => $obj) {
2282 $prefs[$key] = $obj->default_value;
2290 return $this->_prefs;
2293 function pack($nonpacked)
2295 return serialize($nonpacked);
2298 function unpack($packed)
2302 //$packed = base64_decode($packed);
2303 if (substr($packed, 0, 2) == "O:") {
2304 // Looks like a serialized object
2305 return unserialize($packed);
2307 if (substr($packed, 0, 2) == "a:") {
2308 return unserialize($packed);
2315 return wikihash($this->_prefs);
2322 // c-basic-offset: 4
2323 // c-hanging-comment-ender-p: nil
2324 // indent-tabs-mode: nil