2 //$Id: WikiUserNew.php 8160 2011-10-03 12:42:28Z vargenau $
3 /* Copyright (C) 2004,2005,2006,2007,2009,2010 $ThePhpWikiProgrammingTeam
4 * Copyright (C) 2009-2010 Marc-Etienne Vargenau, Alcatel-Lucent
5 * Copyright (C) 2009-2010 Roger Guignard, Alcatel-Lucent
7 * This file is part of PhpWiki.
9 * PhpWiki is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * PhpWiki is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * This is a complete OOP rewrite of the old WikiUser code with various
26 * configurable external authentication methods.
28 * There's only one entry point, the function WikiUser which returns
29 * a WikiUser object, which contains the name, authlevel and user's preferences.
30 * This object might get upgraded during the login step and later also.
31 * There exist three preferences storage methods: cookie, homepage and db,
32 * and multiple password checking methods.
33 * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if
34 * ALLOW_USER_PASSWORDS is defined.
36 * Each user object must define the two preferences methods
37 * getPreferences(), setPreferences(),
38 * and the following 1-4 auth methods
39 * checkPass() must be defined by all classes,
40 * userExists() only if USER_AUTH_POLICY'=='strict'
41 * mayChangePass() only if the password is storable.
42 * storePass() only if the password is storable.
44 * WikiUser() given no name, returns an _AnonUser (anonymous user)
45 * object, who may or may not have a cookie.
46 * However, if the there's a cookie with the userid or a session,
47 * the user is upgraded to the matching user object.
48 * Given a user name, returns a _BogoUser object, who may or may not
49 * have a cookie and/or PersonalPage, one of the various _PassUser objects
50 * or an _AdminUser object.
51 * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might
52 * have stored a password or not. If so, his account is secure, if not
53 * anybody can use it, because the username is visible e.g. in RecentChanges.
55 * Takes care of passwords, all preference loading/storing in the
56 * user's page and any cookies. lib/main.php will query the user object to
57 * verify the password as appropriate.
59 * @author: Reini Urban (the tricky parts),
60 * Carsten Klapp (started rolling the ball)
62 * Random architectural notes, sorted by date:
64 * Test it by defining ENABLE_USER_NEW in config/config.ini
65 * 1) Now a ForbiddenUser is returned instead of false.
66 * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
67 * but may browse. Now with ALLOW_ANON_USER = false he may not browse,
68 * which is needed to disable browse PagePermissions.
69 * I added now ALLOW_ANON_EDIT = true to makes things clear.
70 * (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
72 * 3) Removed pear prepare. Performance hog, and using integers as
73 * handler doesn't help. Do simple sprintf as with adodb. And a prepare
74 * in the object init is no advantage, because in the init loop a lot of
75 * objects are tried, but not used.
76 * 4) Already gotten prefs are passed to the next object to avoid
77 * duplicate getPreferences() calls.
79 * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
80 * So we cannot just discrimate with
81 * if (!check_php_version(5))
83 * A /php5-patch.php is provided, which patches the src automatically
84 * for php4 and php5. Default is php4.
85 * Update: not needed anymore. we use eval to fool the load-time syntax checker.
87 * 6) enforced new cookie policy: prefs don't get stored in cookies
88 * anymore, only in homepage and/or database, but always in the
89 * current session. old pref cookies will get deleted.
91 * 7) Certain themes should be able to extend the predefined list
92 * of preferences. Display/editing is done in the theme specific userprefs.tmpl,
93 * but storage must be extended to the Get/SetPreferences methods.
94 * <theme>/themeinfo.php must provide CustomUserPreferences:
95 * A list of name => _UserPreference class pairs.
97 * Fixed a nasty recursion bug (i.e. php crash), when user = new class
98 * which returned false, did not return false on php-4.4.7. Check for
99 * a object member now.
102 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
103 define('WIKIAUTH_ANON', 0); // Not signed in.
104 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
105 define('WIKIAUTH_USER', 2); // Bogo user with a password.
106 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
107 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
109 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
110 //if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
111 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
112 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
113 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
115 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
116 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
117 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
119 define('TIMEOFFSET_MIN_HOURS', -26);
120 define('TIMEOFFSET_MAX_HOURS', 26);
121 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
123 /* EMAIL VERIFICATION
124 * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
125 * Provide some overrides here.
126 * ( username @ ) domain => mail-domain
128 $EMailHosts = array('avl.com' => 'mail.avl.com');
131 * There are be the following constants in config/config.ini to
132 * establish login parameters:
134 * ALLOW_ANON_USER default true
135 * ALLOW_ANON_EDIT default true
136 * ALLOW_BOGO_LOGIN default true
137 * ALLOW_USER_PASSWORDS default true
138 * PASSWORD_LENGTH_MINIMUM default 0
140 * To require user passwords for editing:
141 * ALLOW_ANON_USER = true
142 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
143 * ALLOW_BOGO_LOGIN = false
144 * ALLOW_USER_PASSWORDS = true
146 * To establish a COMPLETELY private wiki, such as an internal
148 * ALLOW_ANON_USER = false
149 * (and probably require user passwords as described above). In this
150 * case the user will be prompted to login immediately upon accessing
153 * There are other possible combinations, but the typical wiki (such
154 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
159 // The last object in the row is the bad guy...
160 if (!is_array($USER_AUTH_ORDER))
161 $USER_AUTH_ORDER = array("Forbidden");
163 $USER_AUTH_ORDER[] = "Forbidden";
165 // Local convenience functions.
166 function _isAnonUserAllowed() {
167 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
169 function _isBogoUserAllowed() {
170 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
172 function _isUserPasswordsAllowed() {
173 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
176 // Possibly upgrade userobject functions.
177 function _determineAdminUserOrOtherUser($UserName) {
178 // Sanity check. User name is a condition of the definition of the
179 // _AdminUser, _BogoUser and _passuser.
181 return $GLOBALS['ForbiddenUser'];
183 //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
184 //$group = &WikiGroup::getGroup($GLOBALS['request']);
185 if ($UserName == ADMIN_USER)
186 return new _AdminUser($UserName);
187 /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
188 return _determineBogoUserOrPassUser($UserName);
192 return _determineBogoUserOrPassUser($UserName);
195 function _determineBogoUserOrPassUser($UserName) {
196 global $ForbiddenUser;
198 // Sanity check. User name is a condition of the definition of
199 // _BogoUser and _PassUser.
201 return $ForbiddenUser;
203 // Check for password and possibly upgrade user object.
204 // $_BogoUser = new _BogoUser($UserName);
205 if (_isBogoUserAllowed() and isWikiWord($UserName)) {
206 include_once 'lib/WikiUser/BogoLogin.php';
207 $_BogoUser = new _BogoLoginPassUser($UserName);
208 if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
211 if (_isUserPasswordsAllowed()) {
212 // PassUsers override BogoUsers if a password is stored
213 if (isset($_BogoUser) and isset($_BogoUser->_prefs)
214 and $_BogoUser->_prefs->get('passwd'))
215 return new _PassUser($UserName, $_BogoUser->_prefs);
217 $_PassUser = new _PassUser($UserName,
218 isset($_BogoUser) ? $_BogoUser->_prefs : false);
219 if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
220 if (isset($GLOBALS['request']->_user_class))
221 $class = $GLOBALS['request']->_user_class;
222 elseif (strtolower(get_class($_PassUser)) == "_passuser")
223 $class = $_PassUser->nextClass();
225 $class = get_class($_PassUser);
226 if ($user = new $class($UserName, $_PassUser->_prefs)
227 and $user->_userid) {
235 // No Bogo- or PassUser exists, or
236 // passwords are not allowed, and bogo is disallowed too.
237 // (Only the admin can sign in).
238 return $ForbiddenUser;
242 * Primary WikiUser function, called by lib/main.php.
244 * This determines the user's type and returns an appropriate user
245 * object. lib/main.php then querys the resultant object for password
246 * validity as necessary.
248 * If an _AnonUser object is returned, the user may only browse pages
249 * (and save prefs in a cookie).
251 * To disable access but provide prefs the global $ForbiddenUser class
252 * is returned. (was previously false)
255 function WikiUser ($UserName = '') {
256 global $ForbiddenUser, $HTTP_SESSION_VARS;
258 //Maybe: Check sessionvar for username & save username into
259 //sessionvar (may be more appropriate to do this in lib/main.php).
261 $ForbiddenUser = new _ForbiddenUser($UserName);
262 // Found a user name.
263 return _determineAdminUserOrOtherUser($UserName);
265 elseif (!empty($HTTP_SESSION_VARS['userid'])) {
266 // Found a user name.
267 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
268 return _determineAdminUserOrOtherUser($_SESSION['userid']);
271 // Check for autologin pref in cookie and possibly upgrade
272 // user object to another type.
273 $_AnonUser = new _AnonUser();
274 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
275 // Found a user name.
276 $ForbiddenUser = new _ForbiddenUser($UserName);
277 return _determineAdminUserOrOtherUser($UserName);
280 $ForbiddenUser = new _ForbiddenUser();
281 if (_isAnonUserAllowed())
283 return $ForbiddenUser; // User must sign in to browse pages.
285 return $ForbiddenUser; // User must sign in with a password.
288 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
289 . "Unexpectedly, an appropriate user class could not be determined.");
290 return $ForbiddenUser; // Failsafe.
295 * WikiUser.php use the name 'WikiUser'
297 function WikiUserClassname() {
303 * Upgrade olduser by copying properties from user to olduser.
304 * We are not sure yet, for which php's a simple $this = $user works reliably,
305 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
306 * that's why try it the hard way.
308 function UpgradeUser ($user, $newuser) {
309 if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) {
310 // populate the upgraded class $newuser with the values from the current user object
311 //only _auth_level, _current_method, _current_index,
312 if (!empty($user->_level) and
313 $user->_level > $newuser->_level)
314 $newuser->_level = $user->_level;
315 if (!empty($user->_current_index) and
316 $user->_current_index > $newuser->_current_index) {
317 $newuser->_current_index = $user->_current_index;
318 $newuser->_current_method = $user->_current_method;
320 if (!empty($user->_authmethod))
321 $newuser->_authmethod = $user->_authmethod;
322 $GLOBALS['request']->_user_class = get_class($newuser);
324 foreach (get_object_vars($user) as $k => $v) {
325 if (!empty($v)) $olduser->$k = $v;
328 $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
329 //$GLOBALS['request']->_user = $olduser;
337 * Probably not needed, since we use the various user objects methods so far.
338 * Anyway, here it is, looping through all available objects.
340 function UserExists ($UserName) {
342 if (!($user = $request->getUser()))
343 $user = WikiUser($UserName);
346 if ($user->userExists($UserName)) {
347 $request->_user = $user;
350 if (isa($user,'_BogoUser'))
351 $user = new _PassUser($UserName,$user->_prefs);
352 $class = $user->nextClass();
353 if ($user = new $class($UserName, $user->_prefs)) {
354 return $user->userExists($UserName);
356 $request->_user = $GLOBALS['ForbiddenUser'];
360 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
363 * Base WikiUser class.
368 var $_level = WIKIAUTH_ANON;
370 var $_HomePagehandle = false;
373 function _WikiUser($UserName='', $prefs=false) {
375 $this->_userid = $UserName;
376 $this->_HomePagehandle = false;
378 $this->hasHomePage();
380 if (empty($this->_prefs)) {
381 if ($prefs) $this->_prefs = $prefs;
382 else $this->getPreferences();
386 function UserName() {
387 if (!empty($this->_userid))
388 return $this->_userid;
391 function getPreferences() {
392 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
393 . "New subclasses of _WikiUser must override this function.");
397 function setPreferences($prefs, $id_only) {
398 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
400 . "New subclasses of _WikiUser must override this function.");
404 function userExists() {
405 return $this->hasHomePage();
408 function checkPass($submitted_password) {
409 // By definition, an undefined user class cannot sign in.
410 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
412 . "New subclasses of _WikiUser must override this function.");
416 // returns page_handle to user's home page or false if none
417 function hasHomePage() {
418 if ($this->_userid) {
419 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
420 return $this->_HomePagehandle->exists();
423 // check db again (maybe someone else created it since
426 $this->_HomePagehandle = $request->getPage($this->_userid);
427 return $this->_HomePagehandle->exists();
434 function createHomePage() {
436 $versiondata = array('author' => ADMIN_USER);
437 $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.").
438 "\n{{Template/UserPage}}",
440 $request->_dbi->touch();
441 $this->_HomePagehandle = $request->getPage($this->_userid);
444 // innocent helper: case-insensitive position in _auth_methods
445 function array_position ($string, $array) {
446 $string = strtolower($string);
447 for ($found = 0; $found < count($array); $found++) {
448 if (strtolower($array[$found]) == $string)
454 function nextAuthMethodIndex() {
455 if (empty($this->_auth_methods))
456 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
457 if (empty($this->_current_index)) {
458 if (strtolower(get_class($this)) != '_passuser') {
459 $this->_current_method = substr(get_class($this),1,-8);
460 $this->_current_index = $this->array_position($this->_current_method,
461 $this->_auth_methods);
463 $this->_current_index = -1;
466 $this->_current_index++;
467 if ($this->_current_index >= count($this->_auth_methods))
469 $this->_current_method = $this->_auth_methods[$this->_current_index];
470 return $this->_current_index;
473 function AuthMethod($index = false) {
474 return $this->_auth_methods[ $index === false
475 ? count($this->_auth_methods)-1
479 // upgrade the user object
480 function nextClass() {
481 $method = $this->AuthMethod($this->nextAuthMethodIndex());
482 include_once("lib/WikiUser/$method.php");
483 return "_".$method."PassUser";
486 //Fixme: for _HttpAuthPassUser
487 function PrintLoginForm (&$request, $args, $fail_message = false,
488 $seperate_page = false) {
489 include_once 'lib/Template.php';
490 // Call update_locale in case the system's default language is not 'en'.
491 // (We have no user pref for lang at this point yet, no one is logged in.)
492 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
493 update_locale(DEFAULT_LANGUAGE);
494 $userid = $this->_userid;
496 extract($args); // fixme
498 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
500 $pagename = $request->getArg('pagename');
502 $login = Template('login',
503 compact('pagename', 'userid', 'require_level',
504 'fail_message', 'pass_required', 'nocache'));
505 // check if the html template was already processed
506 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
507 if ($seperate_page) {
508 $page = $request->getPage($pagename);
509 $revision = $page->getCurrentRevision();
510 return GeneratePage($login,_("Sign In"), $revision);
512 return $login->printExpansion();
516 /** Signed in but not password checked or empty password.
518 function isSignedIn() {
519 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
522 /** This is password checked for sure.
524 function isAuthenticated() {
525 //return isa($this,'_PassUser');
526 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
527 return $this->_level >= WIKIAUTH_BOGO;
530 function isAdmin () {
532 if ($this->_level == WIKIAUTH_ADMIN) return true;
533 if (!$this->isSignedIn()) return false;
534 if (!$this->isAuthenticated()) return false;
536 if (!$group) $group = &$GLOBALS['request']->getGroup();
537 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
540 /** Name or IP for a signed user. UserName could come from a cookie e.g.
543 return ( $this->UserName()
545 : $GLOBALS['request']->get('REMOTE_ADDR') );
548 /** Name for an authenticated user. No IP here.
550 function getAuthenticatedId() {
551 return ( $this->isAuthenticated()
553 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
556 function hasAuthority ($require_level) {
557 return $this->_level >= $require_level;
560 /* This is quite restrictive and not according the login description online.
561 Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
562 The backends may loosen or tighten this.
564 function isValidName ($userid = false) {
565 if (!$userid) $userid = $this->_userid;
566 if (!$userid) return false;
570 return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
574 * Called on an auth_args POST request, such as login, logout or signin.
575 * TODO: Check BogoLogin users with empty password. (self-signed users)
577 function AuthCheck ($postargs) {
578 // Normalize args, and extract.
579 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
581 foreach ($keys as $key)
582 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
584 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
586 if ($logout) { // Log out
587 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
589 $zone_offset = Request_AccessLogEntry::_zone_offset();
590 $ncsa_time = date("d/M/Y:H:i:s", time());
591 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
592 (string) $request->get('REMOTE_HOST'),
593 (string) $request->_user->_userid,
594 $ncsa_time, $zone_offset,
595 "logout ".get_class($request->_user),
597 (string) $request->get('HTTP_REFERER'),
598 (string) $request->get('HTTP_USER_AGENT')
600 if (($fp = fopen(LOGIN_LOG, "a"))) {
602 fputs($fp, "$entry\n");
605 //error_log("$entry\n", 3, LOGIN_LOG);
607 if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
608 $GLOBALS['request']->_user->logout();
610 $user = new _AnonUser();
612 $user->_level = WIKIAUTH_ANON;
615 return false; // User hit cancel button.
616 elseif (!$login && !$userid)
617 return false; // Nothing to do?
619 if (!$this->isValidName($userid))
620 return _("Invalid username.");;
622 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
624 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
626 $zone_offset = Request_AccessLogEntry::_zone_offset();
627 $ncsa_time = date("d/M/Y:H:i:s", time());
628 $manglepasswd = $passwd;
629 for ($i=0; $i<strlen($manglepasswd); $i++) {
630 $c = substr($manglepasswd,$i,1);
631 if (ord($c) < 32) $manglepasswd[$i] = "<";
632 elseif ($c == '*') $manglepasswd[$i] = "*";
633 elseif ($c == '?') $manglepasswd[$i] = "?";
634 elseif ($c == '(') $manglepasswd[$i] = "(";
635 elseif ($c == ')') $manglepasswd[$i] = ")";
636 elseif ($c == "\\") $manglepasswd[$i] = "\\";
637 elseif (ord($c) < 127) $manglepasswd[$i] = "x";
638 elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
640 if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
641 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
642 $request->get('REMOTE_HOST'),
643 (string) $request->_user->_userid,
644 $ncsa_time, $zone_offset,
645 "login $userid/$manglepasswd => $authlevel ".get_class($request->_user),
646 $authlevel > 0 ? "200" : "403",
647 (string) $request->get('HTTP_REFERER'),
648 (string) $request->get('HTTP_USER_AGENT')
650 if (($fp = fopen(LOGIN_LOG, "a"))) {
652 fputs($fp, "$entry\n");
655 //error_log("$entry\n", 3, LOGIN_LOG);
658 if ($authlevel <= 0) { // anon or forbidden
660 return _("Invalid password.");
662 return _("Invalid password or userid.");
663 } elseif ($authlevel < $require_level) { // auth ok, but not enough
664 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
667 $class = "_" . $this->_current_method . "PassUser";
668 include_once 'lib/WikiUser/'.$this->_current_method.'.php';
669 $user = new $class($userid,$this->_prefs);
670 if (!check_php_version(5))
671 eval("\$this = \$user;");
672 // /*PHP5 patch*/$this = $user;
673 $this->_level = $authlevel;
676 $this->_userid = $userid;
677 $this->_level = $authlevel;
678 return _("Insufficient permissions.");
682 //$user = $GLOBALS['request']->_user;
683 if (!empty($this->_current_method) and
684 strtolower(get_class($this)) == '_passuser')
687 $class = "_" . $this->_current_method . "PassUser";
688 include_once 'lib/WikiUser/'.$this->_current_method.'.php';
689 $user = new $class($userid, $this->_prefs);
690 if (!check_php_version(5))
691 eval("\$this = \$user;");
692 // /*PHP5 patch*/$this = $user;
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 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
712 /** Anon only gets to load and save prefs in a cookie, that's it.
714 function getPreferences() {
717 if (empty($this->_prefs))
718 $this->_prefs = new UserPreferences;
719 $UserName = $this->UserName();
721 // Try to read deprecated 1.3.x style cookies
722 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
723 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
724 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
726 . sprintf("%s='%s'", WIKI_NAME, $cookie)
728 . _("Default preferences will be used."),
732 * Only set if it matches the UserName who is
733 * signing in or if this really is an Anon login (no
734 * username). (Remember, _BogoUser and higher inherit this
737 if (! $UserName || $UserName == @$unboxedcookie['userid']) {
738 $updated = $this->_prefs->updatePrefs($unboxedcookie);
739 //$this->_prefs = new UserPreferences($unboxedcookie);
740 $UserName = @$unboxedcookie['userid'];
741 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
742 $this->_userid = $UserName;
746 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
748 $request->deleteCookieVar(WIKI_NAME);
750 // Try to read deprecated 1.3.4 style cookies
751 if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
752 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
753 if (! $UserName || $UserName == $unboxedcookie['userid']) {
754 $updated = $this->_prefs->updatePrefs($unboxedcookie);
755 //$this->_prefs = new UserPreferences($unboxedcookie);
756 $UserName = $unboxedcookie['userid'];
757 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
758 $this->_userid = $UserName;
763 $request->deleteCookieVar("WIKI_PREF2");
767 // Try reading userid from old PhpWiki cookie formats:
768 if ($cookie = $request->cookies->get_old(getCookieName())) {
769 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
771 elseif (is_array($cookie) and !empty($cookie['userid']))
772 $UserName = $cookie['userid'];
774 if (! $UserName and !headers_sent())
775 $request->deleteCookieVar(getCookieName());
777 $this->_userid = $UserName;
780 // initializeTheme() needs at least an empty object
782 if (empty($this->_prefs))
783 $this->_prefs = new UserPreferences;
785 return $this->_prefs;
788 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
790 * Allow for multiple wikis in same domain. Encode only the
791 * _prefs array of the UserPreference object. Ideally the
792 * prefs array should just be imploded into a single string or
793 * something so it is completely human readable by the end
794 * user. In that case stricter error checking will be needed
795 * when loading the cookie.
797 function setPreferences($prefs, $id_only=false) {
798 if (!is_object($prefs)) {
799 if (is_object($this->_prefs)) {
800 $updated = $this->_prefs->updatePrefs($prefs);
801 $prefs =& $this->_prefs;
803 // update the prefs values from scratch. This could leed to unnecessary
804 // side-effects: duplicate emailVerified, ...
805 $this->_prefs = new UserPreferences($prefs);
809 if (!isset($this->_prefs))
810 $this->_prefs =& $prefs;
812 $updated = $this->_prefs->isChanged($prefs);
815 if ($id_only and !headers_sent()) {
817 // new 1.3.8 policy: no array cookies, only plain userid string as in
818 // the pre 1.3.x versions.
819 // prefs should be stored besides the session in the homepagehandle or in a db.
820 $request->setCookieVar(getCookieName(), $this->_userid,
821 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
822 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
823 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
826 if (is_object($prefs)) {
827 $packed = $prefs->store();
828 $unpacked = $prefs->unpack($packed);
829 if (count($unpacked)) {
830 foreach (array('_method','_select','_update','_insert') as $param) {
831 if (!empty($this->_prefs->{$param}))
832 $prefs->{$param} = $this->_prefs->{$param};
834 $this->_prefs = $prefs;
840 function userExists() {
844 function checkPass($submitted_password) {
846 // this might happen on a old-style signin button.
848 // By definition, the _AnonUser does not HAVE a password
849 // (compared to _BogoUser, who has an EMPTY password).
850 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
851 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
852 . "New subclasses of _WikiUser must override this function.");
859 * Helper class to finish the PassUser auth loop.
860 * This is added automatically to USER_AUTH_ORDER.
865 var $_level = WIKIAUTH_FORBIDDEN;
867 function checkPass($submitted_password) {
868 return WIKIAUTH_FORBIDDEN;
871 function userExists() {
872 if ($this->_HomePagehandle) return true;
878 * Do NOT extend _BogoUser to other classes, for checkPass()
879 * security. (In case of defects in code logic of the new class!)
880 * The intermediate step between anon and passuser.
881 * We also have the _BogoLoginPassUser class with stricter
882 * password checking, which fits into the auth loop.
883 * Note: This class is not called anymore by WikiUser()
888 function userExists() {
889 if (isWikiWord($this->_userid)) {
890 $this->_level = WIKIAUTH_BOGO;
893 $this->_level = WIKIAUTH_ANON;
898 function checkPass($submitted_password) {
899 // By definition, BogoUser has an empty password.
901 return $this->_level;
908 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
910 * The classes for all subsequent auth methods extend from this class.
911 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
912 * the three auth method policies first-only, strict and stacked
913 * and the two methods for prefs: homepage or database,
914 * if $DBAuthParams['pref_select'] is defined.
916 * Default is PersonalPage auth and prefs.
918 * @author: Reini Urban
922 var $_auth_dbi, $_prefs;
923 var $_current_method, $_current_index;
925 // check and prepare the auth and pref methods only once
926 function _PassUser($UserName='', $prefs=false) {
927 //global $DBAuthParams, $DBParams;
929 /*if (!$this->isValidName($UserName))
931 $this->_userid = $UserName;
932 if ($this->hasHomePage())
933 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
935 $this->_authmethod = substr(get_class($this),1,-8);
936 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
938 // Check the configured Prefs methods
939 $dbi = $this->getAuthDbh();
940 $dbh = $GLOBALS['request']->getDbh();
943 and !isset($this->_prefs->_select)
944 and $dbh->getAuthParam('pref_select'))
946 if (!$this->_prefs) {
947 $this->_prefs = new UserPreferences();
950 $this->_prefs->_method = $dbh->getParam('dbtype');
951 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
953 if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
954 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
955 array("userid", "pref_blob"));
958 if (!$this->_prefs) {
959 $this->_prefs = new UserPreferences();
962 $this->_prefs->_method = 'HomePage';
965 if (! $this->_prefs or isset($need_pref) ) {
966 if ($prefs) $this->_prefs = $prefs;
967 else $this->getPreferences();
970 // Upgrade to the next parent _PassUser class. Avoid recursion.
971 if ( strtolower(get_class($this)) === '_passuser' ) {
972 //auth policy: Check the order of the configured auth methods
973 // 1. first-only: Upgrade the class here in the constructor
974 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
975 /// in the previous PhpWiki releases (slow)
976 // 3. strict: upgrade the class after checking the user existance in userExists()
977 // 4. stacked: upgrade the class after the password verification in checkPass()
978 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
979 //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
980 if (defined('USER_AUTH_POLICY')) {
981 // policy 1: only pre-define one method for all users
982 if (USER_AUTH_POLICY === 'first-only') {
983 $class = $this->nextClass();
984 return new $class($UserName,$this->_prefs);
986 // Use the default behaviour from the previous versions:
987 elseif (USER_AUTH_POLICY === 'old') {
988 // Default: try to be smart
989 // On php5 we can directly return and upgrade the Object,
990 // before we have to upgrade it manually.
991 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
992 include_once 'lib/WikiUser/HttpAuth.php';
993 if (check_php_version(5))
994 return new _HttpAuthPassUser($UserName,$this->_prefs);
996 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
997 eval("\$this = \$user;");
998 // /*PHP5 patch*/$this = $user;
1001 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1002 $dbh->getAuthParam('auth_check') and
1003 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
1004 if (check_php_version(5))
1005 return new _DbPassUser($UserName,$this->_prefs);
1007 $user = new _DbPassUser($UserName,$this->_prefs);
1008 eval("\$this = \$user;");
1009 // /*PHP5 patch*/$this = $user;
1012 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1013 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
1014 function_exists('ldap_connect')) {
1015 include_once 'lib/WikiUser/LDAP.php';
1016 if (check_php_version(5))
1017 return new _LDAPPassUser($UserName,$this->_prefs);
1019 $user = new _LDAPPassUser($UserName,$this->_prefs);
1020 eval("\$this = \$user;");
1021 // /*PHP5 patch*/$this = $user;
1024 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1025 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
1026 include_once 'lib/WikiUser/IMAP.php';
1027 if (check_php_version(5))
1028 return new _IMAPPassUser($UserName,$this->_prefs);
1030 $user = new _IMAPPassUser($UserName,$this->_prefs);
1031 eval("\$this = \$user;");
1032 // /*PHP5 patch*/$this = $user;
1035 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1036 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
1037 include_once 'lib/WikiUser/File.php';
1038 if (check_php_version(5))
1039 return new _FilePassUser($UserName, $this->_prefs);
1041 $user = new _FilePassUser($UserName, $this->_prefs);
1042 eval("\$this = \$user;");
1043 // /*PHP5 patch*/$this = $user;
1047 include_once 'lib/WikiUser/PersonalPage.php';
1048 if (check_php_version(5))
1049 return new _PersonalPagePassUser($UserName,$this->_prefs);
1051 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
1052 eval("\$this = \$user;");
1053 // /*PHP5 patch*/$this = $user;
1059 // else use the page methods defined in _PassUser.
1065 function getAuthDbh () {
1066 global $request; //, $DBParams, $DBAuthParams;
1068 $dbh = $request->getDbh();
1069 // session restauration doesn't re-connect to the database automatically,
1070 // so dirty it here, to force a reconnect.
1071 if (isset($this->_auth_dbi)) {
1072 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1073 unset($this->_auth_dbi);
1074 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1075 unset($this->_auth_dbi);
1077 if (empty($this->_auth_dbi)) {
1078 if ($dbh->getParam('dbtype') != 'SQL'
1079 and $dbh->getParam('dbtype') != 'ADODB'
1080 and $dbh->getParam('dbtype') != 'PDO')
1082 if (empty($GLOBALS['DBAuthParams']))
1084 if (!$dbh->getAuthParam('auth_dsn')) {
1085 $dbh = $request->getDbh(); // use phpwiki database
1086 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1087 $dbh = $request->getDbh(); // same phpwiki database
1088 } else { // use another external database handle. needs PHP >= 4.1
1089 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1090 $local_params['dsn'] = $local_params['auth_dsn'];
1091 $dbh = WikiDB::open($local_params);
1093 $this->_auth_dbi =& $dbh->_backend->_dbh;
1095 return $this->_auth_dbi;
1098 function _normalize_stmt_var($var, $oldstyle = false) {
1099 static $valid_variables = array('userid','password','pref_blob','groupname');
1100 // old-style: "'$userid'"
1101 // new-style: '"\$userid"' or just "userid"
1102 $new = str_replace(array("'",'"','\$','$'),'',$var);
1103 if (!in_array($new, $valid_variables)) {
1104 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1107 return !$oldstyle ? "'$".$new."'" : '\$'.$new;
1110 // TODO: use it again for the auth and member tables
1111 // sprintfstyle vs prepare style: %s or ?
1112 // multiple vars should be executed via prepare(?,?)+execute,
1113 // single vars with execute(sprintf(quote(var)))
1114 // help with position independency
1115 function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) {
1117 $dbi = $request->getDbh();
1118 $this->getAuthDbh();
1119 // "'\$userid"' => %s
1120 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1121 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1123 if (is_array($variables)) {
1124 //$sprintfstyle = false;
1125 for ($i=0; $i < count($variables); $i++) {
1126 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1128 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1129 $variables[$i], $stmt), E_USER_WARNING);
1130 $variables[$i] = $var;
1131 if (!$var) $new[] = '';
1133 $s = "%" . ($i+1) . "s";
1134 $new[] = $sprintfstyle ? $s : "?";
1138 $var = $this->_normalize_stmt_var($variables, $oldstyle);
1140 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1141 $variables, $stmt), E_USER_WARNING);
1143 if (!$var) $new = '';
1144 else $new = $sprintfstyle ? '%s' : "?";
1146 $prefix = $dbi->getParam('prefix');
1147 // probably prefix table names if in same database
1148 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1149 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1151 if (!stristr($stmt, $prefix)) {
1153 $stmt = str_replace(array(" user "," pref "," member "),
1154 array(" ".$prefix."user ",
1155 " ".$prefix."pref ",
1156 " ".$prefix."member "), $stmt);
1157 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1158 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt",
1162 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1163 // Simple sprintf-style.
1164 $new_stmt = str_replace($variables, $new, $stmt);
1165 if ($new_stmt == $stmt) {
1167 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1168 $stmt), E_USER_WARNING);
1170 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1171 $stmt), E_USER_WARNING);
1172 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1178 function getPreferences() {
1179 if (!empty($this->_prefs->_method)) {
1180 if ($this->_prefs->_method == 'ADODB') {
1181 // FIXME: strange why this should be needed...
1182 include_once 'lib/WikiUser/Db.php';
1183 include_once 'lib/WikiUser/AdoDb.php';
1184 return _AdoDbPassUser::getPreferences();
1185 } elseif ($this->_prefs->_method == 'SQL') {
1186 include_once 'lib/WikiUser/Db.php';
1187 include_once 'lib/WikiUser/PearDb.php';
1188 return _PearDbPassUser::getPreferences();
1189 } elseif ($this->_prefs->_method == 'PDO') {
1190 include_once 'lib/WikiUser/Db.php';
1191 include_once 'lib/WikiUser/PdoDb.php';
1192 return _PdoDbPassUser::getPreferences();
1196 // We don't necessarily have to read the cookie first. Since
1197 // the user has a password, the prefs stored in the homepage
1198 // cannot be arbitrarily altered by other Bogo users.
1199 _AnonUser::getPreferences();
1200 // User may have deleted cookie, retrieve from his
1201 // PersonalPage if there is one.
1202 if (!empty($this->_HomePagehandle)) {
1203 if ($restored_from_page = $this->_prefs->retrieve
1204 ($this->_HomePagehandle->get('pref'))) {
1205 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1206 //$this->_prefs = new UserPreferences($restored_from_page);
1207 return $this->_prefs;
1210 return $this->_prefs;
1213 function setPreferences($prefs, $id_only=false) {
1214 if (!empty($this->_prefs->_method)) {
1215 if ($this->_prefs->_method == 'ADODB') {
1216 // FIXME: strange why this should be needed...
1217 include_once 'lib/WikiUser/Db.php';
1218 include_once 'lib/WikiUser/AdoDb.php';
1219 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1221 elseif ($this->_prefs->_method == 'SQL') {
1222 include_once 'lib/WikiUser/Db.php';
1223 include_once 'lib/WikiUser/PearDb.php';
1224 return _PearDbPassUser::setPreferences($prefs, $id_only);
1226 elseif ($this->_prefs->_method == 'PDO') {
1227 include_once 'lib/WikiUser/Db.php';
1228 include_once 'lib/WikiUser/PdoDb.php';
1229 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1232 if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1233 // Encode only the _prefs array of the UserPreference object
1234 // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1235 if (empty($this->_HomePagehandle)) {
1236 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1238 if (! $this->_HomePagehandle->exists() ) {
1239 $this->createHomePage();
1241 if (!empty($this->_HomePagehandle) and !$id_only) {
1242 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1248 function mayChangePass() {
1252 //The default method is getting the password from prefs.
1253 // child methods obtain $stored_password from external auth.
1254 function userExists() {
1255 //if ($this->_HomePagehandle) return true;
1256 if (strtolower(get_class($this)) == "_passuser") {
1257 $class = $this->nextClass();
1258 $user = new $class($this->_userid, $this->_prefs);
1262 /* new user => false does not return false, but the _userid is empty then */
1263 while ($user and $user->_userid) {
1264 if (!check_php_version(5))
1265 eval("\$this = \$user;");
1266 $user = UpgradeUser($this, $user);
1267 if ($user->userExists()) {
1268 $user = UpgradeUser($this, $user);
1271 // prevent endless loop. does this work on all PHP's?
1272 // it just has to set the classname, what it correctly does.
1273 $class = $user->nextClass();
1274 if ($class == "_ForbiddenPassUser")
1280 //The default method is getting the password from prefs.
1281 // child methods obtain $stored_password from external auth.
1282 function checkPass($submitted_password) {
1283 $stored_password = $this->_prefs->get('passwd');
1284 if ($this->_checkPass($submitted_password, $stored_password)) {
1285 $this->_level = WIKIAUTH_USER;
1286 return $this->_level;
1288 if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1289 $this->_level = WIKIAUTH_FORBIDDEN;
1290 return $this->_level;
1292 return $this->_tryNextPass($submitted_password);
1297 function _checkPassLength($submitted_password) {
1298 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1299 trigger_error(_("The length of the password is shorter than the system policy allows."));
1306 * The basic password checker for all PassUser objects.
1307 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1308 * Empty passwords are always false!
1309 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1310 * @see UserPreferences::set
1312 * DBPassUser password's have their own crypt definition.
1313 * That's why DBPassUser::checkPass() doesn't call this method, if
1314 * the db password method is 'plain', which means that the DB SQL
1315 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1316 * don't store plain passwords in the DB.
1318 * TODO: remove crypt() function check from config.php:396 ??
1320 function _checkPass($submitted_password, $stored_password) {
1321 if (!empty($submitted_password)) {
1322 // This works only on plaintext passwords.
1323 if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1324 // With the EditMetaData plugin
1325 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."));
1328 if (!$this->_checkPassLength($submitted_password)) {
1331 if (ENCRYPTED_PASSWD) {
1332 // Verify against encrypted password.
1333 if (function_exists('crypt')) {
1334 if (crypt($submitted_password, $stored_password) == $stored_password )
1335 return true; // matches encrypted password
1340 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1341 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1347 // Verify against cleartext password.
1348 if ($submitted_password == $stored_password)
1351 // Check whether we forgot to enable ENCRYPTED_PASSWD
1352 if (function_exists('crypt')) {
1353 if (crypt($submitted_password, $stored_password) == $stored_password) {
1354 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1365 /** The default method is storing the password in prefs.
1366 * Child methods (DB, File) may store in external auth also, but this
1367 * must be explicitly enabled.
1368 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1370 function changePass($submitted_password) {
1371 $stored_password = $this->_prefs->get('passwd');
1372 // check if authenticated
1373 if (!$this->isAuthenticated()) return false;
1374 if (ENCRYPTED_PASSWD) {
1375 $submitted_password = crypt($submitted_password);
1377 // check other restrictions, with side-effects only.
1378 $result = $this->_checkPass($submitted_password, $stored_password);
1379 if ($stored_password != $submitted_password) {
1380 $this->_prefs->set('passwd', $submitted_password);
1381 //update the storage (session, homepage, ...)
1382 $this->SetPreferences($this->_prefs);
1385 //Todo: return an error msg to the caller what failed?
1386 // same password or no privilege
1387 return ENCRYPTED_PASSWD ? true : false;
1390 function _tryNextPass($submitted_password) {
1391 if (DEBUG & _DEBUG_LOGIN) {
1392 $class = strtolower(get_class($this));
1393 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1394 $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1396 if (USER_AUTH_POLICY === 'strict') {
1397 $class = $this->nextClass();
1398 if ($user = new $class($this->_userid,$this->_prefs)) {
1399 if ($user->userExists()) {
1400 return $user->checkPass($submitted_password);
1404 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1405 $class = $this->nextClass();
1406 if ($user = new $class($this->_userid,$this->_prefs))
1407 return $user->checkPass($submitted_password);
1409 return $this->_level;
1412 function _tryNextUser() {
1413 if (DEBUG & _DEBUG_LOGIN) {
1414 $class = strtolower(get_class($this));
1415 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1416 $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1418 if (USER_AUTH_POLICY === 'strict'
1419 or USER_AUTH_POLICY === 'stacked') {
1420 $class = $this->nextClass();
1421 while ($user = new $class($this->_userid, $this->_prefs)) {
1422 if (!check_php_version(5))
1423 eval("\$this = \$user;");
1424 $user = UpgradeUser($this, $user);
1425 if ($user->userExists()) {
1426 $user = UpgradeUser($this, $user);
1429 if ($class == "_ForbiddenPassUser") return false;
1430 $class = $this->nextClass();
1439 * Insert more auth classes here...
1440 * For example a customized db class for another db connection
1441 * or a socket-based auth server.
1447 * For security, this class should not be extended. Instead, extend
1448 * from _PassUser (think of this as unix "root").
1450 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1451 * Other members of the Administrators group must raise their level otherwise somehow.
1452 * Currently every member is a AdminUser, which will not work for the various
1458 function mayChangePass() {
1461 function checkPass($submitted_password) {
1462 if ($this->_userid == ADMIN_USER)
1463 $stored_password = ADMIN_PASSWD;
1465 // Should not happen! Only ADMIN_USER should use this class.
1466 // return $this->_tryNextPass($submitted_password); // ???
1467 // TODO: safety check if really member of the ADMIN group?
1468 $stored_password = $this->_pref->get('passwd');
1470 if ($this->_checkPass($submitted_password, $stored_password)) {
1471 $this->_level = WIKIAUTH_ADMIN;
1472 if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1474 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1476 return $this->_level;
1478 return $this->_tryNextPass($submitted_password);
1479 //$this->_level = WIKIAUTH_ANON;
1480 //return $this->_level;
1484 function storePass($submitted_password) {
1485 if ($this->_userid == ADMIN_USER)
1488 // should not happen! only ADMIN_USER should use this class.
1489 return parent::storePass($submitted_password);
1494 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1496 * Various data classes for the preference types,
1497 * to support get, set, sanify (range checking, ...)
1498 * update() will do the neccessary side-effects if a
1499 * setting gets changed (theme, language, ...)
1502 class _UserPreference
1506 function _UserPreference ($default_value) {
1507 $this->default_value = $default_value;
1510 function sanify ($value) {
1511 return (string)$value;
1514 function get ($name) {
1515 if (isset($this->{$name}))
1516 return $this->{$name};
1518 return $this->default_value;
1521 function getraw ($name) {
1522 if (!empty($this->{$name}))
1523 return $this->{$name};
1526 // stores the value as $this->$name, and not as $this->value (clever?)
1527 function set ($name, $value) {
1529 $value = $this->sanify($value);
1530 if ($this->get($name) != $value) {
1531 $this->update($value);
1534 if ($value != $this->default_value) {
1535 $this->{$name} = $value;
1537 unset($this->{$name});
1542 // default: no side-effects
1543 function update ($value) {
1548 class _UserPreference_numeric
1549 extends _UserPreference
1551 function _UserPreference_numeric ($default, $minval = false,
1553 $this->_UserPreference((double)$default);
1554 $this->_minval = (double)$minval;
1555 $this->_maxval = (double)$maxval;
1558 function sanify ($value) {
1559 $value = (double)$value;
1560 if ($this->_minval !== false && $value < $this->_minval)
1561 $value = $this->_minval;
1562 if ($this->_maxval !== false && $value > $this->_maxval)
1563 $value = $this->_maxval;
1568 class _UserPreference_int
1569 extends _UserPreference_numeric
1571 function _UserPreference_int ($default, $minval = false, $maxval = false) {
1572 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1575 function sanify ($value) {
1576 return (int)parent::sanify((int)$value);
1580 class _UserPreference_bool
1581 extends _UserPreference
1583 function _UserPreference_bool ($default = false) {
1584 $this->_UserPreference((bool)$default);
1587 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) {
1612 $this->_UserPreference($default);
1615 // FIXME: check for valid locale
1616 function sanify ($value) {
1617 // Revert to DEFAULT_LANGUAGE if user does not specify
1618 // language in UserPreferences or chooses <system language>.
1619 if ($value == '' or empty($value))
1620 $value = DEFAULT_LANGUAGE;
1622 return (string) $value;
1625 function update ($newvalue) {
1626 if (! $this->_init ) {
1627 // invalidate etag to force fresh output
1628 $GLOBALS['request']->setValidators(array('%mtime' => false));
1629 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1634 class _UserPreference_theme
1635 extends _UserPreference
1637 function _UserPreference_theme ($default = THEME) {
1638 $this->_UserPreference($default);
1641 function sanify ($value) {
1642 if (!empty($value) and FindFile($this->_themefile($value)))
1644 return $this->default_value;
1647 function update ($newvalue) {
1649 // invalidate etag to force fresh output
1650 if (! $this->_init )
1651 $GLOBALS['request']->setValidators(array('%mtime' => false));
1653 include_once($this->_themefile($newvalue));
1654 if (empty($WikiTheme))
1655 include_once($this->_themefile(THEME));
1658 function _themefile ($theme) {
1659 return "themes/$theme/themeinfo.php";
1663 class _UserPreference_notify
1664 extends _UserPreference
1666 function sanify ($value) {
1670 return $this->default_value;
1673 /** update to global user prefs: side-effect on set notify changes
1674 * use a global_data notify hash:
1675 * notify = array('pagematch' => array(userid => ('email' => mail,
1676 * 'verified' => 0|1),
1680 function update ($value) {
1681 if (!empty($this->_init)) return;
1682 $dbh = $GLOBALS['request']->getDbh();
1683 $notify = $dbh->get('notify');
1688 // expand to existing pages only or store matches?
1689 // for now we store (glob-style) matches which is easier for the user
1690 $pages = $this->_page_split($value);
1691 // Limitation: only current user.
1692 $user = $GLOBALS['request']->getUser();
1693 if (!$user or !method_exists($user,'UserName')) return;
1694 // This fails with php5 and a WIKI_ID cookie:
1695 $userid = $user->UserName();
1696 $email = $user->_prefs->get('email');
1697 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1698 // check existing notify hash and possibly delete pages for email
1699 if (!empty($data)) {
1700 foreach ($data as $page => $users) {
1701 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1702 unset($data[$page][$userid]);
1704 if (count($data[$page]) == 0)
1705 unset($data[$page]);
1708 // add the new pages
1709 if (!empty($pages)) {
1710 foreach ($pages as $page) {
1711 if (!isset($data[$page]))
1712 $data[$page] = array();
1713 if (!isset($data[$page][$userid])) {
1714 // should we really store the verification notice here or
1715 // check it dynamically at every page->save?
1717 $data[$page][$userid] = array('email' => $email,
1718 'verified' => $verified);
1720 $data[$page][$userid] = array('email' => $email);
1725 // store users changes
1726 $dbh->set('notify',$data);
1729 /** split the user-given comma or whitespace delimited pagenames
1732 function _page_split($value) {
1733 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1737 class _UserPreference_email
1738 extends _UserPreference
1740 function get($name) {
1741 // get e-mail address from FusionForge
1742 if (FUSIONFORGE && session_loggedin()) {
1743 $user = session_get_user();
1744 return $user->getEmail();
1750 function sanify($value) {
1751 // e-mail address is already checked by FusionForge
1752 if (FUSIONFORGE) return $value;
1753 // check for valid email address
1754 if ($this->get('email') == $value and $this->getraw('emailVerified'))
1757 if ($value == 1 or $value === true)
1759 list($ok,$msg) = ValidateMail($value,'noconnect');
1763 trigger_error("E-mail Validation Error: ".$msg, E_USER_WARNING);
1764 return $this->default_value;
1768 /** Side-effect on email changes:
1769 * Send a verification mail or for now just a notification email.
1770 * For true verification (value = 2), we'd need a mailserver hook.
1772 function update($value) {
1773 // e-mail address is already checked by FusionForge
1774 if (FUSIONFORGE) return $value;
1775 if (!empty($this->_init)) return;
1776 $verified = $this->getraw('emailVerified');
1778 if (($value == 1 or $value === true) and $verified)
1780 if (!empty($value) and !$verified) {
1781 list($ok,$msg) = ValidateMail($value);
1782 if ($ok and mail($value,"[".WIKI_NAME ."] "._("E-mail address confirmation"),
1783 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1784 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) {
1785 $this->set('emailVerified',1);
1787 trigger_error($msg, E_USER_WARNING);
1793 /** Check for valid email address
1794 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1795 Note: too strict, Bug #1053681
1797 function ValidateMail($email, $noconnect=false) {
1799 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1801 // if this check is too strict (like invalid mail addresses in a local network only)
1802 // uncomment the following line:
1803 //return array(true,"not validated");
1804 // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1808 // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1809 // addresses, from the Perl module Mail::RFC822::Address, reduced to
1810 // accept single RFC822 addresses without comments only. (The original
1811 // accepts groups and properly commented addresses also.)
1812 $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1814 $specials = '()<>@,;:\\\\".\\[\\]';
1815 $controls = '\\000-\\031';
1817 $dtext = "[^\\[\\]\\r\\\\]";
1818 $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1820 $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1822 $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1823 $word = "(?:$atom|$quoted_string)";
1824 $localpart = "$word(?:\\.$lwsp*$word)*";
1826 $sub_domain = "(?:$atom|$domain_literal)";
1827 $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1829 $addr_spec = "$localpart\@$lwsp*$domain";
1832 $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1833 $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1834 $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1836 $rfc822re = "/$lwsp*$mailbox/";
1837 unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1838 $atom, $word, $quoted_string);
1839 unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1841 if (!preg_match($rfc822re, $email)) {
1843 $result[1] = sprintf(_("E-mail address '%s' is not properly formatted"), $email);
1847 return array(true, sprintf(_("E-mail address '%s' is properly formatted"), $email));
1849 list ( $Username, $Domain ) = explode("@", $email);
1850 //Todo: getmxrr workaround on windows or manual input field to verify it manually
1851 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1852 $ConnectAddress = $MXHost[0];
1854 $ConnectAddress = $Domain;
1855 if (isset($EMailHosts[ $Domain ])) {
1856 $ConnectAddress = $EMailHosts[ $Domain ];
1859 $Connect = @fsockopen ( $ConnectAddress, 25 );
1861 if (ereg("^220", $Out = fgets($Connect, 1024))) {
1862 fputs ($Connect, "HELO $HTTP_HOST\r\n");
1863 $Out = fgets ( $Connect, 1024 );
1864 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
1865 $From = fgets ( $Connect, 1024 );
1866 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
1867 $To = fgets ($Connect, 1024);
1868 fputs ($Connect, "QUIT\r\n");
1870 if (!ereg ("^250", $From)) {
1872 $result[1]="Server rejected address: ". $From;
1875 if (!ereg ( "^250", $To )) {
1877 $result[1]="Server rejected address: ". $To;
1882 $result[1] = "No response from server";
1887 $result[1]="Cannot connect e-mail server.";
1891 $result[1]="E-mail address '$email' appears to be valid.";
1893 } // end of function
1895 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1900 * This object holds the $request->_prefs subobjects.
1901 * A simple packed array of non-default values get's stored as cookie,
1902 * homepage, or database, which are converted to the array of
1904 * We don't store the objects, because otherwise we will
1905 * not be able to upgrade any subobject. And it's a waste of space also.
1908 class UserPreferences
1910 var $notifyPagesAll;
1912 function UserPreferences($saved_prefs = false) {
1913 // userid stored too, to ensure the prefs are being loaded for
1914 // the correct (currently signing in) userid if stored in a
1916 // Update: for db prefs we disallow passwd.
1917 // userid is needed for pref reflexion. current pref must know its username,
1918 // if some app needs prefs from different users, different from current user.
1921 'userid' => new _UserPreference(''),
1922 'passwd' => new _UserPreference(''),
1923 'autologin' => new _UserPreference_bool(),
1924 //'emailVerified' => new _UserPreference_emailVerified(),
1925 //fixed: store emailVerified as email parameter, 1.3.8
1926 'email' => new _UserPreference_email(''),
1927 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1928 'theme' => new _UserPreference_theme(THEME),
1929 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1930 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1932 EDITWIDTH_MAX_COLS),
1933 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1934 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1935 EDITHEIGHT_MIN_ROWS,
1936 EDITHEIGHT_MAX_ROWS),
1937 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1938 TIMEOFFSET_MIN_HOURS,
1939 TIMEOFFSET_MAX_HOURS),
1940 'ownModifications' => new _UserPreference_bool(),
1941 'majorModificationsOnly' => new _UserPreference_bool(),
1942 'relativeDates' => new _UserPreference_bool(),
1943 'googleLink' => new _UserPreference_bool(), // 1.3.10
1944 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1947 // This should be probably be done with $customUserPreferenceColumns
1948 // For now, we use FUSIONFORGE define
1950 $fusionforgeprefs = array(
1951 'pageTrail' => new _UserPreference_bool(),
1952 'diffMenuItem' => new _UserPreference_bool(),
1953 'pageInfoMenuItem' => new _UserPreference_bool(),
1954 'pdfMenuItem' => new _UserPreference_bool(),
1955 'lockMenuItem' => new _UserPreference_bool(),
1956 'chownMenuItem' => new _UserPreference_bool(),
1957 'setaclMenuItem' => new _UserPreference_bool(),
1958 'removeMenuItem' => new _UserPreference_bool(),
1959 'renameMenuItem' => new _UserPreference_bool(),
1960 'revertMenuItem' => new _UserPreference_bool(),
1961 'backLinksMenuItem' => new _UserPreference_bool(),
1962 'watchPageMenuItem' => new _UserPreference_bool(),
1963 'recentChangesMenuItem' => new _UserPreference_bool(),
1964 'randomPageMenuItem' => new _UserPreference_bool(),
1965 'likePagesMenuItem' => new _UserPreference_bool(),
1966 'specialPagesMenuItem' => new _UserPreference_bool(),
1968 $this->_prefs = array_merge($this->_prefs, $fusionforgeprefs);
1971 // add custom theme-specific pref types:
1972 // FIXME: on theme changes the wiki_user session pref object will fail.
1973 // We will silently ignore this.
1974 if (!empty($customUserPreferenceColumns))
1975 $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
1977 if (isset($this->_method) and $this->_method == 'SQL') {
1978 //unset($this->_prefs['userid']);
1979 unset($this->_prefs['passwd']);
1982 if (is_array($saved_prefs)) {
1983 foreach ($saved_prefs as $name => $value)
1984 $this->set($name, $value);
1988 function __clone() {
1989 foreach ($this as $key => $val) {
1990 if (is_object($val) || (is_array($val))) {
1991 $this->{$key} = unserialize(serialize($val));
1996 function _getPref($name) {
1997 if ($name == 'emailVerified')
1999 if (!isset($this->_prefs[$name])) {
2000 if ($name == 'passwd2') return false;
2001 if ($name == 'passwd') return false;
2002 trigger_error("$name: unknown preference", E_USER_NOTICE);
2005 return $this->_prefs[$name];
2008 // get the value or default_value of the subobject
2009 function get($name) {
2010 if ($_pref = $this->_getPref($name))
2011 if ($name == 'emailVerified')
2012 return $_pref->getraw($name);
2014 return $_pref->get($name);
2019 // check and set the new value in the subobject
2020 function set($name, $value) {
2021 $pref = $this->_getPref($name);
2022 if ($pref === false)
2025 /* do it here or outside? */
2026 if ($name == 'passwd' and
2027 defined('PASSWORD_LENGTH_MINIMUM') and
2028 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2029 //TODO: How to notify the user?
2033 if ($name == 'theme' and $value == '')
2036 // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2037 if ((!$value and $pref->default_value)
2038 or ($value and !isset($pref->{$name})) // bug #1355533
2039 or ($value and ($pref->{$name} != $pref->default_value)))
2041 if ($name == 'emailVerified') $newvalue = $value;
2042 else $newvalue = $pref->sanify($value);
2043 $pref->set($name, $newvalue);
2045 $this->_prefs[$name] =& $pref;
2049 * use init to avoid update on set
2051 function updatePrefs($prefs, $init = false) {
2053 if ($init) $this->_init = $init;
2054 if (is_object($prefs)) {
2055 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2056 $obj->_init = $init;
2057 if ($obj->get($type) !== $prefs->get($type)) {
2058 if ($obj->set($type, $prefs->get($type)))
2061 foreach (array_keys($this->_prefs) as $type) {
2062 $obj =& $this->_prefs[$type];
2063 $obj->_init = $init;
2064 if ($prefs->get($type) !== $obj->get($type)) {
2065 // special systemdefault prefs: (probably not needed)
2066 if ($type == 'theme' and $prefs->get($type) == '' and
2067 $obj->get($type) == THEME) continue;
2068 if ($type == 'lang' and $prefs->get($type) == '' and
2069 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2070 if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2074 } elseif (is_array($prefs)) {
2075 //unset($this->_prefs['userid']);
2077 if (isset($this->_method) and
2078 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2079 unset($this->_prefs['passwd']);
2082 // emailVerified at first, the rest later
2083 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2084 $obj->_init = $init;
2085 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2086 if ($obj->set($type,$prefs[$type]))
2089 foreach (array_keys($this->_prefs) as $type) {
2090 $obj =& $this->_prefs[$type];
2091 $obj->_init = $init;
2092 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2093 $prefs[$type] = false;
2094 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2095 $prefs[$type] = (int) $prefs[$type];
2096 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2097 // special systemdefault prefs:
2098 if ($type == 'theme' and $prefs[$type] == '' and
2099 $obj->get($type) == THEME) continue;
2100 if ($type == 'lang' and $prefs[$type] == '' and
2101 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2102 if ($obj->set($type,$prefs[$type]))
2110 // For now convert just array of objects => array of values
2111 // Todo: the specialized subobjects must override this.
2114 foreach ($this->_prefs as $name => $object) {
2115 if ($value = $object->getraw($name))
2116 $prefs[$name] = $value;
2117 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2118 $prefs['emailVerified'] = $value;
2119 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2120 if (strlen($value) != strlen(crypt('test')))
2121 $prefs['passwd'] = crypt($value);
2122 else // already crypted
2123 $prefs['passwd'] = $value;
2128 // Merge current notifyPages with notifyPagesAll
2129 // notifyPages are pages to notify in the current project
2130 // while $notifyPagesAll is used to store all the monitored pages.
2131 if (isset($prefs['notifyPages'])) {
2132 $this->notifyPagesAll[PAGE_PREFIX] = $prefs['notifyPages'];
2133 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2137 return $this->pack($prefs);
2140 // packed string or array of values => array of values
2141 // Todo: the specialized subobjects must override this.
2142 function retrieve($packed) {
2143 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2144 $packed = unserialize($packed);
2145 if (!is_array($packed)) return false;
2147 foreach ($packed as $name => $packed_pref) {
2148 if (is_string($packed_pref)
2149 and isSerialized($packed_pref)
2150 and substr($packed_pref, 0, 2) == "O:")
2152 //legacy: check if it's an old array of objects
2153 // Looks like a serialized object.
2154 // This might fail if the object definition does not exist anymore.
2155 // object with ->$name and ->default_value vars.
2156 $pref = @unserialize($packed_pref);
2157 if (is_object($pref))
2158 $prefs[$name] = $pref->get($name);
2159 // fix old-style prefs
2160 } elseif (is_numeric($name) and is_array($packed_pref)) {
2161 if (count($packed_pref) == 1) {
2162 list($name,$value) = each($packed_pref);
2163 $prefs[$name] = $value;
2166 if (isSerialized($packed_pref))
2167 $prefs[$name] = @unserialize($packed_pref);
2168 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2169 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2170 // patched by frederik@pandora.be
2171 if (empty($prefs[$name]))
2172 $prefs[$name] = $packed_pref;
2177 // Restore notifyPages from notifyPagesAll
2178 // notifyPages are pages to notify in the current project
2179 // while $notifyPagesAll is used to store all the monitored pages.
2180 if (isset($prefs['notifyPages'])) {
2181 $this->notifyPagesAll = $prefs['notifyPages'];
2182 if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
2183 $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
2185 $prefs['notifyPages'] = '';
2194 * Check if the given prefs object is different from the current prefs object
2196 function isChanged($other) {
2197 foreach ($this->_prefs as $type => $obj) {
2198 if ($obj->get($type) !== $other->get($type))
2204 function defaultPreferences() {
2206 foreach ($this->_prefs as $key => $obj) {
2207 $prefs[$key] = $obj->default_value;
2214 return $this->_prefs;
2217 function pack($nonpacked) {
2218 return serialize($nonpacked);
2221 function unpack($packed) {
2224 //$packed = base64_decode($packed);
2225 if (substr($packed, 0, 2) == "O:") {
2226 // Looks like a serialized object
2227 return unserialize($packed);
2229 if (substr($packed, 0, 2) == "a:") {
2230 return unserialize($packed);
2232 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2238 return wikihash($this->_prefs);
2242 /** TODO: new pref storage classes
2243 * These are currently user specific and should be rewritten to be pref specific.
2244 * i.e. $this == $user->_prefs
2247 class CookieUserPreferences
2248 extends UserPreferences
2250 function CookieUserPreferences ($saved_prefs = false) {
2251 //_AnonUser::_AnonUser('',$saved_prefs);
2252 UserPreferences::UserPreferences($saved_prefs);
2256 class PageUserPreferences
2257 extends UserPreferences
2259 function PageUserPreferences ($saved_prefs = false) {
2260 UserPreferences::UserPreferences($saved_prefs);
2264 class PearDbUserPreferences
2265 extends UserPreferences
2267 function PearDbUserPreferences ($saved_prefs = false) {
2268 UserPreferences::UserPreferences($saved_prefs);
2272 class AdoDbUserPreferences
2273 extends UserPreferences
2275 function AdoDbUserPreferences ($saved_prefs = false) {
2276 UserPreferences::UserPreferences($saved_prefs);
2278 function getPreferences() {
2279 // override the generic slow method here for efficiency
2280 _AnonUser::getPreferences();
2281 $this->getAuthDbh();
2282 if (isset($this->_select)) {
2283 $dbh = & $this->_auth_dbi;
2284 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2288 $prefs_blob = $rs->fields['pref_blob'];
2290 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2291 $updated = $this->_prefs->updatePrefs($restored_from_db);
2292 //$this->_prefs = new UserPreferences($restored_from_db);
2293 return $this->_prefs;
2297 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2298 if ($restored_from_page = $this->_prefs->retrieve
2299 ($this->_HomePagehandle->get('pref'))) {
2300 $updated = $this->_prefs->updatePrefs($restored_from_page);
2301 //$this->_prefs = new UserPreferences($restored_from_page);
2302 return $this->_prefs;
2305 return $this->_prefs;
2313 // c-basic-offset: 4
2314 // c-hanging-comment-ender-p: nil
2315 // indent-tabs-mode: nil