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 * 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)
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.
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))
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.
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.
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.
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.
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
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);
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);
118 define('TIMEOFFSET_MIN_HOURS', -26);
119 define('TIMEOFFSET_MAX_HOURS', 26);
120 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
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
127 $EMailHosts = array('avl.com' => 'mail.avl.com');
130 * There are be the following constants in config/config.ini to
131 * establish login parameters:
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
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
145 * To establish a COMPLETELY private wiki, such as an internal
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
152 * There are other possible combinations, but the typical wiki (such
153 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
158 // The last object in the row is the bad guy...
159 if (!is_array($USER_AUTH_ORDER))
160 $USER_AUTH_ORDER = array("Forbidden");
162 $USER_AUTH_ORDER[] = "Forbidden";
164 // Local convenience functions.
165 function _isAnonUserAllowed()
167 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
170 function _isBogoUserAllowed()
172 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
175 function _isUserPasswordsAllowed()
177 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
180 // Possibly upgrade userobject functions.
181 function _determineAdminUserOrOtherUser($UserName)
183 // Sanity check. User name is a condition of the definition of the
184 // _AdminUser, _BogoUser and _passuser.
186 return $GLOBALS['ForbiddenUser'];
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);
197 return _determineBogoUserOrPassUser($UserName);
200 function _determineBogoUserOrPassUser($UserName)
202 global $ForbiddenUser;
204 // Sanity check. User name is a condition of the definition of
205 // _BogoUser and _PassUser.
207 return $ForbiddenUser;
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'))
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')
222 return new _PassUser($UserName, $_BogoUser->_prefs);
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)
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;
249 * Primary WikiUser function, called by lib/main.php.
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.
255 * If an _AnonUser object is returned, the user may only browse pages
256 * (and save prefs in a cookie).
258 * To disable access but provide prefs the global $ForbiddenUser class
259 * is returned. (was previously false)
262 function WikiUser($UserName = '')
264 global $ForbiddenUser, $HTTP_SESSION_VARS;
266 //Maybe: Check sessionvar for username & save username into
267 //sessionvar (may be more appropriate to do this in lib/main.php).
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']);
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);
285 $ForbiddenUser = new _ForbiddenUser();
286 if (_isAnonUserAllowed())
288 return $ForbiddenUser; // User must sign in to browse pages.
290 return $ForbiddenUser; // User must sign in with a password.
293 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
294 . "Unexpectedly, an appropriate user class could not be determined.");
295 return $ForbiddenUser; // Failsafe.
300 * WikiUser.php use the name 'WikiUser'
302 function WikiUserClassname()
308 * Upgrade olduser by copying properties from user to olduser.
309 * We are not sure yet, for which php's a simple $this = $user works reliably,
310 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
311 * that's why try it the hard way.
313 function UpgradeUser($user, $newuser)
315 if (isa($user, '_WikiUser') and isa($newuser, '_WikiUser')) {
316 // populate the upgraded class $newuser with the values from the current user object
317 //only _auth_level, _current_method, _current_index,
318 if (!empty($user->_level) and
319 $user->_level > $newuser->_level
321 $newuser->_level = $user->_level;
322 if (!empty($user->_current_index) and
323 $user->_current_index > $newuser->_current_index
325 $newuser->_current_index = $user->_current_index;
326 $newuser->_current_method = $user->_current_method;
328 if (!empty($user->_authmethod))
329 $newuser->_authmethod = $user->_authmethod;
330 $GLOBALS['request']->_user_class = get_class($newuser);
332 foreach (get_object_vars($user) as $k => $v) {
333 if (!empty($v)) $olduser->$k = $v;
336 $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
337 //$GLOBALS['request']->_user = $olduser;
345 * Probably not needed, since we use the various user objects methods so far.
346 * Anyway, here it is, looping through all available objects.
348 function UserExists($UserName)
351 if (!($user = $request->getUser()))
352 $user = WikiUser($UserName);
355 if ($user->userExists($UserName)) {
356 $request->_user = $user;
359 if (isa($user, '_BogoUser'))
360 $user = new _PassUser($UserName, $user->_prefs);
361 $class = $user->nextClass();
362 if ($user = new $class($UserName, $user->_prefs)) {
363 return $user->userExists($UserName);
365 $request->_user = $GLOBALS['ForbiddenUser'];
369 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
372 * Base WikiUser class.
377 var $_level = WIKIAUTH_ANON;
379 var $_HomePagehandle = false;
382 function _WikiUser($UserName = '', $prefs = false)
385 $this->_userid = $UserName;
386 $this->_HomePagehandle = false;
388 $this->hasHomePage();
390 if (empty($this->_prefs)) {
391 if ($prefs) $this->_prefs = $prefs;
392 else $this->getPreferences();
398 if (!empty($this->_userid))
399 return $this->_userid;
402 function getPreferences()
404 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
405 . "New subclasses of _WikiUser must override this function.");
409 function setPreferences($prefs, $id_only)
411 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
413 . "New subclasses of _WikiUser must override this function.");
417 function userExists()
419 return $this->hasHomePage();
422 function checkPass($submitted_password)
424 // By definition, an undefined user class cannot sign in.
425 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
427 . "New subclasses of _WikiUser must override this function.");
431 // returns page_handle to user's home page or false if none
432 function hasHomePage()
434 if ($this->_userid) {
435 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
436 return $this->_HomePagehandle->exists();
438 // check db again (maybe someone else created it since
441 $this->_HomePagehandle = $request->getPage($this->_userid);
442 return $this->_HomePagehandle->exists();
449 function createHomePage()
452 $versiondata = array('author' => ADMIN_USER);
453 $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.") .
454 "\n{{Template/UserPage}}",
456 $request->_dbi->touch();
457 $this->_HomePagehandle = $request->getPage($this->_userid);
460 // innocent helper: case-insensitive position in _auth_methods
461 function array_position($string, $array)
463 $string = strtolower($string);
464 for ($found = 0; $found < count($array); $found++) {
465 if (strtolower($array[$found]) == $string)
471 function nextAuthMethodIndex()
473 if (empty($this->_auth_methods))
474 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
475 if (empty($this->_current_index)) {
476 if (strtolower(get_class($this)) != '_passuser') {
477 $this->_current_method = substr(get_class($this), 1, -8);
478 $this->_current_index = $this->array_position($this->_current_method,
479 $this->_auth_methods);
481 $this->_current_index = -1;
484 $this->_current_index++;
485 if ($this->_current_index >= count($this->_auth_methods))
487 $this->_current_method = $this->_auth_methods[$this->_current_index];
488 return $this->_current_index;
491 function AuthMethod($index = false)
493 return $this->_auth_methods[$index === false
494 ? count($this->_auth_methods) - 1
498 // upgrade the user object
501 $method = $this->AuthMethod($this->nextAuthMethodIndex());
502 include_once("lib/WikiUser/$method.php");
503 return "_" . $method . "PassUser";
506 //Fixme: for _HttpAuthPassUser
507 function PrintLoginForm(&$request, $args, $fail_message = false,
508 $seperate_page = false)
510 include_once 'lib/Template.php';
511 // Call update_locale in case the system's default language is not 'en'.
512 // (We have no user pref for lang at this point yet, no one is logged in.)
513 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
514 update_locale(DEFAULT_LANGUAGE);
515 $userid = $this->_userid;
517 extract($args); // fixme
519 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
521 $pagename = $request->getArg('pagename');
523 $login = Template('login',
524 compact('pagename', 'userid', 'require_level',
525 'fail_message', 'pass_required', 'nocache'));
526 // check if the html template was already processed
527 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
528 if ($seperate_page) {
529 $page = $request->getPage($pagename);
530 $revision = $page->getCurrentRevision();
531 return GeneratePage($login, _("Sign In"), $revision);
533 return $login->printExpansion();
537 /** Signed in but not password checked or empty password.
539 function isSignedIn()
541 return (isa($this, '_BogoUser') or isa($this, '_PassUser'));
544 /** This is password checked for sure.
546 function isAuthenticated()
548 //return isa($this,'_PassUser');
549 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
550 return $this->_level >= WIKIAUTH_BOGO;
556 if ($this->_level == WIKIAUTH_ADMIN) return true;
557 if (!$this->isSignedIn()) return false;
558 if (!$this->isAuthenticated()) return false;
560 if (!$group) $group = &$GLOBALS['request']->getGroup();
561 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
564 /** Name or IP for a signed user. UserName could come from a cookie e.g.
568 return ($this->UserName()
570 : $GLOBALS['request']->get('REMOTE_ADDR'));
573 /** Name for an authenticated user. No IP here.
575 function getAuthenticatedId()
577 return ($this->isAuthenticated()
579 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
582 function hasAuthority($require_level)
584 return $this->_level >= $require_level;
587 /* This is quite restrictive and not according the login description online.
588 Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
589 The backends may loosen or tighten this.
591 function isValidName($userid = false)
593 if (!$userid) $userid = $this->_userid;
594 if (!$userid) return false;
598 return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
602 * Called on an auth_args POST request, such as login, logout or signin.
603 * TODO: Check BogoLogin users with empty password. (self-signed users)
605 function AuthCheck($postargs)
607 // Normalize args, and extract.
608 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
610 foreach ($keys as $key)
611 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
613 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
615 if ($logout) { // Log out
616 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
618 $zone_offset = Request_AccessLogEntry::_zone_offset();
619 $ncsa_time = date("d/M/Y:H:i:s", time());
620 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
621 (string)$request->get('REMOTE_HOST'),
622 (string)$request->_user->_userid,
623 $ncsa_time, $zone_offset,
624 "logout " . get_class($request->_user),
626 (string)$request->get('HTTP_REFERER'),
627 (string)$request->get('HTTP_USER_AGENT')
629 if (($fp = fopen(LOGIN_LOG, "a"))) {
631 fputs($fp, "$entry\n");
634 //error_log("$entry\n", 3, LOGIN_LOG);
636 if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
637 $GLOBALS['request']->_user->logout();
639 $user = new _AnonUser();
641 $user->_level = WIKIAUTH_ANON;
644 return false; // User hit cancel button.
645 elseif (!$login && !$userid)
646 return false; // Nothing to do?
648 if (!$this->isValidName($userid))
649 return _("Invalid username.");
652 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
654 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
656 $zone_offset = Request_AccessLogEntry::_zone_offset();
657 $ncsa_time = date("d/M/Y:H:i:s", time());
658 $manglepasswd = $passwd;
659 for ($i = 0; $i < strlen($manglepasswd); $i++) {
660 $c = substr($manglepasswd, $i, 1);
661 if (ord($c) < 32) $manglepasswd[$i] = "<";
662 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] = ">";
664 if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
665 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
666 $request->get('REMOTE_HOST'),
667 (string)$request->_user->_userid,
668 $ncsa_time, $zone_offset,
669 "login $userid/$manglepasswd => $authlevel " . get_class($request->_user),
670 $authlevel > 0 ? "200" : "403",
671 (string)$request->get('HTTP_REFERER'),
672 (string)$request->get('HTTP_USER_AGENT')
674 if (($fp = fopen(LOGIN_LOG, "a"))) {
676 fputs($fp, "$entry\n");
679 //error_log("$entry\n", 3, LOGIN_LOG);
682 if ($authlevel <= 0) { // anon or forbidden
684 return _("Invalid password.");
686 return _("Invalid password or userid.");
687 } elseif ($authlevel < $require_level) { // auth ok, but not enough
688 if (!empty($this->_current_method) and 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 if (!check_php_version(5))
694 eval("\$this = \$user;");
695 // /*PHP5 patch*/$this = $user;
696 $this->_level = $authlevel;
699 $this->_userid = $userid;
700 $this->_level = $authlevel;
701 return _("Insufficient permissions.");
705 //$user = $GLOBALS['request']->_user;
706 if (!empty($this->_current_method) and
707 strtolower(get_class($this)) == '_passuser'
710 $class = "_" . $this->_current_method . "PassUser";
711 include_once 'lib/WikiUser/' . $this->_current_method . '.php';
712 $user = new $class($userid, $this->_prefs);
713 if (!check_php_version(5))
714 eval("\$this = \$user;");
715 // /*PHP5 patch*/$this = $user;
716 $user->_level = $authlevel;
719 $this->_userid = $userid;
720 $this->_level = $authlevel;
727 * Not authenticated in user, but he may be signed in. Basicly with view access only.
728 * prefs are stored in cookies, but only the userid.
733 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
735 /** Anon only gets to load and save prefs in a cookie, that's it.
737 function getPreferences()
741 if (empty($this->_prefs))
742 $this->_prefs = new UserPreferences;
743 $UserName = $this->UserName();
745 // Try to read deprecated 1.3.x style cookies
746 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
747 if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
748 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
750 . sprintf("%s='%s'", WIKI_NAME, $cookie)
752 . _("Default preferences will be used."),
756 * Only set if it matches the UserName who is
757 * signing in or if this really is an Anon login (no
758 * username). (Remember, _BogoUser and higher inherit this
761 if (!$UserName || $UserName == @$unboxedcookie['userid']) {
762 $updated = $this->_prefs->updatePrefs($unboxedcookie);
763 //$this->_prefs = new UserPreferences($unboxedcookie);
764 $UserName = @$unboxedcookie['userid'];
765 if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
766 $this->_userid = $UserName;
770 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
772 $request->deleteCookieVar(WIKI_NAME);
774 // Try to read deprecated 1.3.4 style cookies
775 if (!$UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
776 if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
777 if (!$UserName || $UserName == $unboxedcookie['userid']) {
778 $updated = $this->_prefs->updatePrefs($unboxedcookie);
779 //$this->_prefs = new UserPreferences($unboxedcookie);
780 $UserName = $unboxedcookie['userid'];
781 if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
782 $this->_userid = $UserName;
787 $request->deleteCookieVar("WIKI_PREF2");
791 // Try reading userid from old PhpWiki cookie formats:
792 if ($cookie = $request->cookies->get_old(getCookieName())) {
793 if (is_string($cookie) and (substr($cookie, 0, 2) != 's:'))
795 elseif (is_array($cookie) and !empty($cookie['userid']))
796 $UserName = $cookie['userid'];
798 if (!$UserName and !headers_sent())
799 $request->deleteCookieVar(getCookieName());
801 $this->_userid = $UserName;
804 // initializeTheme() needs at least an empty object
806 if (empty($this->_prefs))
807 $this->_prefs = new UserPreferences;
809 return $this->_prefs;
812 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
814 * Allow for multiple wikis in same domain. Encode only the
815 * _prefs array of the UserPreference object. Ideally the
816 * prefs array should just be imploded into a single string or
817 * something so it is completely human readable by the end
818 * user. In that case stricter error checking will be needed
819 * when loading the cookie.
821 function setPreferences($prefs, $id_only = false)
823 if (!is_object($prefs)) {
824 if (is_object($this->_prefs)) {
825 $updated = $this->_prefs->updatePrefs($prefs);
826 $prefs =& $this->_prefs;
828 // update the prefs values from scratch. This could leed to unnecessary
829 // side-effects: duplicate emailVerified, ...
830 $this->_prefs = new UserPreferences($prefs);
834 if (!isset($this->_prefs))
835 $this->_prefs =& $prefs;
837 $updated = $this->_prefs->isChanged($prefs);
840 if ($id_only and !headers_sent()) {
842 // new 1.3.8 policy: no array cookies, only plain userid string as in
843 // the pre 1.3.x versions.
844 // prefs should be stored besides the session in the homepagehandle or in a db.
845 $request->setCookieVar(getCookieName(), $this->_userid,
846 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
847 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
848 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
851 if (is_object($prefs)) {
852 $packed = $prefs->store();
853 $unpacked = $prefs->unpack($packed);
854 if (count($unpacked)) {
855 foreach (array('_method', '_select', '_update', '_insert') as $param) {
856 if (!empty($this->_prefs->{$param}))
857 $prefs->{$param} = $this->_prefs->{$param};
859 $this->_prefs = $prefs;
865 function userExists()
870 function checkPass($submitted_password)
873 // this might happen on a old-style signin button.
875 // By definition, the _AnonUser does not HAVE a password
876 // (compared to _BogoUser, who has an EMPTY password).
877 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
878 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
879 . "New subclasses of _WikiUser must override this function.");
886 * Helper class to finish the PassUser auth loop.
887 * This is added automatically to USER_AUTH_ORDER.
892 var $_level = WIKIAUTH_FORBIDDEN;
894 function checkPass($submitted_password)
896 return WIKIAUTH_FORBIDDEN;
899 function userExists()
901 if ($this->_HomePagehandle) return true;
907 * Do NOT extend _BogoUser to other classes, for checkPass()
908 * security. (In case of defects in code logic of the new class!)
909 * The intermediate step between anon and passuser.
910 * We also have the _BogoLoginPassUser class with stricter
911 * password checking, which fits into the auth loop.
912 * Note: This class is not called anymore by WikiUser()
917 function userExists()
919 if (isWikiWord($this->_userid)) {
920 $this->_level = WIKIAUTH_BOGO;
923 $this->_level = WIKIAUTH_ANON;
928 function checkPass($submitted_password)
930 // By definition, BogoUser has an empty password.
932 return $this->_level;
939 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
941 * The classes for all subsequent auth methods extend from this class.
942 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
943 * the three auth method policies first-only, strict and stacked
944 * and the two methods for prefs: homepage or database,
945 * if $DBAuthParams['pref_select'] is defined.
947 * Default is PersonalPage auth and prefs.
949 * @author: Reini Urban
953 var $_auth_dbi, $_prefs;
954 var $_current_method, $_current_index;
956 // check and prepare the auth and pref methods only once
957 function _PassUser($UserName = '', $prefs = false)
959 //global $DBAuthParams, $DBParams;
961 /*if (!$this->isValidName($UserName))
963 $this->_userid = $UserName;
964 if ($this->hasHomePage())
965 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
967 $this->_authmethod = substr(get_class($this), 1, -8);
968 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
970 // Check the configured Prefs methods
971 $dbi = $this->getAuthDbh();
972 $dbh = $GLOBALS['request']->getDbh();
975 and !isset($this->_prefs->_select)
976 and $dbh->getAuthParam('pref_select')
978 if (!$this->_prefs) {
979 $this->_prefs = new UserPreferences();
982 $this->_prefs->_method = $dbh->getParam('dbtype');
983 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
985 if (!isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
986 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
987 array("userid", "pref_blob"));
990 if (!$this->_prefs) {
991 $this->_prefs = new UserPreferences();
994 $this->_prefs->_method = 'HomePage';
997 if (!$this->_prefs or isset($need_pref)) {
998 if ($prefs) $this->_prefs = $prefs;
999 else $this->getPreferences();
1002 // Upgrade to the next parent _PassUser class. Avoid recursion.
1003 if (strtolower(get_class($this)) === '_passuser') {
1004 //auth policy: Check the order of the configured auth methods
1005 // 1. first-only: Upgrade the class here in the constructor
1006 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
1007 /// in the previous PhpWiki releases (slow)
1008 // 3. strict: upgrade the class after checking the user existance in userExists()
1009 // 4. stacked: upgrade the class after the password verification in checkPass()
1010 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
1011 //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
1012 if (defined('USER_AUTH_POLICY')) {
1013 // policy 1: only pre-define one method for all users
1014 if (USER_AUTH_POLICY === 'first-only') {
1015 $class = $this->nextClass();
1016 return new $class($UserName, $this->_prefs);
1017 } // Use the default behaviour from the previous versions:
1018 elseif (USER_AUTH_POLICY === 'old') {
1019 // Default: try to be smart
1020 // On php5 we can directly return and upgrade the Object,
1021 // before we have to upgrade it manually.
1022 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
1023 include_once 'lib/WikiUser/HttpAuth.php';
1024 if (check_php_version(5))
1025 return new _HttpAuthPassUser($UserName, $this->_prefs);
1027 $user = new _HttpAuthPassUser($UserName, $this->_prefs);
1028 eval("\$this = \$user;");
1029 // /*PHP5 patch*/$this = $user;
1032 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1033 $dbh->getAuthParam('auth_check') and
1034 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))
1036 if (check_php_version(5))
1037 return new _DbPassUser($UserName, $this->_prefs);
1039 $user = new _DbPassUser($UserName, $this->_prefs);
1040 eval("\$this = \$user;");
1041 // /*PHP5 patch*/$this = $user;
1044 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1045 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
1046 function_exists('ldap_connect')
1048 include_once 'lib/WikiUser/LDAP.php';
1049 if (check_php_version(5))
1050 return new _LDAPPassUser($UserName, $this->_prefs);
1052 $user = new _LDAPPassUser($UserName, $this->_prefs);
1053 eval("\$this = \$user;");
1054 // /*PHP5 patch*/$this = $user;
1057 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1058 defined('IMAP_AUTH_HOST') and function_exists('imap_open')
1060 include_once 'lib/WikiUser/IMAP.php';
1061 if (check_php_version(5))
1062 return new _IMAPPassUser($UserName, $this->_prefs);
1064 $user = new _IMAPPassUser($UserName, $this->_prefs);
1065 eval("\$this = \$user;");
1066 // /*PHP5 patch*/$this = $user;
1069 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1070 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)
1072 include_once 'lib/WikiUser/File.php';
1073 if (check_php_version(5))
1074 return new _FilePassUser($UserName, $this->_prefs);
1076 $user = new _FilePassUser($UserName, $this->_prefs);
1077 eval("\$this = \$user;");
1078 // /*PHP5 patch*/$this = $user;
1082 include_once 'lib/WikiUser/PersonalPage.php';
1083 if (check_php_version(5))
1084 return new _PersonalPagePassUser($UserName, $this->_prefs);
1086 $user = new _PersonalPagePassUser($UserName, $this->_prefs);
1087 eval("\$this = \$user;");
1088 // /*PHP5 patch*/$this = $user;
1093 // else use the page methods defined in _PassUser.
1099 function getAuthDbh()
1101 global $request; //, $DBParams, $DBAuthParams;
1103 $dbh = $request->getDbh();
1104 // session restauration doesn't re-connect to the database automatically,
1105 // so dirty it here, to force a reconnect.
1106 if (isset($this->_auth_dbi)) {
1107 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1108 unset($this->_auth_dbi);
1109 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1110 unset($this->_auth_dbi);
1112 if (empty($this->_auth_dbi)) {
1113 if ($dbh->getParam('dbtype') != 'SQL'
1114 and $dbh->getParam('dbtype') != 'ADODB'
1115 and $dbh->getParam('dbtype') != 'PDO'
1118 if (empty($GLOBALS['DBAuthParams']))
1120 if (!$dbh->getAuthParam('auth_dsn')) {
1121 $dbh = $request->getDbh(); // use phpwiki database
1122 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1123 $dbh = $request->getDbh(); // same phpwiki database
1124 } else { // use another external database handle. needs PHP >= 4.1
1125 $local_params = array_merge($GLOBALS['DBParams'], $GLOBALS['DBAuthParams']);
1126 $local_params['dsn'] = $local_params['auth_dsn'];
1127 $dbh = WikiDB::open($local_params);
1129 $this->_auth_dbi =& $dbh->_backend->_dbh;
1131 return $this->_auth_dbi;
1134 function _normalize_stmt_var($var, $oldstyle = false)
1136 static $valid_variables = array('userid', 'password', 'pref_blob', 'groupname');
1137 // old-style: "'$userid'"
1138 // new-style: '"\$userid"' or just "userid"
1139 $new = str_replace(array("'", '"', '\$', '$'), '', $var);
1140 if (!in_array($new, $valid_variables)) {
1141 trigger_error("Unknown DBAuthParam statement variable: " . $new, E_USER_ERROR);
1144 return !$oldstyle ? "'$" . $new . "'" : '\$' . $new;
1147 // TODO: use it again for the auth and member tables
1148 // sprintfstyle vs prepare style: %s or ?
1149 // multiple vars should be executed via prepare(?,?)+execute,
1150 // single vars with execute(sprintf(quote(var)))
1151 // help with position independency
1152 function prepare($stmt, $variables, $oldstyle = false, $sprintfstyle = true)
1155 $dbi = $request->getDbh();
1156 $this->getAuthDbh();
1157 // "'\$userid"' => %s
1158 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1159 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1161 if (is_array($variables)) {
1162 //$sprintfstyle = false;
1163 for ($i = 0; $i < count($variables); $i++) {
1164 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1166 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1167 $variables[$i], $stmt), E_USER_WARNING);
1168 $variables[$i] = $var;
1169 if (!$var) $new[] = '';
1171 $s = "%" . ($i + 1) . "s";
1172 $new[] = $sprintfstyle ? $s : "?";
1176 $var = $this->_normalize_stmt_var($variables, $oldstyle);
1178 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1179 $variables, $stmt), E_USER_WARNING);
1181 if (!$var) $new = '';
1182 else $new = $sprintfstyle ? '%s' : "?";
1184 $prefix = $dbi->getParam('prefix');
1185 // probably prefix table names if in same database
1186 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1187 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn'))
1189 if (!stristr($stmt, $prefix)) {
1191 $stmt = str_replace(array(" user ", " pref ", " member "),
1192 array(" " . $prefix . "user ",
1193 " " . $prefix . "pref ",
1194 " " . $prefix . "member "), $stmt);
1195 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1196 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt",
1200 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1201 // Simple sprintf-style.
1202 $new_stmt = str_replace($variables, $new, $stmt);
1203 if ($new_stmt == $stmt) {
1205 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1206 $stmt), E_USER_WARNING);
1208 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1209 $stmt), E_USER_WARNING);
1210 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1216 function getPreferences()
1218 if (!empty($this->_prefs->_method)) {
1219 if ($this->_prefs->_method == 'ADODB') {
1220 // FIXME: strange why this should be needed...
1221 include_once 'lib/WikiUser/Db.php';
1222 include_once 'lib/WikiUser/AdoDb.php';
1223 return _AdoDbPassUser::getPreferences();
1224 } elseif ($this->_prefs->_method == 'SQL') {
1225 include_once 'lib/WikiUser/Db.php';
1226 include_once 'lib/WikiUser/PearDb.php';
1227 return _PearDbPassUser::getPreferences();
1228 } elseif ($this->_prefs->_method == 'PDO') {
1229 include_once 'lib/WikiUser/Db.php';
1230 include_once 'lib/WikiUser/PdoDb.php';
1231 return _PdoDbPassUser::getPreferences();
1235 // We don't necessarily have to read the cookie first. Since
1236 // the user has a password, the prefs stored in the homepage
1237 // cannot be arbitrarily altered by other Bogo users.
1238 _AnonUser::getPreferences();
1239 // User may have deleted cookie, retrieve from his
1240 // PersonalPage if there is one.
1241 if (!empty($this->_HomePagehandle)) {
1242 if ($restored_from_page = $this->_prefs->retrieve
1243 ($this->_HomePagehandle->get('pref'))
1245 $updated = $this->_prefs->updatePrefs($restored_from_page, 'init');
1246 //$this->_prefs = new UserPreferences($restored_from_page);
1247 return $this->_prefs;
1250 return $this->_prefs;
1253 function setPreferences($prefs, $id_only = false)
1255 if (!empty($this->_prefs->_method)) {
1256 if ($this->_prefs->_method == 'ADODB') {
1257 // FIXME: strange why this should be needed...
1258 include_once 'lib/WikiUser/Db.php';
1259 include_once 'lib/WikiUser/AdoDb.php';
1260 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1261 } elseif ($this->_prefs->_method == 'SQL') {
1262 include_once 'lib/WikiUser/Db.php';
1263 include_once 'lib/WikiUser/PearDb.php';
1264 return _PearDbPassUser::setPreferences($prefs, $id_only);
1265 } elseif ($this->_prefs->_method == 'PDO') {
1266 include_once 'lib/WikiUser/Db.php';
1267 include_once 'lib/WikiUser/PdoDb.php';
1268 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1271 if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1272 // Encode only the _prefs array of the UserPreference object
1273 // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1274 if (empty($this->_HomePagehandle)) {
1275 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1277 if (!$this->_HomePagehandle->exists()) {
1278 $this->createHomePage();
1280 if (!empty($this->_HomePagehandle) and !$id_only) {
1281 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1287 function mayChangePass()
1292 //The default method is getting the password from prefs.
1293 // child methods obtain $stored_password from external auth.
1294 function userExists()
1296 //if ($this->_HomePagehandle) return true;
1297 if (strtolower(get_class($this)) == "_passuser") {
1298 $class = $this->nextClass();
1299 $user = new $class($this->_userid, $this->_prefs);
1303 /* new user => false does not return false, but the _userid is empty then */
1304 while ($user and $user->_userid) {
1305 if (!check_php_version(5))
1306 eval("\$this = \$user;");
1307 $user = UpgradeUser($this, $user);
1308 if ($user->userExists()) {
1309 $user = UpgradeUser($this, $user);
1312 // prevent endless loop. does this work on all PHP's?
1313 // it just has to set the classname, what it correctly does.
1314 $class = $user->nextClass();
1315 if ($class == "_ForbiddenPassUser")
1321 //The default method is getting the password from prefs.
1322 // child methods obtain $stored_password from external auth.
1323 function checkPass($submitted_password)
1325 $stored_password = $this->_prefs->get('passwd');
1326 if ($this->_checkPass($submitted_password, $stored_password)) {
1327 $this->_level = WIKIAUTH_USER;
1328 return $this->_level;
1330 if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1331 $this->_level = WIKIAUTH_FORBIDDEN;
1332 return $this->_level;
1334 return $this->_tryNextPass($submitted_password);
1339 function _checkPassLength($submitted_password)
1341 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1342 trigger_error(_("The length of the password is shorter than the system policy allows."));
1349 * The basic password checker for all PassUser objects.
1350 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1351 * Empty passwords are always false!
1352 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1353 * @see UserPreferences::set
1355 * DBPassUser password's have their own crypt definition.
1356 * That's why DBPassUser::checkPass() doesn't call this method, if
1357 * the db password method is 'plain', which means that the DB SQL
1358 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1359 * don't store plain passwords in the DB.
1361 * TODO: remove crypt() function check from config.php:396 ??
1363 function _checkPass($submitted_password, $stored_password)
1365 if (!empty($submitted_password)) {
1366 // This works only on plaintext passwords.
1367 if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1368 // With the EditMetaData plugin
1369 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."));
1372 if (!$this->_checkPassLength($submitted_password)) {
1375 if (ENCRYPTED_PASSWD) {
1376 // Verify against encrypted password.
1377 if (function_exists('crypt')) {
1378 if (crypt($submitted_password, $stored_password) == $stored_password)
1379 return true; // matches encrypted password
1383 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1384 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1389 // Verify against cleartext password.
1390 if ($submitted_password == $stored_password)
1393 // Check whether we forgot to enable ENCRYPTED_PASSWD
1394 if (function_exists('crypt')) {
1395 if (crypt($submitted_password, $stored_password) == $stored_password) {
1396 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1407 /** The default method is storing the password in prefs.
1408 * Child methods (DB, File) may store in external auth also, but this
1409 * must be explicitly enabled.
1410 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1412 function changePass($submitted_password)
1414 $stored_password = $this->_prefs->get('passwd');
1415 // check if authenticated
1416 if (!$this->isAuthenticated()) return false;
1417 if (ENCRYPTED_PASSWD) {
1418 $submitted_password = crypt($submitted_password);
1420 // check other restrictions, with side-effects only.
1421 $result = $this->_checkPass($submitted_password, $stored_password);
1422 if ($stored_password != $submitted_password) {
1423 $this->_prefs->set('passwd', $submitted_password);
1424 //update the storage (session, homepage, ...)
1425 $this->SetPreferences($this->_prefs);
1428 //Todo: return an error msg to the caller what failed?
1429 // same password or no privilege
1430 return ENCRYPTED_PASSWD ? true : false;
1433 function _tryNextPass($submitted_password)
1435 if (DEBUG & _DEBUG_LOGIN) {
1436 $class = strtolower(get_class($this));
1437 if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1438 $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1440 if (USER_AUTH_POLICY === 'strict') {
1441 $class = $this->nextClass();
1442 if ($user = new $class($this->_userid, $this->_prefs)) {
1443 if ($user->userExists()) {
1444 return $user->checkPass($submitted_password);
1448 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1449 $class = $this->nextClass();
1450 if ($user = new $class($this->_userid, $this->_prefs))
1451 return $user->checkPass($submitted_password);
1453 return $this->_level;
1456 function _tryNextUser()
1458 if (DEBUG & _DEBUG_LOGIN) {
1459 $class = strtolower(get_class($this));
1460 if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1461 $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1463 if (USER_AUTH_POLICY === 'strict'
1464 or USER_AUTH_POLICY === 'stacked'
1466 $class = $this->nextClass();
1467 while ($user = new $class($this->_userid, $this->_prefs)) {
1468 if (!check_php_version(5))
1469 eval("\$this = \$user;");
1470 $user = UpgradeUser($this, $user);
1471 if ($user->userExists()) {
1472 $user = UpgradeUser($this, $user);
1475 if ($class == "_ForbiddenPassUser") return false;
1476 $class = $this->nextClass();
1485 * Insert more auth classes here...
1486 * For example a customized db class for another db connection
1487 * or a socket-based auth server.
1493 * For security, this class should not be extended. Instead, extend
1494 * from _PassUser (think of this as unix "root").
1496 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1497 * Other members of the Administrators group must raise their level otherwise somehow.
1498 * Currently every member is a AdminUser, which will not work for the various
1504 function mayChangePass()
1509 function checkPass($submitted_password)
1511 if ($this->_userid == ADMIN_USER)
1512 $stored_password = ADMIN_PASSWD;
1514 // Should not happen! Only ADMIN_USER should use this class.
1515 // return $this->_tryNextPass($submitted_password); // ???
1516 // TODO: safety check if really member of the ADMIN group?
1517 $stored_password = $this->_pref->get('passwd');
1519 if ($this->_checkPass($submitted_password, $stored_password)) {
1520 $this->_level = WIKIAUTH_ADMIN;
1521 if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1523 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1525 return $this->_level;
1527 return $this->_tryNextPass($submitted_password);
1528 //$this->_level = WIKIAUTH_ANON;
1529 //return $this->_level;
1533 function storePass($submitted_password)
1535 if ($this->_userid == ADMIN_USER)
1538 // should not happen! only ADMIN_USER should use this class.
1539 return parent::storePass($submitted_password);
1544 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1546 * Various data classes for the preference types,
1547 * to support get, set, sanify (range checking, ...)
1548 * update() will do the neccessary side-effects if a
1549 * setting gets changed (theme, language, ...)
1552 class _UserPreference
1556 function _UserPreference($default_value)
1558 $this->default_value = $default_value;
1561 function sanify($value)
1563 return (string)$value;
1568 if (isset($this->{$name}))
1569 return $this->{$name};
1571 return $this->default_value;
1574 function getraw($name)
1576 if (!empty($this->{$name}))
1577 return $this->{$name};
1580 // stores the value as $this->$name, and not as $this->value (clever?)
1581 function set($name, $value)
1584 $value = $this->sanify($value);
1585 if ($this->get($name) != $value) {
1586 $this->update($value);
1589 if ($value != $this->default_value) {
1590 $this->{$name} = $value;
1592 unset($this->{$name});
1597 // default: no side-effects
1598 function update($value)
1604 class _UserPreference_numeric
1605 extends _UserPreference
1607 function _UserPreference_numeric($default, $minval = false,
1610 $this->_UserPreference((double)$default);
1611 $this->_minval = (double)$minval;
1612 $this->_maxval = (double)$maxval;
1615 function sanify($value)
1617 $value = (double)$value;
1618 if ($this->_minval !== false && $value < $this->_minval)
1619 $value = $this->_minval;
1620 if ($this->_maxval !== false && $value > $this->_maxval)
1621 $value = $this->_maxval;
1626 class _UserPreference_int
1627 extends _UserPreference_numeric
1629 function _UserPreference_int($default, $minval = false, $maxval = false)
1631 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1634 function sanify($value)
1636 return (int)parent::sanify((int)$value);
1640 class _UserPreference_bool
1641 extends _UserPreference
1643 function _UserPreference_bool($default = false)
1645 $this->_UserPreference((bool)$default);
1648 function sanify($value)
1650 if (is_array($value)) {
1651 /* This allows for constructs like:
1653 * <input type="hidden" name="pref[boolPref][]" value="0" />
1654 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1656 * (If the checkbox is not checked, only the hidden input
1657 * gets sent. If the checkbox is sent, both inputs get
1660 foreach ($value as $val) {
1666 return (bool)$value;
1670 class _UserPreference_language
1671 extends _UserPreference
1673 function _UserPreference_language($default = DEFAULT_LANGUAGE)
1675 $this->_UserPreference($default);
1678 // FIXME: check for valid locale
1679 function sanify($value)
1681 // Revert to DEFAULT_LANGUAGE if user does not specify
1682 // language in UserPreferences or chooses <system language>.
1683 if ($value == '' or empty($value))
1684 $value = DEFAULT_LANGUAGE;
1686 return (string)$value;
1689 function update($newvalue)
1691 if (!$this->_init) {
1692 // invalidate etag to force fresh output
1693 $GLOBALS['request']->setValidators(array('%mtime' => false));
1694 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1699 class _UserPreference_theme
1700 extends _UserPreference
1702 function _UserPreference_theme($default = THEME)
1704 $this->_UserPreference($default);
1707 function sanify($value)
1709 if (!empty($value) and FindFile($this->_themefile($value)))
1711 return $this->default_value;
1714 function update($newvalue)
1717 // invalidate etag to force fresh output
1719 $GLOBALS['request']->setValidators(array('%mtime' => false));
1721 include_once($this->_themefile($newvalue));
1722 if (empty($WikiTheme))
1723 include_once($this->_themefile(THEME));
1726 function _themefile($theme)
1728 return "themes/$theme/themeinfo.php";
1732 class _UserPreference_notify
1733 extends _UserPreference
1735 function sanify($value)
1740 return $this->default_value;
1743 /** update to global user prefs: side-effect on set notify changes
1744 * use a global_data notify hash:
1745 * notify = array('pagematch' => array(userid => ('email' => mail,
1746 * 'verified' => 0|1),
1750 function update($value)
1752 if (!empty($this->_init)) return;
1753 $dbh = $GLOBALS['request']->getDbh();
1754 $notify = $dbh->get('notify');
1759 // expand to existing pages only or store matches?
1760 // for now we store (glob-style) matches which is easier for the user
1761 $pages = $this->_page_split($value);
1762 // Limitation: only current user.
1763 $user = $GLOBALS['request']->getUser();
1764 if (!$user or !method_exists($user, 'UserName')) return;
1765 // This fails with php5 and a WIKI_ID cookie:
1766 $userid = $user->UserName();
1767 $email = $user->_prefs->get('email');
1768 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1769 // check existing notify hash and possibly delete pages for email
1770 if (!empty($data)) {
1771 foreach ($data as $page => $users) {
1772 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1773 unset($data[$page][$userid]);
1775 if (count($data[$page]) == 0)
1776 unset($data[$page]);
1779 // add the new pages
1780 if (!empty($pages)) {
1781 foreach ($pages as $page) {
1782 if (!isset($data[$page]))
1783 $data[$page] = array();
1784 if (!isset($data[$page][$userid])) {
1785 // should we really store the verification notice here or
1786 // check it dynamically at every page->save?
1788 $data[$page][$userid] = array('email' => $email,
1789 'verified' => $verified);
1791 $data[$page][$userid] = array('email' => $email);
1796 // store users changes
1797 $dbh->set('notify', $data);
1800 /** split the user-given comma or whitespace delimited pagenames
1803 function _page_split($value)
1805 return preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
1809 class _UserPreference_email
1810 extends _UserPreference
1814 // get e-mail address from FusionForge
1815 if (FUSIONFORGE && session_loggedin()) {
1816 $user = session_get_user();
1817 return $user->getEmail();
1823 function sanify($value)
1825 // e-mail address is already checked by FusionForge
1826 if (FUSIONFORGE) return $value;
1827 // check for valid email address
1828 if ($this->get('email') == $value and $this->getraw('emailVerified'))
1831 if ($value == 1 or $value === true)
1833 list($ok, $msg) = ValidateMail($value, 'noconnect');
1837 trigger_error("E-mail Validation Error: " . $msg, E_USER_WARNING);
1838 return $this->default_value;
1842 /** Side-effect on email changes:
1843 * Send a verification mail or for now just a notification email.
1844 * For true verification (value = 2), we'd need a mailserver hook.
1846 function update($value)
1848 // e-mail address is already checked by FusionForge
1849 if (FUSIONFORGE) return $value;
1850 if (!empty($this->_init)) return;
1851 $verified = $this->getraw('emailVerified');
1853 if (($value == 1 or $value === true) and $verified)
1855 if (!empty($value) and !$verified) {
1856 list($ok, $msg) = ValidateMail($value);
1857 if ($ok and mail($value, "[" . WIKI_NAME . "] " . _("E-mail address confirmation"),
1858 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1859 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'), '', true)))
1861 $this->set('emailVerified', 1);
1863 trigger_error($msg, E_USER_WARNING);
1869 /** Check for valid email address
1870 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1871 Note: too strict, Bug #1053681
1873 function ValidateMail($email, $noconnect = false)
1876 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1878 // if this check is too strict (like invalid mail addresses in a local network only)
1879 // uncomment the following line:
1880 //return array(true,"not validated");
1881 // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1885 // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1886 // addresses, from the Perl module Mail::RFC822::Address, reduced to
1887 // accept single RFC822 addresses without comments only. (The original
1888 // accepts groups and properly commented addresses also.)
1889 $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1891 $specials = '()<>@,;:\\\\".\\[\\]';
1892 $controls = '\\000-\\031';
1894 $dtext = "[^\\[\\]\\r\\\\]";
1895 $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1897 $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1899 $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1900 $word = "(?:$atom|$quoted_string)";
1901 $localpart = "$word(?:\\.$lwsp*$word)*";
1903 $sub_domain = "(?:$atom|$domain_literal)";
1904 $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1906 $addr_spec = "$localpart\@$lwsp*$domain";
1909 $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1910 $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1911 $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1913 $rfc822re = "/$lwsp*$mailbox/";
1914 unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1915 $atom, $word, $quoted_string);
1916 unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1918 if (!preg_match($rfc822re, $email)) {
1920 $result[1] = sprintf(_("E-mail address '%s' is not properly formatted"), $email);
1924 return array(true, sprintf(_("E-mail address '%s' is properly formatted"), $email));
1926 list ($Username, $Domain) = explode("@", $email);
1927 //Todo: getmxrr workaround on windows or manual input field to verify it manually
1928 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1929 $ConnectAddress = $MXHost[0];
1931 $ConnectAddress = $Domain;
1932 if (isset($EMailHosts[$Domain])) {
1933 $ConnectAddress = $EMailHosts[$Domain];
1936 $Connect = @fsockopen($ConnectAddress, 25);
1938 if (ereg("^220", $Out = fgets($Connect, 1024))) {
1939 fputs($Connect, "HELO $HTTP_HOST\r\n");
1940 $Out = fgets($Connect, 1024);
1941 fputs($Connect, "MAIL FROM: <" . $email . ">\r\n");
1942 $From = fgets($Connect, 1024);
1943 fputs($Connect, "RCPT TO: <" . $email . ">\r\n");
1944 $To = fgets($Connect, 1024);
1945 fputs($Connect, "QUIT\r\n");
1947 if (!ereg("^250", $From)) {
1949 $result[1] = "Server rejected address: " . $From;
1952 if (!ereg("^250", $To)) {
1954 $result[1] = "Server rejected address: " . $To;
1959 $result[1] = "No response from server";
1964 $result[1] = "Cannot connect e-mail server.";
1968 $result[1] = "E-mail address '$email' appears to be valid.";
1970 } // end of function
1972 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1977 * This object holds the $request->_prefs subobjects.
1978 * A simple packed array of non-default values get's stored as cookie,
1979 * homepage, or database, which are converted to the array of
1981 * We don't store the objects, because otherwise we will
1982 * not be able to upgrade any subobject. And it's a waste of space also.
1985 class UserPreferences
1987 var $notifyPagesAll;
1989 function UserPreferences($saved_prefs = false)
1991 // userid stored too, to ensure the prefs are being loaded for
1992 // the correct (currently signing in) userid if stored in a
1994 // Update: for db prefs we disallow passwd.
1995 // userid is needed for pref reflexion. current pref must know its username,
1996 // if some app needs prefs from different users, different from current user.
1999 'userid' => new _UserPreference(''),
2000 'passwd' => new _UserPreference(''),
2001 'autologin' => new _UserPreference_bool(),
2002 //'emailVerified' => new _UserPreference_emailVerified(),
2003 //fixed: store emailVerified as email parameter, 1.3.8
2004 'email' => new _UserPreference_email(''),
2005 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
2006 'theme' => new _UserPreference_theme(THEME),
2007 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
2008 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2010 EDITWIDTH_MAX_COLS),
2011 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
2012 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2013 EDITHEIGHT_MIN_ROWS,
2014 EDITHEIGHT_MAX_ROWS),
2015 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2016 TIMEOFFSET_MIN_HOURS,
2017 TIMEOFFSET_MAX_HOURS),
2018 'ownModifications' => new _UserPreference_bool(),
2019 'majorModificationsOnly' => new _UserPreference_bool(),
2020 'relativeDates' => new _UserPreference_bool(),
2021 'googleLink' => new _UserPreference_bool(), // 1.3.10
2022 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
2025 // This should be probably be done with $customUserPreferenceColumns
2026 // For now, we use FUSIONFORGE define
2028 $fusionforgeprefs = array(
2029 'pageTrail' => new _UserPreference_bool(),
2030 'diffMenuItem' => new _UserPreference_bool(),
2031 'pageInfoMenuItem' => new _UserPreference_bool(),
2032 'pdfMenuItem' => new _UserPreference_bool(),
2033 'lockMenuItem' => new _UserPreference_bool(),
2034 'chownMenuItem' => new _UserPreference_bool(),
2035 'setaclMenuItem' => new _UserPreference_bool(),
2036 'removeMenuItem' => new _UserPreference_bool(),
2037 'renameMenuItem' => new _UserPreference_bool(),
2038 'revertMenuItem' => new _UserPreference_bool(),
2039 'backLinksMenuItem' => new _UserPreference_bool(),
2040 'watchPageMenuItem' => new _UserPreference_bool(),
2041 'recentChangesMenuItem' => new _UserPreference_bool(),
2042 'randomPageMenuItem' => new _UserPreference_bool(),
2043 'likePagesMenuItem' => new _UserPreference_bool(),
2044 'specialPagesMenuItem' => new _UserPreference_bool(),
2046 $this->_prefs = array_merge($this->_prefs, $fusionforgeprefs);
2049 // add custom theme-specific pref types:
2050 // FIXME: on theme changes the wiki_user session pref object will fail.
2051 // We will silently ignore this.
2052 if (!empty($customUserPreferenceColumns))
2053 $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
2055 if (isset($this->_method) and $this->_method == 'SQL') {
2056 //unset($this->_prefs['userid']);
2057 unset($this->_prefs['passwd']);
2060 if (is_array($saved_prefs)) {
2061 foreach ($saved_prefs as $name => $value)
2062 $this->set($name, $value);
2068 foreach ($this as $key => $val) {
2069 if (is_object($val) || (is_array($val))) {
2070 $this->{$key} = unserialize(serialize($val));
2075 function _getPref($name)
2077 if ($name == 'emailVerified')
2079 if (!isset($this->_prefs[$name])) {
2080 if ($name == 'passwd2') return false;
2081 if ($name == 'passwd') return false;
2082 trigger_error("$name: unknown preference", E_USER_NOTICE);
2085 return $this->_prefs[$name];
2088 // get the value or default_value of the subobject
2091 if ($_pref = $this->_getPref($name))
2092 if ($name == 'emailVerified')
2093 return $_pref->getraw($name);
2095 return $_pref->get($name);
2100 // check and set the new value in the subobject
2101 function set($name, $value)
2103 $pref = $this->_getPref($name);
2104 if ($pref === false)
2107 /* do it here or outside? */
2108 if ($name == 'passwd' and
2109 defined('PASSWORD_LENGTH_MINIMUM') and
2110 strlen($value) <= PASSWORD_LENGTH_MINIMUM
2112 //TODO: How to notify the user?
2116 if ($name == 'theme' and $value == '')
2119 // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2120 if ((!$value and $pref->default_value)
2121 or ($value and !isset($pref->{$name})) // bug #1355533
2122 or ($value and ($pref->{$name} != $pref->default_value))
2124 if ($name == 'emailVerified') $newvalue = $value;
2125 else $newvalue = $pref->sanify($value);
2126 $pref->set($name, $newvalue);
2128 $this->_prefs[$name] =& $pref;
2133 * use init to avoid update on set
2135 function updatePrefs($prefs, $init = false)
2138 if ($init) $this->_init = $init;
2139 if (is_object($prefs)) {
2140 $type = 'emailVerified';
2141 $obj =& $this->_prefs['email'];
2142 $obj->_init = $init;
2143 if ($obj->get($type) !== $prefs->get($type)) {
2144 if ($obj->set($type, $prefs->get($type)))
2147 foreach (array_keys($this->_prefs) as $type) {
2148 $obj =& $this->_prefs[$type];
2149 $obj->_init = $init;
2150 if ($prefs->get($type) !== $obj->get($type)) {
2151 // special systemdefault prefs: (probably not needed)
2152 if ($type == 'theme' and $prefs->get($type) == '' and
2153 $obj->get($type) == THEME
2155 if ($type == 'lang' and $prefs->get($type) == '' and
2156 $obj->get($type) == DEFAULT_LANGUAGE
2158 if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2162 } elseif (is_array($prefs)) {
2163 //unset($this->_prefs['userid']);
2165 if (isset($this->_method) and
2166 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2167 unset($this->_prefs['passwd']);
2170 // emailVerified at first, the rest later
2171 $type = 'emailVerified';
2172 $obj =& $this->_prefs['email'];
2173 $obj->_init = $init;
2174 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2175 if ($obj->set($type, $prefs[$type]))
2178 foreach (array_keys($this->_prefs) as $type) {
2179 $obj =& $this->_prefs[$type];
2180 $obj->_init = $init;
2181 if (!isset($prefs[$type]) and isa($obj, "_UserPreference_bool"))
2182 $prefs[$type] = false;
2183 if (isset($prefs[$type]) and isa($obj, "_UserPreference_int"))
2184 $prefs[$type] = (int)$prefs[$type];
2185 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2186 // special systemdefault prefs:
2187 if ($type == 'theme' and $prefs[$type] == '' and
2188 $obj->get($type) == THEME
2190 if ($type == 'lang' and $prefs[$type] == '' and
2191 $obj->get($type) == DEFAULT_LANGUAGE
2193 if ($obj->set($type, $prefs[$type]))
2201 // For now convert just array of objects => array of values
2202 // Todo: the specialized subobjects must override this.
2206 foreach ($this->_prefs as $name => $object) {
2207 if ($value = $object->getraw($name))
2208 $prefs[$name] = $value;
2209 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2210 $prefs['emailVerified'] = $value;
2211 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2212 if (strlen($value) != strlen(crypt('test')))
2213 $prefs['passwd'] = crypt($value);
2214 else // already crypted
2215 $prefs['passwd'] = $value;
2220 // Merge current notifyPages with notifyPagesAll
2221 // notifyPages are pages to notify in the current project
2222 // while $notifyPagesAll is used to store all the monitored pages.
2223 if (isset($prefs['notifyPages'])) {
2224 $this->notifyPagesAll[PAGE_PREFIX] = $prefs['notifyPages'];
2225 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2229 return $this->pack($prefs);
2232 // packed string or array of values => array of values
2233 // Todo: the specialized subobjects must override this.
2234 function retrieve($packed)
2236 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2237 $packed = unserialize($packed);
2238 if (!is_array($packed)) return false;
2240 foreach ($packed as $name => $packed_pref) {
2241 if (is_string($packed_pref)
2242 and isSerialized($packed_pref)
2243 and substr($packed_pref, 0, 2) == "O:"
2245 //legacy: check if it's an old array of objects
2246 // Looks like a serialized object.
2247 // This might fail if the object definition does not exist anymore.
2248 // object with ->$name and ->default_value vars.
2249 $pref = @unserialize($packed_pref);
2250 if (is_object($pref))
2251 $prefs[$name] = $pref->get($name);
2252 // fix old-style prefs
2253 } elseif (is_numeric($name) and is_array($packed_pref)) {
2254 if (count($packed_pref) == 1) {
2255 list($name, $value) = each($packed_pref);
2256 $prefs[$name] = $value;
2259 if (isSerialized($packed_pref))
2260 $prefs[$name] = @unserialize($packed_pref);
2261 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2262 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2263 // patched by frederik@pandora.be
2264 if (empty($prefs[$name]))
2265 $prefs[$name] = $packed_pref;
2270 // Restore notifyPages from notifyPagesAll
2271 // notifyPages are pages to notify in the current project
2272 // while $notifyPagesAll is used to store all the monitored pages.
2273 if (isset($prefs['notifyPages'])) {
2274 $this->notifyPagesAll = $prefs['notifyPages'];
2275 if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
2276 $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
2278 $prefs['notifyPages'] = '';
2287 * Check if the given prefs object is different from the current prefs object
2289 function isChanged($other)
2291 foreach ($this->_prefs as $type => $obj) {
2292 if ($obj->get($type) !== $other->get($type))
2298 function defaultPreferences()
2301 foreach ($this->_prefs as $key => $obj) {
2302 $prefs[$key] = $obj->default_value;
2310 return $this->_prefs;
2313 function pack($nonpacked)
2315 return serialize($nonpacked);
2318 function unpack($packed)
2322 //$packed = base64_decode($packed);
2323 if (substr($packed, 0, 2) == "O:") {
2324 // Looks like a serialized object
2325 return unserialize($packed);
2327 if (substr($packed, 0, 2) == "a:") {
2328 return unserialize($packed);
2330 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2337 return wikihash($this->_prefs);
2341 /** TODO: new pref storage classes
2342 * These are currently user specific and should be rewritten to be pref specific.
2343 * i.e. $this == $user->_prefs
2346 class CookieUserPreferences
2347 extends UserPreferences
2349 function CookieUserPreferences ($saved_prefs = false) {
2350 //_AnonUser::_AnonUser('',$saved_prefs);
2351 UserPreferences::UserPreferences($saved_prefs);
2355 class PageUserPreferences
2356 extends UserPreferences
2358 function PageUserPreferences ($saved_prefs = false) {
2359 UserPreferences::UserPreferences($saved_prefs);
2363 class PearDbUserPreferences
2364 extends UserPreferences
2366 function PearDbUserPreferences ($saved_prefs = false) {
2367 UserPreferences::UserPreferences($saved_prefs);
2371 class AdoDbUserPreferences
2372 extends UserPreferences
2374 function AdoDbUserPreferences ($saved_prefs = false) {
2375 UserPreferences::UserPreferences($saved_prefs);
2377 function getPreferences() {
2378 // override the generic slow method here for efficiency
2379 _AnonUser::getPreferences();
2380 $this->getAuthDbh();
2381 if (isset($this->_select)) {
2382 $dbh = & $this->_auth_dbi;
2383 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2387 $prefs_blob = $rs->fields['pref_blob'];
2389 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2390 $updated = $this->_prefs->updatePrefs($restored_from_db);
2391 //$this->_prefs = new UserPreferences($restored_from_db);
2392 return $this->_prefs;
2396 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2397 if ($restored_from_page = $this->_prefs->retrieve
2398 ($this->_HomePagehandle->get('pref'))) {
2399 $updated = $this->_prefs->updatePrefs($restored_from_page);
2400 //$this->_prefs = new UserPreferences($restored_from_page);
2401 return $this->_prefs;
2404 return $this->_prefs;
2412 // c-basic-offset: 4
2413 // c-hanging-comment-ender-p: nil
2414 // indent-tabs-mode: nil