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
20 * along with PhpWiki; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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() {
166 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
168 function _isBogoUserAllowed() {
169 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
171 function _isUserPasswordsAllowed() {
172 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
175 // Possibly upgrade userobject functions.
176 function _determineAdminUserOrOtherUser($UserName) {
177 // Sanity check. User name is a condition of the definition of the
178 // _AdminUser, _BogoUser and _passuser.
180 return $GLOBALS['ForbiddenUser'];
182 //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
183 //$group = &WikiGroup::getGroup($GLOBALS['request']);
184 if ($UserName == ADMIN_USER)
185 return new _AdminUser($UserName);
186 /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
187 return _determineBogoUserOrPassUser($UserName);
191 return _determineBogoUserOrPassUser($UserName);
194 function _determineBogoUserOrPassUser($UserName) {
195 global $ForbiddenUser;
197 // Sanity check. User name is a condition of the definition of
198 // _BogoUser and _PassUser.
200 return $ForbiddenUser;
202 // Check for password and possibly upgrade user object.
203 // $_BogoUser = new _BogoUser($UserName);
204 if (_isBogoUserAllowed() and isWikiWord($UserName)) {
205 include_once("lib/WikiUser/BogoLogin.php");
206 $_BogoUser = new _BogoLoginPassUser($UserName);
207 if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
210 if (_isUserPasswordsAllowed()) {
211 // PassUsers override BogoUsers if a password is stored
212 if (isset($_BogoUser) and isset($_BogoUser->_prefs)
213 and $_BogoUser->_prefs->get('passwd'))
214 return new _PassUser($UserName, $_BogoUser->_prefs);
216 $_PassUser = new _PassUser($UserName,
217 isset($_BogoUser) ? $_BogoUser->_prefs : false);
218 if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
219 if (isset($GLOBALS['request']->_user_class))
220 $class = $GLOBALS['request']->_user_class;
221 elseif (strtolower(get_class($_PassUser)) == "_passuser")
222 $class = $_PassUser->nextClass();
224 $class = get_class($_PassUser);
225 if ($user = new $class($UserName, $_PassUser->_prefs)
226 and $user->_userid) {
234 // No Bogo- or PassUser exists, or
235 // passwords are not allowed, and bogo is disallowed too.
236 // (Only the admin can sign in).
237 return $ForbiddenUser;
241 * Primary WikiUser function, called by lib/main.php.
243 * This determines the user's type and returns an appropriate user
244 * object. lib/main.php then querys the resultant object for password
245 * validity as necessary.
247 * If an _AnonUser object is returned, the user may only browse pages
248 * (and save prefs in a cookie).
250 * To disable access but provide prefs the global $ForbiddenUser class
251 * is returned. (was previously false)
254 function WikiUser ($UserName = '') {
255 global $ForbiddenUser, $HTTP_SESSION_VARS;
257 //Maybe: Check sessionvar for username & save username into
258 //sessionvar (may be more appropriate to do this in lib/main.php).
260 $ForbiddenUser = new _ForbiddenUser($UserName);
261 // Found a user name.
262 return _determineAdminUserOrOtherUser($UserName);
264 elseif (!empty($HTTP_SESSION_VARS['userid'])) {
265 // Found a user name.
266 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
267 return _determineAdminUserOrOtherUser($_SESSION['userid']);
270 // Check for autologin pref in cookie and possibly upgrade
271 // user object to another type.
272 $_AnonUser = new _AnonUser();
273 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
274 // Found a user name.
275 $ForbiddenUser = new _ForbiddenUser($UserName);
276 return _determineAdminUserOrOtherUser($UserName);
279 $ForbiddenUser = new _ForbiddenUser();
280 if (_isAnonUserAllowed())
282 return $ForbiddenUser; // User must sign in to browse pages.
284 return $ForbiddenUser; // User must sign in with a password.
287 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
288 . "Unexpectedly, an appropriate user class could not be determined.");
289 return $ForbiddenUser; // Failsafe.
294 * WikiUser.php use the name 'WikiUser'
296 function WikiUserClassname() {
302 * Upgrade olduser by copying properties from user to olduser.
303 * We are not sure yet, for which php's a simple $this = $user works reliably,
304 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
305 * that's why try it the hard way.
307 function UpgradeUser ($user, $newuser) {
308 if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) {
309 // populate the upgraded class $newuser with the values from the current user object
310 //only _auth_level, _current_method, _current_index,
311 if (!empty($user->_level) and
312 $user->_level > $newuser->_level)
313 $newuser->_level = $user->_level;
314 if (!empty($user->_current_index) and
315 $user->_current_index > $newuser->_current_index) {
316 $newuser->_current_index = $user->_current_index;
317 $newuser->_current_method = $user->_current_method;
319 if (!empty($user->_authmethod))
320 $newuser->_authmethod = $user->_authmethod;
321 $GLOBALS['request']->_user_class = get_class($newuser);
323 foreach (get_object_vars($user) as $k => $v) {
324 if (!empty($v)) $olduser->$k = $v;
327 $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
328 //$GLOBALS['request']->_user = $olduser;
336 * Probably not needed, since we use the various user objects methods so far.
337 * Anyway, here it is, looping through all available objects.
339 function UserExists ($UserName) {
341 if (!($user = $request->getUser()))
342 $user = WikiUser($UserName);
345 if ($user->userExists($UserName)) {
346 $request->_user = $user;
349 if (isa($user,'_BogoUser'))
350 $user = new _PassUser($UserName,$user->_prefs);
351 $class = $user->nextClass();
352 if ($user = new $class($UserName, $user->_prefs)) {
353 return $user->userExists($UserName);
355 $request->_user = $GLOBALS['ForbiddenUser'];
359 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
362 * Base WikiUser class.
367 var $_level = WIKIAUTH_ANON;
369 var $_HomePagehandle = false;
372 function _WikiUser($UserName='', $prefs=false) {
374 $this->_userid = $UserName;
375 $this->_HomePagehandle = false;
377 $this->hasHomePage();
379 if (empty($this->_prefs)) {
380 if ($prefs) $this->_prefs = $prefs;
381 else $this->getPreferences();
385 function UserName() {
386 if (!empty($this->_userid))
387 return $this->_userid;
390 function getPreferences() {
391 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
392 . "New subclasses of _WikiUser must override this function.");
396 function setPreferences($prefs, $id_only) {
397 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
399 . "New subclasses of _WikiUser must override this function.");
403 function userExists() {
404 return $this->hasHomePage();
407 function checkPass($submitted_password) {
408 // By definition, an undefined user class cannot sign in.
409 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
411 . "New subclasses of _WikiUser must override this function.");
415 // returns page_handle to user's home page or false if none
416 function hasHomePage() {
417 if ($this->_userid) {
418 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
419 return $this->_HomePagehandle->exists();
422 // check db again (maybe someone else created it since
425 $this->_HomePagehandle = $request->getPage($this->_userid);
426 return $this->_HomePagehandle->exists();
433 function createHomePage() {
435 $versiondata = array('author' => ADMIN_USER);
436 $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.").
437 "\n{{Template/UserPage}}",
439 $request->_dbi->touch();
440 $this->_HomePagehandle = $request->getPage($this->_userid);
443 // innocent helper: case-insensitive position in _auth_methods
444 function array_position ($string, $array) {
445 $string = strtolower($string);
446 for ($found = 0; $found < count($array); $found++) {
447 if (strtolower($array[$found]) == $string)
453 function nextAuthMethodIndex() {
454 if (empty($this->_auth_methods))
455 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
456 if (empty($this->_current_index)) {
457 if (strtolower(get_class($this)) != '_passuser') {
458 $this->_current_method = substr(get_class($this),1,-8);
459 $this->_current_index = $this->array_position($this->_current_method,
460 $this->_auth_methods);
462 $this->_current_index = -1;
465 $this->_current_index++;
466 if ($this->_current_index >= count($this->_auth_methods))
468 $this->_current_method = $this->_auth_methods[$this->_current_index];
469 return $this->_current_index;
472 function AuthMethod($index = false) {
473 return $this->_auth_methods[ $index === false
474 ? count($this->_auth_methods)-1
478 // upgrade the user object
479 function nextClass() {
480 $method = $this->AuthMethod($this->nextAuthMethodIndex());
481 include_once("lib/WikiUser/$method.php");
482 return "_".$method."PassUser";
485 //Fixme: for _HttpAuthPassUser
486 function PrintLoginForm (&$request, $args, $fail_message = false,
487 $seperate_page = false) {
488 include_once('lib/Template.php');
489 // Call update_locale in case the system's default language is not 'en'.
490 // (We have no user pref for lang at this point yet, no one is logged in.)
491 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
492 update_locale(DEFAULT_LANGUAGE);
493 $userid = $this->_userid;
495 extract($args); // fixme
497 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
499 $pagename = $request->getArg('pagename');
501 $login = Template('login',
502 compact('pagename', 'userid', 'require_level',
503 'fail_message', 'pass_required', 'nocache'));
504 // check if the html template was already processed
505 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
506 if ($seperate_page) {
507 $page = $request->getPage($pagename);
508 $revision = $page->getCurrentRevision();
509 return GeneratePage($login,_("Sign In"), $revision);
511 return $login->printExpansion();
515 /** Signed in but not password checked or empty password.
517 function isSignedIn() {
518 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
521 /** This is password checked for sure.
523 function isAuthenticated() {
524 //return isa($this,'_PassUser');
525 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
526 return $this->_level >= WIKIAUTH_BOGO;
529 function isAdmin () {
531 if ($this->_level == WIKIAUTH_ADMIN) return true;
532 if (!$this->isSignedIn()) return false;
533 if (!$this->isAuthenticated()) return false;
535 if (!$group) $group = &$GLOBALS['request']->getGroup();
536 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
539 /** Name or IP for a signed user. UserName could come from a cookie e.g.
542 return ( $this->UserName()
544 : $GLOBALS['request']->get('REMOTE_ADDR') );
547 /** Name for an authenticated user. No IP here.
549 function getAuthenticatedId() {
550 return ( $this->isAuthenticated()
552 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
555 function hasAuthority ($require_level) {
556 return $this->_level >= $require_level;
559 /* This is quite restrictive and not according the login description online.
560 Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
561 The backends may loosen or tighten this.
563 function isValidName ($userid = false) {
564 if (!$userid) $userid = $this->_userid;
565 if (!$userid) return false;
569 return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
573 * Called on an auth_args POST request, such as login, logout or signin.
574 * TODO: Check BogoLogin users with empty password. (self-signed users)
576 function AuthCheck ($postargs) {
577 // Normalize args, and extract.
578 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
580 foreach ($keys as $key)
581 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
583 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
585 if ($logout) { // Log out
586 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
588 $zone_offset = Request_AccessLogEntry::_zone_offset();
589 $ncsa_time = date("d/M/Y:H:i:s", time());
590 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
591 (string) $request->get('REMOTE_HOST'),
592 (string) $request->_user->_userid,
593 $ncsa_time, $zone_offset,
594 "logout ".get_class($request->_user),
596 (string) $request->get('HTTP_REFERER'),
597 (string) $request->get('HTTP_USER_AGENT')
599 if (($fp = fopen(LOGIN_LOG, "a"))) {
601 fputs($fp, "$entry\n");
604 //error_log("$entry\n", 3, LOGIN_LOG);
606 if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
607 $GLOBALS['request']->_user->logout();
609 $user = new _AnonUser();
611 $user->_level = WIKIAUTH_ANON;
614 return false; // User hit cancel button.
615 elseif (!$login && !$userid)
616 return false; // Nothing to do?
618 if (!$this->isValidName($userid))
619 return _("Invalid username.");;
621 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
623 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
625 $zone_offset = Request_AccessLogEntry::_zone_offset();
626 $ncsa_time = date("d/M/Y:H:i:s", time());
627 $manglepasswd = $passwd;
628 for ($i=0; $i<strlen($manglepasswd); $i++) {
629 $c = substr($manglepasswd,$i,1);
630 if (ord($c) < 32) $manglepasswd[$i] = "<";
631 elseif ($c == '*') $manglepasswd[$i] = "*";
632 elseif ($c == '?') $manglepasswd[$i] = "?";
633 elseif ($c == '(') $manglepasswd[$i] = "(";
634 elseif ($c == ')') $manglepasswd[$i] = ")";
635 elseif ($c == "\\") $manglepasswd[$i] = "\\";
636 elseif (ord($c) < 127) $manglepasswd[$i] = "x";
637 elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
639 if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
640 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
641 $request->get('REMOTE_HOST'),
642 (string) $request->_user->_userid,
643 $ncsa_time, $zone_offset,
644 "login $userid/$manglepasswd => $authlevel ".get_class($request->_user),
645 $authlevel > 0 ? "200" : "403",
646 (string) $request->get('HTTP_REFERER'),
647 (string) $request->get('HTTP_USER_AGENT')
649 if (($fp = fopen(LOGIN_LOG, "a"))) {
651 fputs($fp, "$entry\n");
654 //error_log("$entry\n", 3, LOGIN_LOG);
657 if ($authlevel <= 0) { // anon or forbidden
659 return _("Invalid password.");
661 return _("Invalid password or userid.");
662 } elseif ($authlevel < $require_level) { // auth ok, but not enough
663 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
666 $class = "_" . $this->_current_method . "PassUser";
667 include_once("lib/WikiUser/".$this->_current_method.".php");
668 $user = new $class($userid,$this->_prefs);
669 if (!check_php_version(5))
670 eval("\$this = \$user;");
671 // /*PHP5 patch*/$this = $user;
672 $this->_level = $authlevel;
675 $this->_userid = $userid;
676 $this->_level = $authlevel;
677 return _("Insufficient permissions.");
681 //$user = $GLOBALS['request']->_user;
682 if (!empty($this->_current_method) and
683 strtolower(get_class($this)) == '_passuser')
686 $class = "_" . $this->_current_method . "PassUser";
687 include_once("lib/WikiUser/".$this->_current_method.".php");
688 $user = new $class($userid, $this->_prefs);
689 if (!check_php_version(5))
690 eval("\$this = \$user;");
691 // /*PHP5 patch*/$this = $user;
692 $user->_level = $authlevel;
695 $this->_userid = $userid;
696 $this->_level = $authlevel;
703 * Not authenticated in user, but he may be signed in. Basicly with view access only.
704 * prefs are stored in cookies, but only the userid.
709 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
711 /** Anon only gets to load and save prefs in a cookie, that's it.
713 function getPreferences() {
716 if (empty($this->_prefs))
717 $this->_prefs = new UserPreferences;
718 $UserName = $this->UserName();
720 // Try to read deprecated 1.3.x style cookies
721 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
722 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
723 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
725 . sprintf("%s='%s'", WIKI_NAME, $cookie)
727 . _("Default preferences will be used."),
731 * Only set if it matches the UserName who is
732 * signing in or if this really is an Anon login (no
733 * username). (Remember, _BogoUser and higher inherit this
736 if (! $UserName || $UserName == @$unboxedcookie['userid']) {
737 $updated = $this->_prefs->updatePrefs($unboxedcookie);
738 //$this->_prefs = new UserPreferences($unboxedcookie);
739 $UserName = @$unboxedcookie['userid'];
740 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
741 $this->_userid = $UserName;
745 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
747 $request->deleteCookieVar(WIKI_NAME);
749 // Try to read deprecated 1.3.4 style cookies
750 if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
751 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
752 if (! $UserName || $UserName == $unboxedcookie['userid']) {
753 $updated = $this->_prefs->updatePrefs($unboxedcookie);
754 //$this->_prefs = new UserPreferences($unboxedcookie);
755 $UserName = $unboxedcookie['userid'];
756 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
757 $this->_userid = $UserName;
762 $request->deleteCookieVar("WIKI_PREF2");
766 // Try reading userid from old PhpWiki cookie formats:
767 if ($cookie = $request->cookies->get_old(getCookieName())) {
768 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
770 elseif (is_array($cookie) and !empty($cookie['userid']))
771 $UserName = $cookie['userid'];
773 if (! $UserName and !headers_sent())
774 $request->deleteCookieVar(getCookieName());
776 $this->_userid = $UserName;
779 // initializeTheme() needs at least an empty object
781 if (empty($this->_prefs))
782 $this->_prefs = new UserPreferences;
784 return $this->_prefs;
787 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
789 * Allow for multiple wikis in same domain. Encode only the
790 * _prefs array of the UserPreference object. Ideally the
791 * prefs array should just be imploded into a single string or
792 * something so it is completely human readable by the end
793 * user. In that case stricter error checking will be needed
794 * when loading the cookie.
796 function setPreferences($prefs, $id_only=false) {
797 if (!is_object($prefs)) {
798 if (is_object($this->_prefs)) {
799 $updated = $this->_prefs->updatePrefs($prefs);
800 $prefs =& $this->_prefs;
802 // update the prefs values from scratch. This could leed to unnecessary
803 // side-effects: duplicate emailVerified, ...
804 $this->_prefs = new UserPreferences($prefs);
808 if (!isset($this->_prefs))
809 $this->_prefs =& $prefs;
811 $updated = $this->_prefs->isChanged($prefs);
814 if ($id_only and !headers_sent()) {
816 // new 1.3.8 policy: no array cookies, only plain userid string as in
817 // the pre 1.3.x versions.
818 // prefs should be stored besides the session in the homepagehandle or in a db.
819 $request->setCookieVar(getCookieName(), $this->_userid,
820 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
821 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
822 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
825 if (is_object($prefs)) {
826 $packed = $prefs->store();
827 $unpacked = $prefs->unpack($packed);
828 if (count($unpacked)) {
829 foreach (array('_method','_select','_update','_insert') as $param) {
830 if (!empty($this->_prefs->{$param}))
831 $prefs->{$param} = $this->_prefs->{$param};
833 $this->_prefs = $prefs;
839 function userExists() {
843 function checkPass($submitted_password) {
845 // this might happen on a old-style signin button.
847 // By definition, the _AnonUser does not HAVE a password
848 // (compared to _BogoUser, who has an EMPTY password).
849 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
850 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
851 . "New subclasses of _WikiUser must override this function.");
858 * Helper class to finish the PassUser auth loop.
859 * This is added automatically to USER_AUTH_ORDER.
864 var $_level = WIKIAUTH_FORBIDDEN;
866 function checkPass($submitted_password) {
867 return WIKIAUTH_FORBIDDEN;
870 function userExists() {
871 if ($this->_HomePagehandle) return true;
877 * Do NOT extend _BogoUser to other classes, for checkPass()
878 * security. (In case of defects in code logic of the new class!)
879 * The intermediate step between anon and passuser.
880 * We also have the _BogoLoginPassUser class with stricter
881 * password checking, which fits into the auth loop.
882 * Note: This class is not called anymore by WikiUser()
887 function userExists() {
888 if (isWikiWord($this->_userid)) {
889 $this->_level = WIKIAUTH_BOGO;
892 $this->_level = WIKIAUTH_ANON;
897 function checkPass($submitted_password) {
898 // By definition, BogoUser has an empty password.
900 return $this->_level;
907 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
909 * The classes for all subsequent auth methods extend from this class.
910 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
911 * the three auth method policies first-only, strict and stacked
912 * and the two methods for prefs: homepage or database,
913 * if $DBAuthParams['pref_select'] is defined.
915 * Default is PersonalPage auth and prefs.
917 * @author: Reini Urban
921 var $_auth_dbi, $_prefs;
922 var $_current_method, $_current_index;
924 // check and prepare the auth and pref methods only once
925 function _PassUser($UserName='', $prefs=false) {
926 //global $DBAuthParams, $DBParams;
928 /*if (!$this->isValidName($UserName))
930 $this->_userid = $UserName;
931 if ($this->hasHomePage())
932 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
934 $this->_authmethod = substr(get_class($this),1,-8);
935 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
937 // Check the configured Prefs methods
938 $dbi = $this->getAuthDbh();
939 $dbh = $GLOBALS['request']->getDbh();
942 and !isset($this->_prefs->_select)
943 and $dbh->getAuthParam('pref_select'))
945 if (!$this->_prefs) {
946 $this->_prefs = new UserPreferences();
949 $this->_prefs->_method = $dbh->getParam('dbtype');
950 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
952 if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
953 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
954 array("userid", "pref_blob"));
957 if (!$this->_prefs) {
958 $this->_prefs = new UserPreferences();
961 $this->_prefs->_method = 'HomePage';
964 if (! $this->_prefs or isset($need_pref) ) {
965 if ($prefs) $this->_prefs = $prefs;
966 else $this->getPreferences();
969 // Upgrade to the next parent _PassUser class. Avoid recursion.
970 if ( strtolower(get_class($this)) === '_passuser' ) {
971 //auth policy: Check the order of the configured auth methods
972 // 1. first-only: Upgrade the class here in the constructor
973 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
974 /// in the previous PhpWiki releases (slow)
975 // 3. strict: upgrade the class after checking the user existance in userExists()
976 // 4. stacked: upgrade the class after the password verification in checkPass()
977 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
978 //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
979 if (defined('USER_AUTH_POLICY')) {
980 // policy 1: only pre-define one method for all users
981 if (USER_AUTH_POLICY === 'first-only') {
982 $class = $this->nextClass();
983 return new $class($UserName,$this->_prefs);
985 // Use the default behaviour from the previous versions:
986 elseif (USER_AUTH_POLICY === 'old') {
987 // Default: try to be smart
988 // On php5 we can directly return and upgrade the Object,
989 // before we have to upgrade it manually.
990 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
991 include_once("lib/WikiUser/HttpAuth.php");
992 if (check_php_version(5))
993 return new _HttpAuthPassUser($UserName,$this->_prefs);
995 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
996 eval("\$this = \$user;");
997 // /*PHP5 patch*/$this = $user;
1000 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1001 $dbh->getAuthParam('auth_check') and
1002 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
1003 if (check_php_version(5))
1004 return new _DbPassUser($UserName,$this->_prefs);
1006 $user = new _DbPassUser($UserName,$this->_prefs);
1007 eval("\$this = \$user;");
1008 // /*PHP5 patch*/$this = $user;
1011 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1012 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
1013 function_exists('ldap_connect')) {
1014 include_once("lib/WikiUser/LDAP.php");
1015 if (check_php_version(5))
1016 return new _LDAPPassUser($UserName,$this->_prefs);
1018 $user = new _LDAPPassUser($UserName,$this->_prefs);
1019 eval("\$this = \$user;");
1020 // /*PHP5 patch*/$this = $user;
1023 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1024 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
1025 include_once("lib/WikiUser/IMAP.php");
1026 if (check_php_version(5))
1027 return new _IMAPPassUser($UserName,$this->_prefs);
1029 $user = new _IMAPPassUser($UserName,$this->_prefs);
1030 eval("\$this = \$user;");
1031 // /*PHP5 patch*/$this = $user;
1034 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1035 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
1036 include_once("lib/WikiUser/File.php");
1037 if (check_php_version(5))
1038 return new _FilePassUser($UserName, $this->_prefs);
1040 $user = new _FilePassUser($UserName, $this->_prefs);
1041 eval("\$this = \$user;");
1042 // /*PHP5 patch*/$this = $user;
1046 include_once("lib/WikiUser/PersonalPage.php");
1047 if (check_php_version(5))
1048 return new _PersonalPagePassUser($UserName,$this->_prefs);
1050 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
1051 eval("\$this = \$user;");
1052 // /*PHP5 patch*/$this = $user;
1058 // else use the page methods defined in _PassUser.
1064 function getAuthDbh () {
1065 global $request; //, $DBParams, $DBAuthParams;
1067 $dbh = $request->getDbh();
1068 // session restauration doesn't re-connect to the database automatically,
1069 // so dirty it here, to force a reconnect.
1070 if (isset($this->_auth_dbi)) {
1071 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1072 unset($this->_auth_dbi);
1073 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1074 unset($this->_auth_dbi);
1076 if (empty($this->_auth_dbi)) {
1077 if ($dbh->getParam('dbtype') != 'SQL'
1078 and $dbh->getParam('dbtype') != 'ADODB'
1079 and $dbh->getParam('dbtype') != 'PDO')
1081 if (empty($GLOBALS['DBAuthParams']))
1083 if (!$dbh->getAuthParam('auth_dsn')) {
1084 $dbh = $request->getDbh(); // use phpwiki database
1085 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1086 $dbh = $request->getDbh(); // same phpwiki database
1087 } else { // use another external database handle. needs PHP >= 4.1
1088 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1089 $local_params['dsn'] = $local_params['auth_dsn'];
1090 $dbh = WikiDB::open($local_params);
1092 $this->_auth_dbi =& $dbh->_backend->_dbh;
1094 return $this->_auth_dbi;
1097 function _normalize_stmt_var($var, $oldstyle = false) {
1098 static $valid_variables = array('userid','password','pref_blob','groupname');
1099 // old-style: "'$userid'"
1100 // new-style: '"\$userid"' or just "userid"
1101 $new = str_replace(array("'",'"','\$','$'),'',$var);
1102 if (!in_array($new, $valid_variables)) {
1103 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1106 return !$oldstyle ? "'$".$new."'" : '\$'.$new;
1109 // TODO: use it again for the auth and member tables
1110 // sprintfstyle vs prepare style: %s or ?
1111 // multiple vars should be executed via prepare(?,?)+execute,
1112 // single vars with execute(sprintf(quote(var)))
1113 // help with position independency
1114 function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) {
1116 $dbi = $request->getDbh();
1117 $this->getAuthDbh();
1118 // "'\$userid"' => %s
1119 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1120 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1122 if (is_array($variables)) {
1123 //$sprintfstyle = false;
1124 for ($i=0; $i < count($variables); $i++) {
1125 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1127 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1128 $variables[$i], $stmt), E_USER_WARNING);
1129 $variables[$i] = $var;
1130 if (!$var) $new[] = '';
1132 $s = "%" . ($i+1) . "s";
1133 $new[] = $sprintfstyle ? $s : "?";
1137 $var = $this->_normalize_stmt_var($variables, $oldstyle);
1139 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1140 $variables, $stmt), E_USER_WARNING);
1142 if (!$var) $new = '';
1143 else $new = $sprintfstyle ? '%s' : "?";
1145 $prefix = $dbi->getParam('prefix');
1146 // probably prefix table names if in same database
1147 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1148 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1150 if (!stristr($stmt, $prefix)) {
1152 $stmt = str_replace(array(" user "," pref "," member "),
1153 array(" ".$prefix."user ",
1154 " ".$prefix."pref ",
1155 " ".$prefix."member "), $stmt);
1156 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1157 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt",
1161 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1162 // Simple sprintf-style.
1163 $new_stmt = str_replace($variables, $new, $stmt);
1164 if ($new_stmt == $stmt) {
1166 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1167 $stmt), E_USER_WARNING);
1169 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1170 $stmt), E_USER_WARNING);
1171 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1177 function getPreferences() {
1178 if (!empty($this->_prefs->_method)) {
1179 if ($this->_prefs->_method == 'ADODB') {
1180 // FIXME: strange why this should be needed...
1181 include_once("lib/WikiUser/Db.php");
1182 include_once("lib/WikiUser/AdoDb.php");
1183 if (check_php_version(5)) {
1184 $user = new _AdoDbPassUser($this->_userid, $this->_prefs);
1185 return $user->getPreferences();
1187 _AdoDbPassUser::_AdoDbPassUser($this->_userid, $this->_prefs);
1188 return _AdoDbPassUser::getPreferences();
1190 } elseif ($this->_prefs->_method == 'SQL') {
1191 include_once("lib/WikiUser/Db.php");
1192 include_once("lib/WikiUser/PearDb.php");
1193 if (check_php_version(5)) {
1194 $user = new _PearDbPassUser($this->_userid, $this->_prefs);
1195 return $user->getPreferences();
1197 _PearDbPassUser::_PearDbPassUser($this->_userid, $this->_prefs);
1198 return _PearDbPassUser::getPreferences();
1200 } elseif ($this->_prefs->_method == 'PDO') {
1201 include_once("lib/WikiUser/Db.php");
1202 include_once("lib/WikiUser/PdoDb.php");
1203 if (check_php_version(5)) {
1204 $user = new _PdoDbPassUser($this->_userid, $this->_prefs);
1205 return $user->getPreferences();
1207 _PdoDbPassUser::_PdoDbPassUser($this->_userid, $this->_prefs);
1208 return _PdoDbPassUser::getPreferences();
1213 // We don't necessarily have to read the cookie first. Since
1214 // the user has a password, the prefs stored in the homepage
1215 // cannot be arbitrarily altered by other Bogo users.
1216 _AnonUser::getPreferences();
1217 // User may have deleted cookie, retrieve from his
1218 // PersonalPage if there is one.
1219 if (!empty($this->_HomePagehandle)) {
1220 if ($restored_from_page = $this->_prefs->retrieve
1221 ($this->_HomePagehandle->get('pref'))) {
1222 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1223 //$this->_prefs = new UserPreferences($restored_from_page);
1224 return $this->_prefs;
1227 return $this->_prefs;
1230 function setPreferences($prefs, $id_only=false) {
1231 if (!empty($this->_prefs->_method)) {
1232 if ($this->_prefs->_method == 'ADODB') {
1233 // FIXME: strange why this should be needed...
1234 include_once("lib/WikiUser/Db.php");
1235 include_once("lib/WikiUser/AdoDb.php");
1236 if (check_php_version(5)) {
1237 $user = new _AdoDbPassUser($this->_userid, $prefs);
1238 return $user->setPreferences($prefs, $id_only);
1240 _AdoDbPassUser::_AdoDbPassUser($this->_userid, $prefs);
1241 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1244 elseif ($this->_prefs->_method == 'SQL') {
1245 include_once("lib/WikiUser/Db.php");
1246 include_once("lib/WikiUser/PearDb.php");
1247 if (check_php_version(5)) {
1248 $user = new _PearDbPassUser($this->_userid, $prefs);
1249 return $user->setPreferences($prefs, $id_only);
1251 _PearDbPassUser::_PearDbPassUser($this->_userid, $prefs);
1252 return _PearDbPassUser::setPreferences($prefs, $id_only);
1255 elseif ($this->_prefs->_method == 'PDO') {
1256 include_once("lib/WikiUser/Db.php");
1257 include_once("lib/WikiUser/PdoDb.php");
1258 if (check_php_version(5)) {
1259 $user = new _PdoDbPassUser($this->_userid, $prefs);
1260 return $user->setPreferences($prefs, $id_only);
1262 _PdoDbPassUser::_PdoDbPassUser($this->_userid, $prefs);
1263 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1267 if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1268 // Encode only the _prefs array of the UserPreference object
1269 // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1270 if (empty($this->_HomePagehandle)) {
1271 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1273 if (! $this->_HomePagehandle->exists() ) {
1274 $this->createHomePage();
1276 if (!empty($this->_HomePagehandle) and !$id_only) {
1277 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1283 function mayChangePass() {
1287 //The default method is getting the password from prefs.
1288 // child methods obtain $stored_password from external auth.
1289 function userExists() {
1290 //if ($this->_HomePagehandle) return true;
1291 if (strtolower(get_class($this)) == "_passuser") {
1292 $class = $this->nextClass();
1293 $user = new $class($this->_userid, $this->_prefs);
1297 $UserName = $this->_userid;
1298 /* new user => false does not return false, but the _userid is empty then */
1299 if ($user and $user->_userid) {
1300 if (!check_php_version(5))
1301 eval("\$this = \$user;");
1302 $user = UpgradeUser($this, $user);
1303 if ($user->userExists())
1306 while (!$this->_tryNextUser($UserName)) {
1307 // prevent endless loop. does this work on all PHP's?
1308 // it just has to set the classname, what it correctly does.
1309 if ($this->nextClass() == "_ForbiddenPassUser")
1315 //The default method is getting the password from prefs.
1316 // child methods obtain $stored_password from external auth.
1317 function checkPass($submitted_password) {
1318 $stored_password = $this->_prefs->get('passwd');
1319 if ($this->_checkPass($submitted_password, $stored_password)) {
1320 $this->_level = WIKIAUTH_USER;
1321 return $this->_level;
1323 if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1324 $this->_level = WIKIAUTH_FORBIDDEN;
1325 return $this->_level;
1327 return $this->_tryNextPass($submitted_password);
1332 function _checkPassLength($submitted_password) {
1333 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1334 trigger_error(_("The length of the password is shorter than the system policy allows."));
1341 * The basic password checker for all PassUser objects.
1342 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1343 * Empty passwords are always false!
1344 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1345 * @see UserPreferences::set
1347 * DBPassUser password's have their own crypt definition.
1348 * That's why DBPassUser::checkPass() doesn't call this method, if
1349 * the db password method is 'plain', which means that the DB SQL
1350 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1351 * don't store plain passwords in the DB.
1353 * TODO: remove crypt() function check from config.php:396 ??
1355 function _checkPass($submitted_password, $stored_password) {
1356 if (!empty($submitted_password)) {
1357 // This works only on plaintext passwords.
1358 if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1359 // With the EditMetaData plugin
1360 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."));
1363 if (!$this->_checkPassLength($submitted_password)) {
1366 if (ENCRYPTED_PASSWD) {
1367 // Verify against encrypted password.
1368 if (function_exists('crypt')) {
1369 if (crypt($submitted_password, $stored_password) == $stored_password )
1370 return true; // matches encrypted password
1375 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1376 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1382 // Verify against cleartext password.
1383 if ($submitted_password == $stored_password)
1386 // Check whether we forgot to enable ENCRYPTED_PASSWD
1387 if (function_exists('crypt')) {
1388 if (crypt($submitted_password, $stored_password) == $stored_password) {
1389 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1400 /** The default method is storing the password in prefs.
1401 * Child methods (DB, File) may store in external auth also, but this
1402 * must be explicitly enabled.
1403 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1405 function changePass($submitted_password) {
1406 $stored_password = $this->_prefs->get('passwd');
1407 // check if authenticated
1408 if (!$this->isAuthenticated()) return false;
1409 if (ENCRYPTED_PASSWD) {
1410 $submitted_password = crypt($submitted_password);
1412 // check other restrictions, with side-effects only.
1413 $result = $this->_checkPass($submitted_password, $stored_password);
1414 if ($stored_password != $submitted_password) {
1415 $this->_prefs->set('passwd', $submitted_password);
1416 //update the storage (session, homepage, ...)
1417 $this->SetPreferences($this->_prefs);
1420 //Todo: return an error msg to the caller what failed?
1421 // same password or no privilege
1422 return ENCRYPTED_PASSWD ? true : false;
1425 function _tryNextPass($submitted_password) {
1426 if (DEBUG & _DEBUG_LOGIN) {
1427 $class = strtolower(get_class($this));
1428 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1429 $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1431 if (USER_AUTH_POLICY === 'strict') {
1432 $class = $this->nextClass();
1433 if ($user = new $class($this->_userid, $this->_prefs)) {
1434 if ($user->userExists()) {
1435 return $user->checkPass($submitted_password);
1439 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1440 $class = $this->nextClass();
1441 if ($user = new $class($this->_userid, $this->_prefs))
1442 return $user->checkPass($submitted_password);
1444 return $this->_level;
1447 function _tryNextUser($username = false) {
1448 if (DEBUG & _DEBUG_LOGIN) {
1449 $class = strtolower(get_class($this));
1450 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1451 $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1453 if (!$username) $username = $this->_userid;
1454 if (USER_AUTH_POLICY === 'strict'
1455 or USER_AUTH_POLICY === 'stacked')
1457 $class = $this->nextClass();
1458 while ($user = new $class($username, $this->_prefs)) {
1459 if (!check_php_version(5))
1460 eval("\$this = \$user;");
1461 $user = UpgradeUser($this, $user);
1462 if ($user->userExists()) {
1463 //$user = UpgradeUser($this, $user);
1466 if ($class == "_ForbiddenPassUser") return false;
1467 $class = $this->nextClass();
1476 * Insert more auth classes here...
1477 * For example a customized db class for another db connection
1478 * or a socket-based auth server.
1484 * For security, this class should not be extended. Instead, extend
1485 * from _PassUser (think of this as unix "root").
1487 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1488 * Other members of the Administrators group must raise their level otherwise somehow.
1489 * Currently every member is a AdminUser, which will not work for the various
1495 function mayChangePass() {
1498 function checkPass($submitted_password) {
1499 if ($this->_userid == ADMIN_USER)
1500 $stored_password = ADMIN_PASSWD;
1502 // Should not happen! Only ADMIN_USER should use this class.
1503 // return $this->_tryNextPass($submitted_password); // ???
1504 // TODO: safety check if really member of the ADMIN group?
1505 $stored_password = $this->_pref->get('passwd');
1507 if ($this->_checkPass($submitted_password, $stored_password)) {
1508 $this->_level = WIKIAUTH_ADMIN;
1509 if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1511 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1513 return $this->_level;
1515 return $this->_tryNextPass($submitted_password);
1516 //$this->_level = WIKIAUTH_ANON;
1517 //return $this->_level;
1521 function storePass($submitted_password) {
1522 if ($this->_userid == ADMIN_USER)
1525 // should not happen! only ADMIN_USER should use this class.
1526 return parent::storePass($submitted_password);
1531 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1533 * Various data classes for the preference types,
1534 * to support get, set, sanify (range checking, ...)
1535 * update() will do the neccessary side-effects if a
1536 * setting gets changed (theme, language, ...)
1539 class _UserPreference
1543 function _UserPreference ($default_value) {
1544 $this->default_value = $default_value;
1547 function sanify ($value) {
1548 return (string)$value;
1551 function get ($name) {
1552 if (isset($this->{$name}))
1553 return $this->{$name};
1555 return $this->default_value;
1558 function getraw ($name) {
1559 if (!empty($this->{$name}))
1560 return $this->{$name};
1563 // stores the value as $this->$name, and not as $this->value (clever?)
1564 function set ($name, $value) {
1566 $value = $this->sanify($value);
1567 if ($this->get($name) != $value) {
1568 $this->update($value);
1571 if ($value != $this->default_value) {
1572 $this->{$name} = $value;
1574 unset($this->{$name});
1579 // default: no side-effects
1580 function update ($value) {
1585 class _UserPreference_numeric
1586 extends _UserPreference
1588 function _UserPreference_numeric ($default, $minval = false,
1590 $this->_UserPreference((double)$default);
1591 $this->_minval = (double)$minval;
1592 $this->_maxval = (double)$maxval;
1595 function sanify ($value) {
1596 $value = (double)$value;
1597 if ($this->_minval !== false && $value < $this->_minval)
1598 $value = $this->_minval;
1599 if ($this->_maxval !== false && $value > $this->_maxval)
1600 $value = $this->_maxval;
1605 class _UserPreference_int
1606 extends _UserPreference_numeric
1608 function _UserPreference_int ($default, $minval = false, $maxval = false) {
1609 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1612 function sanify ($value) {
1613 return (int)parent::sanify((int)$value);
1617 class _UserPreference_bool
1618 extends _UserPreference
1620 function _UserPreference_bool ($default = false) {
1621 $this->_UserPreference((bool)$default);
1624 function sanify ($value) {
1625 if (is_array($value)) {
1626 /* This allows for constructs like:
1628 * <input type="hidden" name="pref[boolPref][]" value="0" />
1629 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1631 * (If the checkbox is not checked, only the hidden input
1632 * gets sent. If the checkbox is sent, both inputs get
1635 foreach ($value as $val) {
1641 return (bool) $value;
1645 class _UserPreference_language
1646 extends _UserPreference
1648 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1649 $this->_UserPreference($default);
1652 // FIXME: check for valid locale
1653 function sanify ($value) {
1654 // Revert to DEFAULT_LANGUAGE if user does not specify
1655 // language in UserPreferences or chooses <system language>.
1656 if ($value == '' or empty($value))
1657 $value = DEFAULT_LANGUAGE;
1659 return (string) $value;
1662 function update ($newvalue) {
1663 if (! $this->_init ) {
1664 // invalidate etag to force fresh output
1665 $GLOBALS['request']->setValidators(array('%mtime' => false));
1666 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1671 class _UserPreference_theme
1672 extends _UserPreference
1674 function _UserPreference_theme ($default = THEME) {
1675 $this->_UserPreference($default);
1678 function sanify ($value) {
1679 if (!empty($value) and FindFile($this->_themefile($value)))
1681 return $this->default_value;
1684 function update ($newvalue) {
1686 // invalidate etag to force fresh output
1687 if (! $this->_init )
1688 $GLOBALS['request']->setValidators(array('%mtime' => false));
1690 include_once($this->_themefile($newvalue));
1691 if (empty($WikiTheme))
1692 include_once($this->_themefile(THEME));
1695 function _themefile ($theme) {
1696 return "themes/$theme/themeinfo.php";
1700 class _UserPreference_notify
1701 extends _UserPreference
1703 function sanify ($value) {
1707 return $this->default_value;
1710 /** update to global user prefs: side-effect on set notify changes
1711 * use a global_data notify hash:
1712 * notify = array('pagematch' => array(userid => ('email' => mail,
1713 * 'verified' => 0|1),
1717 function update ($value) {
1718 if (!empty($this->_init)) return;
1719 $dbh = $GLOBALS['request']->getDbh();
1720 $notify = $dbh->get('notify');
1725 // expand to existing pages only or store matches?
1726 // for now we store (glob-style) matches which is easier for the user
1727 $pages = $this->_page_split($value);
1728 // Limitation: only current user.
1729 $user = $GLOBALS['request']->getUser();
1730 if (!$user or !method_exists($user,'UserName')) return;
1731 // This fails with php5 and a WIKI_ID cookie:
1732 $userid = $user->UserName();
1733 $email = $user->_prefs->get('email');
1734 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1735 // check existing notify hash and possibly delete pages for email
1736 if (!empty($data)) {
1737 foreach ($data as $page => $users) {
1738 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1739 unset($data[$page][$userid]);
1741 if (count($data[$page]) == 0)
1742 unset($data[$page]);
1745 // add the new pages
1746 if (!empty($pages)) {
1747 foreach ($pages as $page) {
1748 if (!isset($data[$page]))
1749 $data[$page] = array();
1750 if (!isset($data[$page][$userid])) {
1751 // should we really store the verification notice here or
1752 // check it dynamically at every page->save?
1754 $data[$page][$userid] = array('email' => $email,
1755 'verified' => $verified);
1757 $data[$page][$userid] = array('email' => $email);
1762 // store users changes
1763 $dbh->set('notify',$data);
1766 /** split the user-given comma or whitespace delimited pagenames
1769 function _page_split($value) {
1770 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1774 class _UserPreference_email
1775 extends _UserPreference
1777 function get($name) {
1778 // get email address from Gforge
1779 if (GFORGE && session_loggedin()) {
1780 $user = session_get_user();
1781 return $user->getEmail();
1787 function sanify($value) {
1788 // email address is already checked by Gforge
1789 if (GFORGE) return $value;
1790 // check for valid email address
1791 if ($this->get('email') == $value and $this->getraw('emailVerified'))
1794 if ($value == 1 or $value === true)
1796 list($ok,$msg) = ValidateMail($value,'noconnect');
1800 trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
1801 return $this->default_value;
1805 /** Side-effect on email changes:
1806 * Send a verification mail or for now just a notification email.
1807 * For true verification (value = 2), we'd need a mailserver hook.
1809 function update($value) {
1810 // email address is already checked by Gforge
1811 if (GFORGE) return $value;
1812 if (!empty($this->_init)) return;
1813 $verified = $this->getraw('emailVerified');
1815 if (($value == 1 or $value === true) and $verified)
1817 if (!empty($value) and !$verified) {
1818 list($ok,$msg) = ValidateMail($value);
1819 if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
1820 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1821 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) {
1822 $this->set('emailVerified',1);
1824 trigger_error($msg, E_USER_WARNING);
1830 /** Check for valid email address
1831 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1832 Note: too strict, Bug #1053681
1834 function ValidateMail($email, $noconnect=false) {
1836 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1838 // if this check is too strict (like invalid mail addresses in a local network only)
1839 // uncomment the following line:
1840 //return array(true,"not validated");
1841 // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1845 // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1846 // addresses, from the Perl module Mail::RFC822::Address, reduced to
1847 // accept single RFC822 addresses without comments only. (The original
1848 // accepts groups and properly commented addresses also.)
1849 $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1851 $specials = '()<>@,;:\\\\".\\[\\]';
1852 $controls = '\\000-\\031';
1854 $dtext = "[^\\[\\]\\r\\\\]";
1855 $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1857 $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1859 $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1860 $word = "(?:$atom|$quoted_string)";
1861 $localpart = "$word(?:\\.$lwsp*$word)*";
1863 $sub_domain = "(?:$atom|$domain_literal)";
1864 $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1866 $addr_spec = "$localpart\@$lwsp*$domain";
1869 $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1870 $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1871 $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1873 $rfc822re = "/$lwsp*$mailbox/";
1874 unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1875 $atom, $word, $quoted_string);
1876 unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1878 if (!preg_match($rfc822re, $email)) {
1880 $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
1884 return array(true, sprintf(_("E-Mail address '%s' is properly formatted"), $email));
1886 list ( $Username, $Domain ) = explode("@", $email);
1887 //Todo: getmxrr workaround on windows or manual input field to verify it manually
1888 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1889 $ConnectAddress = $MXHost[0];
1891 $ConnectAddress = $Domain;
1892 if (isset($EMailHosts[ $Domain ])) {
1893 $ConnectAddress = $EMailHosts[ $Domain ];
1896 $Connect = @fsockopen ( $ConnectAddress, 25 );
1898 if (ereg("^220", $Out = fgets($Connect, 1024))) {
1899 fputs ($Connect, "HELO $HTTP_HOST\r\n");
1900 $Out = fgets ( $Connect, 1024 );
1901 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
1902 $From = fgets ( $Connect, 1024 );
1903 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
1904 $To = fgets ($Connect, 1024);
1905 fputs ($Connect, "QUIT\r\n");
1907 if (!ereg ("^250", $From)) {
1909 $result[1]="Server rejected address: ". $From;
1912 if (!ereg ( "^250", $To )) {
1914 $result[1]="Server rejected address: ". $To;
1919 $result[1] = "No response from server";
1924 $result[1]="Can not connect E-Mail server.";
1928 $result[1]="E-Mail address '$email' appears to be valid.";
1930 } // end of function
1932 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1937 * This object holds the $request->_prefs subobjects.
1938 * A simple packed array of non-default values get's stored as cookie,
1939 * homepage, or database, which are converted to the array of
1941 * We don't store the objects, because otherwise we will
1942 * not be able to upgrade any subobject. And it's a waste of space also.
1945 class UserPreferences
1947 var $notifyPagesAll;
1949 function UserPreferences($saved_prefs = false) {
1950 // userid stored too, to ensure the prefs are being loaded for
1951 // the correct (currently signing in) userid if stored in a
1953 // Update: for db prefs we disallow passwd.
1954 // userid is needed for pref reflexion. current pref must know its username,
1955 // if some app needs prefs from different users, different from current user.
1958 'userid' => new _UserPreference(''),
1959 'passwd' => new _UserPreference(''),
1960 'autologin' => new _UserPreference_bool(),
1961 //'emailVerified' => new _UserPreference_emailVerified(),
1962 //fixed: store emailVerified as email parameter, 1.3.8
1963 'email' => new _UserPreference_email(''),
1964 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1965 'theme' => new _UserPreference_theme(THEME),
1966 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1967 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1969 EDITWIDTH_MAX_COLS),
1970 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1971 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1972 EDITHEIGHT_MIN_ROWS,
1973 EDITHEIGHT_MAX_ROWS),
1974 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1975 TIMEOFFSET_MIN_HOURS,
1976 TIMEOFFSET_MAX_HOURS),
1977 'ownModifications' => new _UserPreference_bool(),
1978 'majorModificationsOnly' => new _UserPreference_bool(),
1979 'relativeDates' => new _UserPreference_bool(),
1980 'googleLink' => new _UserPreference_bool(), // 1.3.10
1981 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1984 // This should be probably be done with $customUserPreferenceColumns
1985 // For now, we use GFORGE define
1987 $gforgeprefs = array(
1988 'pageTrail' => new _UserPreference_bool(),
1989 'diffMenuItem' => new _UserPreference_bool(),
1990 'pageInfoMenuItem' => new _UserPreference_bool(),
1991 'pdfMenuItem' => new _UserPreference_bool(),
1992 'lockMenuItem' => new _UserPreference_bool(),
1993 'chownMenuItem' => new _UserPreference_bool(),
1994 'setaclMenuItem' => new _UserPreference_bool(),
1995 'removeMenuItem' => new _UserPreference_bool(),
1996 'renameMenuItem' => new _UserPreference_bool(),
1997 'revertMenuItem' => new _UserPreference_bool(),
1998 'backLinksMenuItem' => new _UserPreference_bool(),
1999 'watchPageMenuItem' => new _UserPreference_bool(),
2000 'recentChangesMenuItem' => new _UserPreference_bool(),
2001 'randomPageMenuItem' => new _UserPreference_bool(),
2002 'likePagesMenuItem' => new _UserPreference_bool(),
2003 'specialPagesMenuItem' => new _UserPreference_bool(),
2005 $this->_prefs = array_merge($this->_prefs, $gforgeprefs);
2008 // add custom theme-specific pref types:
2009 // FIXME: on theme changes the wiki_user session pref object will fail.
2010 // We will silently ignore this.
2011 if (!empty($customUserPreferenceColumns))
2012 $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
2014 if (isset($this->_method) and $this->_method == 'SQL') {
2015 //unset($this->_prefs['userid']);
2016 unset($this->_prefs['passwd']);
2019 if (is_array($saved_prefs)) {
2020 foreach ($saved_prefs as $name => $value)
2021 $this->set($name, $value);
2025 function __clone() {
2026 foreach ($this as $key => $val) {
2027 if (is_object($val) || (is_array($val))) {
2028 $this->{$key} = unserialize(serialize($val));
2033 function _getPref($name) {
2034 if ($name == 'emailVerified')
2036 if (!isset($this->_prefs[$name])) {
2037 if ($name == 'passwd2') return false;
2038 if ($name == 'passwd') return false;
2039 trigger_error("$name: unknown preference", E_USER_NOTICE);
2042 return $this->_prefs[$name];
2045 // get the value or default_value of the subobject
2046 function get($name) {
2047 if ($_pref = $this->_getPref($name))
2048 if ($name == 'emailVerified')
2049 return $_pref->getraw($name);
2051 return $_pref->get($name);
2056 // check and set the new value in the subobject
2057 function set($name, $value) {
2058 $pref = $this->_getPref($name);
2059 if ($pref === false)
2062 /* do it here or outside? */
2063 if ($name == 'passwd' and
2064 defined('PASSWORD_LENGTH_MINIMUM') and
2065 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2066 //TODO: How to notify the user?
2070 if ($name == 'theme' and $value == '')
2073 // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2074 if ((!$value and $pref->default_value)
2075 or ($value and !isset($pref->{$name})) // bug #1355533
2076 or ($value and ($pref->{$name} != $pref->default_value)))
2078 if ($name == 'emailVerified') $newvalue = $value;
2079 else $newvalue = $pref->sanify($value);
2080 $pref->set($name, $newvalue);
2082 $this->_prefs[$name] =& $pref;
2086 * use init to avoid update on set
2088 function updatePrefs($prefs, $init = false) {
2090 if ($init) $this->_init = $init;
2091 if (is_object($prefs)) {
2092 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2093 $obj->_init = $init;
2094 if ($obj->get($type) !== $prefs->get($type)) {
2095 if ($obj->set($type, $prefs->get($type)))
2098 foreach (array_keys($this->_prefs) as $type) {
2099 $obj =& $this->_prefs[$type];
2100 $obj->_init = $init;
2101 if ($prefs->get($type) !== $obj->get($type)) {
2102 // special systemdefault prefs: (probably not needed)
2103 if ($type == 'theme' and $prefs->get($type) == '' and
2104 $obj->get($type) == THEME) continue;
2105 if ($type == 'lang' and $prefs->get($type) == '' and
2106 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2107 if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2111 } elseif (is_array($prefs)) {
2112 //unset($this->_prefs['userid']);
2114 if (isset($this->_method) and
2115 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2116 unset($this->_prefs['passwd']);
2119 // emailVerified at first, the rest later
2120 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2121 $obj->_init = $init;
2122 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2123 if ($obj->set($type,$prefs[$type]))
2126 foreach (array_keys($this->_prefs) as $type) {
2127 $obj =& $this->_prefs[$type];
2128 $obj->_init = $init;
2129 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2130 $prefs[$type] = false;
2131 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2132 $prefs[$type] = (int) $prefs[$type];
2133 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2134 // special systemdefault prefs:
2135 if ($type == 'theme' and $prefs[$type] == '' and
2136 $obj->get($type) == THEME) continue;
2137 if ($type == 'lang' and $prefs[$type] == '' and
2138 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2139 if ($obj->set($type,$prefs[$type]))
2147 // For now convert just array of objects => array of values
2148 // Todo: the specialized subobjects must override this.
2151 foreach ($this->_prefs as $name => $object) {
2152 if ($value = $object->getraw($name))
2153 $prefs[$name] = $value;
2154 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2155 $prefs['emailVerified'] = $value;
2156 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2157 if (strlen($value) != strlen(crypt('test')))
2158 $prefs['passwd'] = crypt($value);
2159 else // already crypted
2160 $prefs['passwd'] = $value;
2165 // Merge current notifyPages with notifyPagesAll
2166 // notifyPages are pages to notify in the current project
2167 // while $notifyPagesAll is used to store all the monitored pages.
2168 if (isset($prefs['notifyPages'])) {
2169 $this->notifyPagesAll[PAGE_PREFIX] = $prefs['notifyPages'];
2170 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2174 return $this->pack($prefs);
2177 // packed string or array of values => array of values
2178 // Todo: the specialized subobjects must override this.
2179 function retrieve($packed) {
2180 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2181 $packed = unserialize($packed);
2182 if (!is_array($packed)) return false;
2184 foreach ($packed as $name => $packed_pref) {
2185 if (is_string($packed_pref)
2186 and isSerialized($packed_pref)
2187 and substr($packed_pref, 0, 2) == "O:")
2189 //legacy: check if it's an old array of objects
2190 // Looks like a serialized object.
2191 // This might fail if the object definition does not exist anymore.
2192 // object with ->$name and ->default_value vars.
2193 $pref = @unserialize($packed_pref);
2194 if (is_object($pref))
2195 $prefs[$name] = $pref->get($name);
2196 // fix old-style prefs
2197 } elseif (is_numeric($name) and is_array($packed_pref)) {
2198 if (count($packed_pref) == 1) {
2199 list($name,$value) = each($packed_pref);
2200 $prefs[$name] = $value;
2203 if (isSerialized($packed_pref))
2204 $prefs[$name] = @unserialize($packed_pref);
2205 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2206 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2207 // patched by frederik@pandora.be
2208 if (empty($prefs[$name]))
2209 $prefs[$name] = $packed_pref;
2214 // Restore notifyPages from notifyPagesAll
2215 // notifyPages are pages to notify in the current project
2216 // while $notifyPagesAll is used to store all the monitored pages.
2217 if (isset($prefs['notifyPages'])) {
2218 $this->notifyPagesAll = $prefs['notifyPages'];
2219 if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
2220 $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
2222 $prefs['notifyPages'] = '';
2231 * Check if the given prefs object is different from the current prefs object
2233 function isChanged($other) {
2234 foreach ($this->_prefs as $type => $obj) {
2235 if ($obj->get($type) !== $other->get($type))
2241 function defaultPreferences() {
2243 foreach ($this->_prefs as $key => $obj) {
2244 $prefs[$key] = $obj->default_value;
2251 return $this->_prefs;
2254 function pack($nonpacked) {
2255 return serialize($nonpacked);
2258 function unpack($packed) {
2261 //$packed = base64_decode($packed);
2262 if (substr($packed, 0, 2) == "O:") {
2263 // Looks like a serialized object
2264 return unserialize($packed);
2266 if (substr($packed, 0, 2) == "a:") {
2267 return unserialize($packed);
2269 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2275 return wikihash($this->_prefs);
2279 /** TODO: new pref storage classes
2280 * These are currently user specific and should be rewritten to be pref specific.
2281 * i.e. $this == $user->_prefs
2284 class CookieUserPreferences
2285 extends UserPreferences
2287 function CookieUserPreferences ($saved_prefs = false) {
2288 //_AnonUser::_AnonUser('',$saved_prefs);
2289 UserPreferences::UserPreferences($saved_prefs);
2293 class PageUserPreferences
2294 extends UserPreferences
2296 function PageUserPreferences ($saved_prefs = false) {
2297 UserPreferences::UserPreferences($saved_prefs);
2301 class PearDbUserPreferences
2302 extends UserPreferences
2304 function PearDbUserPreferences ($saved_prefs = false) {
2305 UserPreferences::UserPreferences($saved_prefs);
2309 class AdoDbUserPreferences
2310 extends UserPreferences
2312 function AdoDbUserPreferences ($saved_prefs = false) {
2313 UserPreferences::UserPreferences($saved_prefs);
2315 function getPreferences() {
2316 // override the generic slow method here for efficiency
2317 _AnonUser::getPreferences();
2318 $this->getAuthDbh();
2319 if (isset($this->_select)) {
2320 $dbh = & $this->_auth_dbi;
2321 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2325 $prefs_blob = $rs->fields['pref_blob'];
2327 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2328 $updated = $this->_prefs->updatePrefs($restored_from_db);
2329 //$this->_prefs = new UserPreferences($restored_from_db);
2330 return $this->_prefs;
2334 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2335 if ($restored_from_page = $this->_prefs->retrieve
2336 ($this->_HomePagehandle->get('pref'))) {
2337 $updated = $this->_prefs->updatePrefs($restored_from_page);
2338 //$this->_prefs = new UserPreferences($restored_from_page);
2339 return $this->_prefs;
2342 return $this->_prefs;
2350 // c-basic-offset: 4
2351 // c-hanging-comment-ender-p: nil
2352 // indent-tabs-mode: nil