2 rcs_id('$Id: WikiUserNew.php,v 1.147 2007-09-15 12:55:56 rurban Exp $');
3 /* Copyright (C) 2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
5 * This file is part of PhpWiki.
7 * PhpWiki is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * PhpWiki is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with PhpWiki; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * This is a complete OOP rewrite of the old WikiUser code with various
23 * configurable external authentication methods.
25 * There's only one entry point, the function WikiUser which returns
26 * a WikiUser object, which contains the name, authlevel and user's preferences.
27 * This object might get upgraded during the login step and later also.
28 * There exist three preferences storage methods: cookie, homepage and db,
29 * and multiple password checking methods.
30 * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if
31 * ALLOW_USER_PASSWORDS is defined.
33 * Each user object must define the two preferences methods
34 * getPreferences(), setPreferences(),
35 * and the following 1-4 auth methods
36 * checkPass() must be defined by all classes,
37 * userExists() only if USER_AUTH_POLICY'=='strict'
38 * mayChangePass() only if the password is storable.
39 * storePass() only if the password is storable.
41 * WikiUser() given no name, returns an _AnonUser (anonymous user)
42 * object, who may or may not have a cookie.
43 * However, if the there's a cookie with the userid or a session,
44 * the user is upgraded to the matching user object.
45 * Given a user name, returns a _BogoUser object, who may or may not
46 * have a cookie and/or PersonalPage, one of the various _PassUser objects
47 * or an _AdminUser object.
48 * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might
49 * have stored a password or not. If so, his account is secure, if not
50 * anybody can use it, because the username is visible e.g. in RecentChanges.
52 * Takes care of passwords, all preference loading/storing in the
53 * user's page and any cookies. lib/main.php will query the user object to
54 * verify the password as appropriate.
56 * @author: Reini Urban (the tricky parts),
57 * Carsten Klapp (started rolling the ball)
59 * Random architectural notes, sorted by date:
61 * Test it by defining ENABLE_USER_NEW in config/config.ini
62 * 1) Now a ForbiddenUser is returned instead of false.
63 * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
64 * but may browse. Now with ALLOW_ANON_USER = false he may not browse,
65 * which is needed to disable browse PagePermissions.
66 * I added now ALLOW_ANON_EDIT = true to makes things clear.
67 * (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
69 * 3) Removed pear prepare. Performance hog, and using integers as
70 * handler doesn't help. Do simple sprintf as with adodb. And a prepare
71 * in the object init is no advantage, because in the init loop a lot of
72 * objects are tried, but not used.
73 * 4) Already gotten prefs are passed to the next object to avoid
74 * duplicate getPreferences() calls.
76 * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
77 * So we cannot just discrimate with
78 * if (!check_php_version(5))
80 * A /php5-patch.php is provided, which patches the src automatically
81 * for php4 and php5. Default is php4.
82 * Update: not needed anymore. we use eval to fool the load-time syntax checker.
84 * 6) enforced new cookie policy: prefs don't get stored in cookies
85 * anymore, only in homepage and/or database, but always in the
86 * current session. old pref cookies will get deleted.
88 * 7) Certain themes should be able to extend the predefined list
89 * of preferences. Display/editing is done in the theme specific userprefs.tmpl,
90 * but storage must be extended to the Get/SetPreferences methods.
91 * <theme>/themeinfo.php must provide CustomUserPreferences:
92 * A list of name => _UserPreference class pairs.
95 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
96 define('WIKIAUTH_ANON', 0); // Not signed in.
97 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
98 define('WIKIAUTH_USER', 2); // Bogo user with a password.
99 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
100 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
102 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
103 //if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
104 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
105 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
106 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
108 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
109 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
110 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
112 define('TIMEOFFSET_MIN_HOURS', -26);
113 define('TIMEOFFSET_MAX_HOURS', 26);
114 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
116 /* EMAIL VERIFICATION
117 * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
118 * Provide some overrides here.
119 * ( username @ ) domain => mail-domain
121 $EMailHosts = array('avl.com' => 'mail.avl.com');
124 * There are be the following constants in config/config.ini to
125 * establish login parameters:
127 * ALLOW_ANON_USER default true
128 * ALLOW_ANON_EDIT default true
129 * ALLOW_BOGO_LOGIN default true
130 * ALLOW_USER_PASSWORDS default true
131 * PASSWORD_LENGTH_MINIMUM default 0
133 * To require user passwords for editing:
134 * ALLOW_ANON_USER = true
135 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
136 * ALLOW_BOGO_LOGIN = false
137 * ALLOW_USER_PASSWORDS = true
139 * To establish a COMPLETELY private wiki, such as an internal
141 * ALLOW_ANON_USER = false
142 * (and probably require user passwords as described above). In this
143 * case the user will be prompted to login immediately upon accessing
146 * There are other possible combinations, but the typical wiki (such
147 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
152 // The last object in the row is the bad guy...
153 if (!is_array($USER_AUTH_ORDER))
154 $USER_AUTH_ORDER = array("Forbidden");
156 $USER_AUTH_ORDER[] = "Forbidden";
158 // Local convenience functions.
159 function _isAnonUserAllowed() {
160 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
162 function _isBogoUserAllowed() {
163 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
165 function _isUserPasswordsAllowed() {
166 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
169 // Possibly upgrade userobject functions.
170 function _determineAdminUserOrOtherUser($UserName) {
171 // Sanity check. User name is a condition of the definition of the
172 // _AdminUser, _BogoUser and _passuser.
174 return $GLOBALS['ForbiddenUser'];
176 //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
177 //$group = &WikiGroup::getGroup($GLOBALS['request']);
178 if ($UserName == ADMIN_USER)
179 return new _AdminUser($UserName);
180 /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
181 return _determineBogoUserOrPassUser($UserName);
185 return _determineBogoUserOrPassUser($UserName);
188 function _determineBogoUserOrPassUser($UserName) {
189 global $ForbiddenUser;
191 // Sanity check. User name is a condition of the definition of
192 // _BogoUser and _PassUser.
194 return $ForbiddenUser;
196 // Check for password and possibly upgrade user object.
197 // $_BogoUser = new _BogoUser($UserName);
198 if (_isBogoUserAllowed() and isWikiWord($UserName)) {
199 include_once("lib/WikiUser/BogoLogin.php");
200 $_BogoUser = new _BogoLoginPassUser($UserName);
201 if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
204 if (_isUserPasswordsAllowed()) {
205 // PassUsers override BogoUsers if a password is stored
206 if (isset($_BogoUser) and isset($_BogoUser->_prefs)
207 and $_BogoUser->_prefs->get('passwd'))
208 return new _PassUser($UserName, $_BogoUser->_prefs);
210 $_PassUser = new _PassUser($UserName,
211 isset($_BogoUser) ? $_BogoUser->_prefs : false);
212 if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
213 if (isset($GLOBALS['request']->_user_class))
214 $class = $GLOBALS['request']->_user_class;
215 elseif (strtolower(get_class($_PassUser)) == "_passuser")
216 $class = $_PassUser->nextClass();
218 $class = get_class($_PassUser);
219 if ($user = new $class($UserName, $_PassUser->_prefs)) {
227 // No Bogo- or PassUser exists, or
228 // passwords are not allowed, and bogo is disallowed too.
229 // (Only the admin can sign in).
230 return $ForbiddenUser;
234 * Primary WikiUser function, called by lib/main.php.
236 * This determines the user's type and returns an appropriate user
237 * object. lib/main.php then querys the resultant object for password
238 * validity as necessary.
240 * If an _AnonUser object is returned, the user may only browse pages
241 * (and save prefs in a cookie).
243 * To disable access but provide prefs the global $ForbiddenUser class
244 * is returned. (was previously false)
247 function WikiUser ($UserName = '') {
248 global $ForbiddenUser, $HTTP_SESSION_VARS;
250 //Maybe: Check sessionvar for username & save username into
251 //sessionvar (may be more appropriate to do this in lib/main.php).
253 $ForbiddenUser = new _ForbiddenUser($UserName);
254 // Found a user name.
255 return _determineAdminUserOrOtherUser($UserName);
257 elseif (!empty($HTTP_SESSION_VARS['userid'])) {
258 // Found a user name.
259 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
260 return _determineAdminUserOrOtherUser($_SESSION['userid']);
263 // Check for autologin pref in cookie and possibly upgrade
264 // user object to another type.
265 $_AnonUser = new _AnonUser();
266 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
267 // Found a user name.
268 $ForbiddenUser = new _ForbiddenUser($UserName);
269 return _determineAdminUserOrOtherUser($UserName);
272 $ForbiddenUser = new _ForbiddenUser();
273 if (_isAnonUserAllowed())
275 return $ForbiddenUser; // User must sign in to browse pages.
277 return $ForbiddenUser; // User must sign in with a password.
280 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
281 . "Unexpectedly, an appropriate user class could not be determined.");
282 return $ForbiddenUser; // Failsafe.
287 * WikiUser.php use the name 'WikiUser'
289 function WikiUserClassname() {
295 * Upgrade olduser by copying properties from user to olduser.
296 * We are not sure yet, for which php's a simple $this = $user works reliably,
297 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
298 * that's why try it the hard way.
300 function UpgradeUser ($user, $newuser) {
301 if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) {
302 // populate the upgraded class $newuser with the values from the current user object
303 //only _auth_level, _current_method, _current_index,
304 if (!empty($user->_level) and
305 $user->_level > $newuser->_level)
306 $newuser->_level = $user->_level;
307 if (!empty($user->_current_index) and
308 $user->_current_index > $newuser->_current_index) {
309 $newuser->_current_index = $user->_current_index;
310 $newuser->_current_method = $user->_current_method;
312 if (!empty($user->_authmethod))
313 $newuser->_authmethod = $user->_authmethod;
314 $GLOBALS['request']->_user_class = get_class($newuser);
316 foreach (get_object_vars($user) as $k => $v) {
317 if (!empty($v)) $olduser->$k = $v;
320 $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
321 //$GLOBALS['request']->_user = $olduser;
329 * Probably not needed, since we use the various user objects methods so far.
330 * Anyway, here it is, looping through all available objects.
332 function UserExists ($UserName) {
334 if (!($user = $request->getUser()))
335 $user = WikiUser($UserName);
338 if ($user->userExists($UserName)) {
339 $request->_user = $user;
342 if (isa($user,'_BogoUser'))
343 $user = new _PassUser($UserName,$user->_prefs);
344 $class = $user->nextClass();
345 if ($user = new $class($UserName, $user->_prefs)) {
346 return $user->userExists($UserName);
348 $request->_user = $GLOBALS['ForbiddenUser'];
352 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
355 * Base WikiUser class.
360 var $_level = WIKIAUTH_ANON;
362 var $_HomePagehandle = false;
365 function _WikiUser($UserName='', $prefs=false) {
367 $this->_userid = $UserName;
368 $this->_HomePagehandle = false;
370 $this->hasHomePage();
372 if (empty($this->_prefs)) {
373 if ($prefs) $this->_prefs = $prefs;
374 else $this->getPreferences();
378 function UserName() {
379 if (!empty($this->_userid))
380 return $this->_userid;
383 function getPreferences() {
384 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
385 . "New subclasses of _WikiUser must override this function.");
389 function setPreferences($prefs, $id_only) {
390 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
392 . "New subclasses of _WikiUser must override this function.");
396 function userExists() {
397 return $this->hasHomePage();
400 function checkPass($submitted_password) {
401 // By definition, an undefined user class cannot sign in.
402 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
404 . "New subclasses of _WikiUser must override this function.");
408 // returns page_handle to user's home page or false if none
409 function hasHomePage() {
410 if ($this->_userid) {
411 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
412 return $this->_HomePagehandle->exists();
415 // check db again (maybe someone else created it since
418 $this->_HomePagehandle = $request->getPage($this->_userid);
419 return $this->_HomePagehandle->exists();
427 function createHomePage() {
429 $versiondata = array('author' => _("The PhpWiki programming team"));
430 $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.").
431 "\n{{Template/UserPage}}",
433 $request->_dbi->touch();
434 $this->_HomePagehandle = $request->getPage($this->_userid);
437 // innocent helper: case-insensitive position in _auth_methods
438 function array_position ($string, $array) {
439 $string = strtolower($string);
440 for ($found = 0; $found < count($array); $found++) {
441 if (strtolower($array[$found]) == $string)
447 function nextAuthMethodIndex() {
448 if (empty($this->_auth_methods))
449 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
450 if (empty($this->_current_index)) {
451 if (strtolower(get_class($this)) != '_passuser') {
452 $this->_current_method = substr(get_class($this),1,-8);
453 $this->_current_index = $this->array_position($this->_current_method,
454 $this->_auth_methods);
456 $this->_current_index = -1;
459 $this->_current_index++;
460 if ($this->_current_index >= count($this->_auth_methods))
462 $this->_current_method = $this->_auth_methods[$this->_current_index];
463 return $this->_current_index;
466 function AuthMethod($index = false) {
467 return $this->_auth_methods[ $index === false
468 ? count($this->_auth_methods)-1
472 // upgrade the user object
473 function nextClass() {
474 $method = $this->AuthMethod($this->nextAuthMethodIndex());
475 include_once("lib/WikiUser/$method.php");
476 return "_".$method."PassUser";
479 //Fixme: for _HttpAuthPassUser
480 function PrintLoginForm (&$request, $args, $fail_message = false,
481 $seperate_page = false) {
482 include_once('lib/Template.php');
483 // Call update_locale in case the system's default language is not 'en'.
484 // (We have no user pref for lang at this point yet, no one is logged in.)
485 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
486 update_locale(DEFAULT_LANGUAGE);
487 $userid = $this->_userid;
489 extract($args); // fixme
491 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
493 $pagename = $request->getArg('pagename');
495 $login = Template('login',
496 compact('pagename', 'userid', 'require_level',
497 'fail_message', 'pass_required', 'nocache'));
498 // check if the html template was already processed
499 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
500 if ($seperate_page) {
501 $page = $request->getPage($pagename);
502 $revision = $page->getCurrentRevision();
503 return GeneratePage($login,_("Sign In"), $revision);
505 return $login->printExpansion();
509 /** Signed in but not password checked or empty password.
511 function isSignedIn() {
512 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
515 /** This is password checked for sure.
517 function isAuthenticated() {
518 //return isa($this,'_PassUser');
519 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
520 return $this->_level >= WIKIAUTH_BOGO;
523 function isAdmin () {
525 if ($this->_level == WIKIAUTH_ADMIN) return true;
526 if (!$this->isSignedIn()) return false;
527 if (!$this->isAuthenticated()) return false;
529 if (!$group) $group = &$GLOBALS['request']->getGroup();
530 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
533 /** Name or IP for a signed user. UserName could come from a cookie e.g.
536 return ( $this->UserName()
538 : $GLOBALS['request']->get('REMOTE_ADDR') );
541 /** Name for an authenticated user. No IP here.
543 function getAuthenticatedId() {
544 return ( $this->isAuthenticated()
546 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
549 function hasAuthority ($require_level) {
550 return $this->_level >= $require_level;
553 /* This is quite restrictive and not according the login description online.
554 Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
555 The backends may loosen or tighten this.
557 function isValidName ($userid = false) {
558 if (!$userid) $userid = $this->_userid;
559 if (!$userid) return false;
560 return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
564 * Called on an auth_args POST request, such as login, logout or signin.
565 * TODO: Check BogoLogin users with empty password. (self-signed users)
567 function AuthCheck ($postargs) {
568 // Normalize args, and extract.
569 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
571 foreach ($keys as $key)
572 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
574 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
576 if ($logout) { // Log out
577 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
579 $zone_offset = Request_AccessLogEntry::_zone_offset();
580 $ncsa_time = date("d/M/Y:H:i:s", time());
581 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
582 (string) $request->get('REMOTE_HOST'),
583 (string) $request->_user->_userid,
584 $ncsa_time, $zone_offset,
585 "logout ".get_class($request->_user),
587 (string) $request->get('HTTP_REFERER'),
588 (string) $request->get('HTTP_USER_AGENT')
590 if (($fp = fopen(LOGIN_LOG, "a"))) {
592 fputs($fp, "$entry\n");
595 //error_log("$entry\n", 3, LOGIN_LOG);
597 if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
598 $GLOBALS['request']->_user->logout();
600 $user = new _AnonUser();
602 $user->_level = WIKIAUTH_ANON;
605 return false; // User hit cancel button.
606 elseif (!$login && !$userid)
607 return false; // Nothing to do?
609 if (!$this->isValidName($userid))
610 return _("Invalid username.");;
612 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
614 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
616 $zone_offset = Request_AccessLogEntry::_zone_offset();
617 $ncsa_time = date("d/M/Y:H:i:s", time());
618 $manglepasswd = $passwd;
619 for ($i=0; $i<strlen($manglepasswd); $i++) {
620 $c = substr($manglepasswd,$i,1);
621 if (ord($c) < 32) $manglepasswd[$i] = "<";
622 elseif ($c == '*') $manglepasswd[$i] = "*";
623 elseif ($c == '?') $manglepasswd[$i] = "?";
624 elseif ($c == '(') $manglepasswd[$i] = "(";
625 elseif ($c == ')') $manglepasswd[$i] = ")";
626 elseif ($c == "\\") $manglepasswd[$i] = "\\";
627 elseif (ord($c) < 127) $manglepasswd[$i] = "x";
628 elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
630 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
631 $request->get('REMOTE_HOST'),
632 (string) $request->_user->_userid,
633 $ncsa_time, $zone_offset,
634 "login $userid/$manglepasswd => $authlevel ".get_class($request->_user),
635 $authlevel > 0 ? "200" : "403",
636 (string) $request->get('HTTP_REFERER'),
637 (string) $request->get('HTTP_USER_AGENT')
639 if (($fp = fopen(LOGIN_LOG, "a"))) {
641 fputs($fp, "$entry\n");
644 //error_log("$entry\n", 3, LOGIN_LOG);
647 if ($authlevel <= 0) { // anon or forbidden
649 return _("Invalid password.");
651 return _("Invalid password or userid.");
652 } elseif ($authlevel < $require_level) { // auth ok, but not enough
653 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
656 $class = "_" . $this->_current_method . "PassUser";
657 include_once("lib/WikiUser/".$this->_current_method.".php");
658 $user = new $class($userid,$this->_prefs);
659 if (!check_php_version(5))
660 eval("\$this = \$user;");
661 // /*PHP5 patch*/$this = $user;
662 $this->_level = $authlevel;
665 $this->_userid = $userid;
666 $this->_level = $authlevel;
667 return _("Insufficient permissions.");
671 //$user = $GLOBALS['request']->_user;
672 if (!empty($this->_current_method) and
673 strtolower(get_class($this)) == '_passuser')
676 $class = "_" . $this->_current_method . "PassUser";
677 include_once("lib/WikiUser/".$this->_current_method.".php");
678 $user = new $class($userid, $this->_prefs);
679 if (!check_php_version(5))
680 eval("\$this = \$user;");
681 // /*PHP5 patch*/$this = $user;
682 $user->_level = $authlevel;
685 $this->_userid = $userid;
686 $this->_level = $authlevel;
693 * Not authenticated in user, but he may be signed in. Basicly with view access only.
694 * prefs are stored in cookies, but only the userid.
699 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
701 /** Anon only gets to load and save prefs in a cookie, that's it.
703 function getPreferences() {
706 if (empty($this->_prefs))
707 $this->_prefs = new UserPreferences;
708 $UserName = $this->UserName();
710 // Try to read deprecated 1.3.x style cookies
711 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
712 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
713 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
715 . sprintf("%s='%s'", WIKI_NAME, $cookie)
717 . _("Default preferences will be used."),
721 * Only set if it matches the UserName who is
722 * signing in or if this really is an Anon login (no
723 * username). (Remember, _BogoUser and higher inherit this
726 if (! $UserName || $UserName == @$unboxedcookie['userid']) {
727 $updated = $this->_prefs->updatePrefs($unboxedcookie);
728 //$this->_prefs = new UserPreferences($unboxedcookie);
729 $UserName = @$unboxedcookie['userid'];
730 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
731 $this->_userid = $UserName;
735 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
737 $request->deleteCookieVar(WIKI_NAME);
739 // Try to read deprecated 1.3.4 style cookies
740 if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
741 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
742 if (! $UserName || $UserName == $unboxedcookie['userid']) {
743 $updated = $this->_prefs->updatePrefs($unboxedcookie);
744 //$this->_prefs = new UserPreferences($unboxedcookie);
745 $UserName = $unboxedcookie['userid'];
746 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
747 $this->_userid = $UserName;
752 $request->deleteCookieVar("WIKI_PREF2");
756 // Try reading userid from old PhpWiki cookie formats:
757 if ($cookie = $request->cookies->get_old(getCookieName())) {
758 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
760 elseif (is_array($cookie) and !empty($cookie['userid']))
761 $UserName = $cookie['userid'];
763 if (! $UserName and !headers_sent())
764 $request->deleteCookieVar(getCookieName());
766 $this->_userid = $UserName;
769 // initializeTheme() needs at least an empty object
771 if (empty($this->_prefs))
772 $this->_prefs = new UserPreferences;
774 return $this->_prefs;
777 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
779 * Allow for multiple wikis in same domain. Encode only the
780 * _prefs array of the UserPreference object. Ideally the
781 * prefs array should just be imploded into a single string or
782 * something so it is completely human readable by the end
783 * user. In that case stricter error checking will be needed
784 * when loading the cookie.
786 function setPreferences($prefs, $id_only=false) {
787 if (!is_object($prefs)) {
788 if (is_object($this->_prefs)) {
789 $updated = $this->_prefs->updatePrefs($prefs);
790 $prefs =& $this->_prefs;
792 // update the prefs values from scratch. This could leed to unnecessary
793 // side-effects: duplicate emailVerified, ...
794 $this->_prefs = new UserPreferences($prefs);
798 if (!isset($this->_prefs))
799 $this->_prefs =& $prefs;
801 $updated = $this->_prefs->isChanged($prefs);
804 if ($id_only and !headers_sent()) {
806 // new 1.3.8 policy: no array cookies, only plain userid string as in
807 // the pre 1.3.x versions.
808 // prefs should be stored besides the session in the homepagehandle or in a db.
809 $request->setCookieVar(getCookieName(), $this->_userid,
810 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
811 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
812 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
815 $packed = $prefs->store();
816 $unpacked = $prefs->unpack($packed);
817 if (count($unpacked)) {
818 foreach (array('_method','_select','_update','_insert') as $param) {
819 if (!empty($this->_prefs->{$param}))
820 $prefs->{$param} = $this->_prefs->{$param};
822 $this->_prefs = $prefs;
827 function userExists() {
831 function checkPass($submitted_password) {
833 // this might happen on a old-style signin button.
835 // By definition, the _AnonUser does not HAVE a password
836 // (compared to _BogoUser, who has an EMPTY password).
837 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
838 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
839 . "New subclasses of _WikiUser must override this function.");
846 * Helper class to finish the PassUser auth loop.
847 * This is added automatically to USER_AUTH_ORDER.
852 var $_level = WIKIAUTH_FORBIDDEN;
854 function checkPass($submitted_password) {
855 return WIKIAUTH_FORBIDDEN;
858 function userExists() {
859 if ($this->_HomePagehandle) return true;
865 * Do NOT extend _BogoUser to other classes, for checkPass()
866 * security. (In case of defects in code logic of the new class!)
867 * The intermediate step between anon and passuser.
868 * We also have the _BogoLoginPassUser class with stricter
869 * password checking, which fits into the auth loop.
870 * Note: This class is not called anymore by WikiUser()
875 function userExists() {
876 if (isWikiWord($this->_userid)) {
877 $this->_level = WIKIAUTH_BOGO;
880 $this->_level = WIKIAUTH_ANON;
885 function checkPass($submitted_password) {
886 // By definition, BogoUser has an empty password.
888 return $this->_level;
895 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
897 * The classes for all subsequent auth methods extend from this class.
898 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
899 * the three auth method policies first-only, strict and stacked
900 * and the two methods for prefs: homepage or database,
901 * if $DBAuthParams['pref_select'] is defined.
903 * Default is PersonalPage auth and prefs.
905 * @author: Reini Urban
909 var $_auth_dbi, $_prefs;
910 var $_current_method, $_current_index;
912 // check and prepare the auth and pref methods only once
913 function _PassUser($UserName='', $prefs=false) {
914 //global $DBAuthParams, $DBParams;
916 /*if (!$this->isValidName($UserName))
918 $this->_userid = $UserName;
919 if ($this->hasHomePage())
920 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
922 $this->_authmethod = substr(get_class($this),1,-8);
923 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
925 // Check the configured Prefs methods
926 $dbi = $this->getAuthDbh();
927 $dbh = $GLOBALS['request']->getDbh();
928 if ( $dbi and !isset($this->_prefs->_select) and $dbh->getAuthParam('pref_select')) {
929 if (!$this->_prefs) {
930 $this->_prefs = new UserPreferences();
933 $this->_prefs->_method = $dbh->getParam('dbtype');
934 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
936 if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
937 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
938 array("userid", "pref_blob"));
941 if (!$this->_prefs) {
942 $this->_prefs = new UserPreferences();
945 $this->_prefs->_method = 'HomePage';
948 if (! $this->_prefs or isset($need_pref) ) {
949 if ($prefs) $this->_prefs = $prefs;
950 else $this->getPreferences();
953 // Upgrade to the next parent _PassUser class. Avoid recursion.
954 if ( strtolower(get_class($this)) === '_passuser' ) {
955 //auth policy: Check the order of the configured auth methods
956 // 1. first-only: Upgrade the class here in the constructor
957 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
958 /// in the previous PhpWiki releases (slow)
959 // 3. strict: upgrade the class after checking the user existance in userExists()
960 // 4. stacked: upgrade the class after the password verification in checkPass()
961 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
962 //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
963 if (defined('USER_AUTH_POLICY')) {
964 // policy 1: only pre-define one method for all users
965 if (USER_AUTH_POLICY === 'first-only') {
966 $class = $this->nextClass();
967 return new $class($UserName,$this->_prefs);
969 // Use the default behaviour from the previous versions:
970 elseif (USER_AUTH_POLICY === 'old') {
971 // Default: try to be smart
972 // On php5 we can directly return and upgrade the Object,
973 // before we have to upgrade it manually.
974 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
975 include_once("lib/WikiUser/HttpAuth.php");
976 if (check_php_version(5))
977 return new _HttpAuthPassUser($UserName,$this->_prefs);
979 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
980 eval("\$this = \$user;");
981 // /*PHP5 patch*/$this = $user;
984 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
985 $dbh->getAuthParam('auth_check') and
986 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
987 if (check_php_version(5))
988 return new _DbPassUser($UserName,$this->_prefs);
990 $user = new _DbPassUser($UserName,$this->_prefs);
991 eval("\$this = \$user;");
992 // /*PHP5 patch*/$this = $user;
995 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
996 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
997 function_exists('ldap_connect')) {
998 include_once("lib/WikiUser/LDAP.php");
999 if (check_php_version(5))
1000 return new _LDAPPassUser($UserName,$this->_prefs);
1002 $user = new _LDAPPassUser($UserName,$this->_prefs);
1003 eval("\$this = \$user;");
1004 // /*PHP5 patch*/$this = $user;
1007 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1008 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
1009 include_once("lib/WikiUser/IMAP.php");
1010 if (check_php_version(5))
1011 return new _IMAPPassUser($UserName,$this->_prefs);
1013 $user = new _IMAPPassUser($UserName,$this->_prefs);
1014 eval("\$this = \$user;");
1015 // /*PHP5 patch*/$this = $user;
1018 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1019 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
1020 include_once("lib/WikiUser/File.php");
1021 if (check_php_version(5))
1022 return new _FilePassUser($UserName, $this->_prefs);
1024 $user = new _FilePassUser($UserName, $this->_prefs);
1025 eval("\$this = \$user;");
1026 // /*PHP5 patch*/$this = $user;
1030 include_once("lib/WikiUser/PersonalPage.php");
1031 if (check_php_version(5))
1032 return new _PersonalPagePassUser($UserName,$this->_prefs);
1034 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
1035 eval("\$this = \$user;");
1036 // /*PHP5 patch*/$this = $user;
1042 // else use the page methods defined in _PassUser.
1048 function getAuthDbh () {
1049 global $request; //, $DBParams, $DBAuthParams;
1051 $dbh = $request->getDbh();
1052 // session restauration doesn't re-connect to the database automatically,
1053 // so dirty it here, to force a reconnect.
1054 if (isset($this->_auth_dbi)) {
1055 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1056 unset($this->_auth_dbi);
1057 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1058 unset($this->_auth_dbi);
1060 if (empty($this->_auth_dbi)) {
1061 if ($dbh->getParam('dbtype') != 'SQL'
1062 and $dbh->getParam('dbtype') != 'ADODB'
1063 and $dbh->getParam('dbtype') != 'PDO')
1065 if (empty($GLOBALS['DBAuthParams']))
1067 if (!$dbh->getAuthParam('auth_dsn')) {
1068 $dbh = $request->getDbh(); // use phpwiki database
1069 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1070 $dbh = $request->getDbh(); // same phpwiki database
1071 } else { // use another external database handle. needs PHP >= 4.1
1072 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1073 $local_params['dsn'] = $local_params['auth_dsn'];
1074 $dbh = WikiDB::open($local_params);
1076 $this->_auth_dbi =& $dbh->_backend->_dbh;
1078 return $this->_auth_dbi;
1081 function _normalize_stmt_var($var, $oldstyle = false) {
1082 static $valid_variables = array('userid','password','pref_blob','groupname');
1083 // old-style: "'$userid'"
1084 // new-style: '"\$userid"' or just "userid"
1085 $new = str_replace(array("'",'"','\$','$'),'',$var);
1086 if (!in_array($new, $valid_variables)) {
1087 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1090 return !$oldstyle ? "'$".$new."'" : '\$'.$new;
1093 // TODO: use it again for the auth and member tables
1094 // sprintfstyle vs prepare style: %s or ?
1095 // multiple vars should be executed via prepare(?,?)+execute,
1096 // single vars with execute(sprintf(quote(var)))
1097 // help with position independency
1098 function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) {
1100 $dbi = $request->getDbh();
1101 $this->getAuthDbh();
1102 // "'\$userid"' => %s
1103 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1104 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1106 if (is_array($variables)) {
1107 //$sprintfstyle = false;
1108 for ($i=0; $i < count($variables); $i++) {
1109 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1111 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1112 $variables[$i], $stmt), E_USER_WARNING);
1113 $variables[$i] = $var;
1114 if (!$var) $new[] = '';
1116 $s = "%" . ($i+1) . "s";
1117 $new[] = $sprintfstyle ? $s : "?";
1121 $var = $this->_normalize_stmt_var($variables, $oldstyle);
1123 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1124 $variables, $stmt), E_USER_WARNING);
1126 if (!$var) $new = '';
1127 else $new = $sprintfstyle ? '%s' : "?";
1129 $prefix = $dbi->getParam('prefix');
1130 // probably prefix table names if in same database
1131 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1132 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1134 if (!stristr($stmt, $prefix)) {
1136 $stmt = str_replace(array(" user "," pref "," member "),
1137 array(" ".$prefix."user ",
1138 " ".$prefix."pref ",
1139 " ".$prefix."member "), $stmt);
1140 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1141 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt",
1145 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1146 // Simple sprintf-style.
1147 $new_stmt = str_replace($variables, $new, $stmt);
1148 if ($new_stmt == $stmt) {
1150 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1151 $stmt), E_USER_WARNING);
1153 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1154 $stmt), E_USER_WARNING);
1155 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1161 function getPreferences() {
1162 if (!empty($this->_prefs->_method)) {
1163 if ($this->_prefs->_method == 'ADODB') {
1164 // FIXME: strange why this should be needed...
1165 include_once("lib/WikiUser/Db.php");
1166 include_once("lib/WikiUser/AdoDb.php");
1167 _AdoDbPassUser::_AdoDbPassUser($this->_userid, $this->_prefs);
1168 return _AdoDbPassUser::getPreferences();
1169 } elseif ($this->_prefs->_method == 'SQL') {
1170 include_once("lib/WikiUser/Db.php");
1171 include_once("lib/WikiUser/PearDb.php");
1172 _PearDbPassUser::_PearDbPassUser($this->_userid, $this->_prefs);
1173 return _PearDbPassUser::getPreferences();
1174 } elseif ($this->_prefs->_method == 'PDO') {
1175 include_once("lib/WikiUser/Db.php");
1176 include_once("lib/WikiUser/PdoDb.php");
1177 _PdoDbPassUser::_PdoDbPassUser($this->_userid, $this->_prefs);
1178 return _PdoDbPassUser::getPreferences();
1182 // We don't necessarily have to read the cookie first. Since
1183 // the user has a password, the prefs stored in the homepage
1184 // cannot be arbitrarily altered by other Bogo users.
1185 _AnonUser::getPreferences();
1186 // User may have deleted cookie, retrieve from his
1187 // PersonalPage if there is one.
1188 if (!empty($this->_HomePagehandle)) {
1189 if ($restored_from_page = $this->_prefs->retrieve
1190 ($this->_HomePagehandle->get('pref'))) {
1191 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1192 //$this->_prefs = new UserPreferences($restored_from_page);
1193 return $this->_prefs;
1196 return $this->_prefs;
1199 function setPreferences($prefs, $id_only=false) {
1200 if (!empty($this->_prefs->_method)) {
1201 if ($this->_prefs->_method == 'ADODB') {
1202 // FIXME: strange why this should be needed...
1203 include_once("lib/WikiUser/Db.php");
1204 include_once("lib/WikiUser/AdoDb.php");
1205 _AdoDbPassUser::_AdoDbPassUser($this->_userid, $prefs);
1206 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1208 elseif ($this->_prefs->_method == 'SQL') {
1209 include_once("lib/WikiUser/Db.php");
1210 include_once("lib/WikiUser/PearDb.php");
1211 _PearDbPassUser::_PearDbPassUser($this->_userid, $prefs);
1212 return _PearDbPassUser::setPreferences($prefs, $id_only);
1214 elseif ($this->_prefs->_method == 'PDO') {
1215 include_once("lib/WikiUser/Db.php");
1216 include_once("lib/WikiUser/PdoDb.php");
1217 _PdoDbPassUser::_PdoDbPassUser($this->_userid, $prefs);
1218 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1221 if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1222 // Encode only the _prefs array of the UserPreference object
1223 // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1224 if (empty($this->_HomePagehandle)) {
1225 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1227 if (! $this->_HomePagehandle->exists() ) {
1228 $this->createHomePage();
1230 if (!empty($this->_HomePagehandle) and !$id_only) {
1231 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1237 function mayChangePass() {
1241 //The default method is getting the password from prefs.
1242 // child methods obtain $stored_password from external auth.
1243 function userExists() {
1244 //if ($this->_HomePagehandle) return true;
1245 if (strtolower(get_class($this)) == "_passuser") {
1246 $class = $this->nextClass();
1247 $user = new $class($this->_userid, $this->_prefs);
1252 if (!check_php_version(5))
1253 eval("\$this = \$user;");
1254 $user = UpgradeUser($this, $user);
1255 if ($user->userExists()) {
1256 $user = UpgradeUser($this, $user);
1259 // prevent endless loop. does this work on all PHP's?
1260 // it just has to set the classname, what it correctly does.
1261 $class = $user->nextClass();
1262 if ($class == "_ForbiddenPassUser")
1268 //The default method is getting the password from prefs.
1269 // child methods obtain $stored_password from external auth.
1270 function checkPass($submitted_password) {
1271 $stored_password = $this->_prefs->get('passwd');
1272 if ($this->_checkPass($submitted_password, $stored_password)) {
1273 $this->_level = WIKIAUTH_USER;
1274 return $this->_level;
1276 if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1277 $this->_level = WIKIAUTH_FORBIDDEN;
1278 return $this->_level;
1280 return $this->_tryNextPass($submitted_password);
1285 function _checkPassLength($submitted_password) {
1286 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1287 trigger_error(_("The length of the password is shorter than the system policy allows."));
1294 * The basic password checker for all PassUser objects.
1295 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1296 * Empty passwords are always false!
1297 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1298 * @see UserPreferences::set
1300 * DBPassUser password's have their own crypt definition.
1301 * That's why DBPassUser::checkPass() doesn't call this method, if
1302 * the db password method is 'plain', which means that the DB SQL
1303 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1304 * don't store plain passwords in the DB.
1306 * TODO: remove crypt() function check from config.php:396 ??
1308 function _checkPass($submitted_password, $stored_password) {
1309 if (!empty($submitted_password)) {
1310 // This works only on plaintext passwords.
1311 if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1312 // With the EditMetaData plugin
1313 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."));
1316 if (!$this->_checkPassLength($submitted_password)) {
1319 if (ENCRYPTED_PASSWD) {
1320 // Verify against encrypted password.
1321 if (function_exists('crypt')) {
1322 if (crypt($submitted_password, $stored_password) == $stored_password )
1323 return true; // matches encrypted password
1328 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1329 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1335 // Verify against cleartext password.
1336 if ($submitted_password == $stored_password)
1339 // Check whether we forgot to enable ENCRYPTED_PASSWD
1340 if (function_exists('crypt')) {
1341 if (crypt($submitted_password, $stored_password) == $stored_password) {
1342 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1353 /** The default method is storing the password in prefs.
1354 * Child methods (DB, File) may store in external auth also, but this
1355 * must be explicitly enabled.
1356 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1358 function changePass($submitted_password) {
1359 $stored_password = $this->_prefs->get('passwd');
1360 // check if authenticated
1361 if (!$this->isAuthenticated()) return false;
1362 if (ENCRYPTED_PASSWD) {
1363 $submitted_password = crypt($submitted_password);
1365 // check other restrictions, with side-effects only.
1366 $result = $this->_checkPass($submitted_password, $stored_password);
1367 if ($stored_password != $submitted_password) {
1368 $this->_prefs->set('passwd', $submitted_password);
1369 //update the storage (session, homepage, ...)
1370 $this->SetPreferences($this->_prefs);
1373 //Todo: return an error msg to the caller what failed?
1374 // same password or no privilege
1375 return ENCRYPTED_PASSWD ? true : false;
1378 function _tryNextPass($submitted_password) {
1379 if (DEBUG & _DEBUG_LOGIN) {
1380 $class = strtolower(get_class($this));
1381 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1382 $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1384 if (USER_AUTH_POLICY === 'strict') {
1385 $class = $this->nextClass();
1386 if ($user = new $class($this->_userid,$this->_prefs)) {
1387 if ($user->userExists()) {
1388 return $user->checkPass($submitted_password);
1392 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1393 $class = $this->nextClass();
1394 if ($user = new $class($this->_userid,$this->_prefs))
1395 return $user->checkPass($submitted_password);
1397 return $this->_level;
1400 function _tryNextUser() {
1401 if (DEBUG & _DEBUG_LOGIN) {
1402 $class = strtolower(get_class($this));
1403 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1404 $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1406 if (USER_AUTH_POLICY === 'strict'
1407 or USER_AUTH_POLICY === 'stacked') {
1408 $class = $this->nextClass();
1409 while ($user = new $class($this->_userid, $this->_prefs)) {
1410 if (!check_php_version(5))
1411 eval("\$this = \$user;");
1412 $user = UpgradeUser($this, $user);
1413 if ($user->userExists()) {
1414 $user = UpgradeUser($this, $user);
1417 $class = $this->nextClass();
1426 * Insert more auth classes here...
1427 * For example a customized db class for another db connection
1428 * or a socket-based auth server.
1434 * For security, this class should not be extended. Instead, extend
1435 * from _PassUser (think of this as unix "root").
1437 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1438 * Other members of the Administrators group must raise their level otherwise somehow.
1439 * Currently every member is a AdminUser, which will not work for the various
1445 function mayChangePass() {
1448 function checkPass($submitted_password) {
1449 if ($this->_userid == ADMIN_USER)
1450 $stored_password = ADMIN_PASSWD;
1452 // Should not happen! Only ADMIN_USER should use this class.
1453 // return $this->_tryNextPass($submitted_password); // ???
1454 // TODO: safety check if really member of the ADMIN group?
1455 $stored_password = $this->_pref->get('passwd');
1457 if ($this->_checkPass($submitted_password, $stored_password)) {
1458 $this->_level = WIKIAUTH_ADMIN;
1459 if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1461 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1463 return $this->_level;
1465 return $this->_tryNextPass($submitted_password);
1466 //$this->_level = WIKIAUTH_ANON;
1467 //return $this->_level;
1471 function storePass($submitted_password) {
1472 if ($this->_userid == ADMIN_USER)
1475 // should not happen! only ADMIN_USER should use this class.
1476 return parent::storePass($submitted_password);
1481 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1483 * Various data classes for the preference types,
1484 * to support get, set, sanify (range checking, ...)
1485 * update() will do the neccessary side-effects if a
1486 * setting gets changed (theme, language, ...)
1489 class _UserPreference
1493 function _UserPreference ($default_value) {
1494 $this->default_value = $default_value;
1497 function sanify ($value) {
1498 return (string)$value;
1501 function get ($name) {
1502 if (isset($this->{$name}))
1503 return $this->{$name};
1505 return $this->default_value;
1508 function getraw ($name) {
1509 if (!empty($this->{$name}))
1510 return $this->{$name};
1513 // stores the value as $this->$name, and not as $this->value (clever?)
1514 function set ($name, $value) {
1516 $value = $this->sanify($value);
1517 if ($this->get($name) != $value) {
1518 $this->update($value);
1521 if ($value != $this->default_value) {
1522 $this->{$name} = $value;
1524 unset($this->{$name});
1529 // default: no side-effects
1530 function update ($value) {
1535 class _UserPreference_numeric
1536 extends _UserPreference
1538 function _UserPreference_numeric ($default, $minval = false,
1540 $this->_UserPreference((double)$default);
1541 $this->_minval = (double)$minval;
1542 $this->_maxval = (double)$maxval;
1545 function sanify ($value) {
1546 $value = (double)$value;
1547 if ($this->_minval !== false && $value < $this->_minval)
1548 $value = $this->_minval;
1549 if ($this->_maxval !== false && $value > $this->_maxval)
1550 $value = $this->_maxval;
1555 class _UserPreference_int
1556 extends _UserPreference_numeric
1558 function _UserPreference_int ($default, $minval = false, $maxval = false) {
1559 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1562 function sanify ($value) {
1563 return (int)parent::sanify((int)$value);
1567 class _UserPreference_bool
1568 extends _UserPreference
1570 function _UserPreference_bool ($default = false) {
1571 $this->_UserPreference((bool)$default);
1574 function sanify ($value) {
1575 if (is_array($value)) {
1576 /* This allows for constructs like:
1578 * <input type="hidden" name="pref[boolPref][]" value="0" />
1579 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1581 * (If the checkbox is not checked, only the hidden input
1582 * gets sent. If the checkbox is sent, both inputs get
1585 foreach ($value as $val) {
1591 return (bool) $value;
1595 class _UserPreference_language
1596 extends _UserPreference
1598 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1599 $this->_UserPreference($default);
1602 // FIXME: check for valid locale
1603 function sanify ($value) {
1604 // Revert to DEFAULT_LANGUAGE if user does not specify
1605 // language in UserPreferences or chooses <system language>.
1606 if ($value == '' or empty($value))
1607 $value = DEFAULT_LANGUAGE;
1609 return (string) $value;
1612 function update ($newvalue) {
1613 if (! $this->_init ) {
1614 // invalidate etag to force fresh output
1615 $GLOBALS['request']->setValidators(array('%mtime' => false));
1616 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1621 class _UserPreference_theme
1622 extends _UserPreference
1624 function _UserPreference_theme ($default = THEME) {
1625 $this->_UserPreference($default);
1628 function sanify ($value) {
1629 if (!empty($value) and FindFile($this->_themefile($value)))
1631 return $this->default_value;
1634 function update ($newvalue) {
1636 // invalidate etag to force fresh output
1637 if (! $this->_init )
1638 $GLOBALS['request']->setValidators(array('%mtime' => false));
1640 include_once($this->_themefile($newvalue));
1641 if (empty($WikiTheme))
1642 include_once($this->_themefile(THEME));
1645 function _themefile ($theme) {
1646 return "themes/$theme/themeinfo.php";
1650 class _UserPreference_notify
1651 extends _UserPreference
1653 function sanify ($value) {
1657 return $this->default_value;
1660 /** update to global user prefs: side-effect on set notify changes
1661 * use a global_data notify hash:
1662 * notify = array('pagematch' => array(userid => ('email' => mail,
1663 * 'verified' => 0|1),
1667 function update ($value) {
1668 if (!empty($this->_init)) return;
1669 $dbh = $GLOBALS['request']->getDbh();
1670 $notify = $dbh->get('notify');
1675 // expand to existing pages only or store matches?
1676 // for now we store (glob-style) matches which is easier for the user
1677 $pages = $this->_page_split($value);
1678 // Limitation: only current user.
1679 $user = $GLOBALS['request']->getUser();
1680 if (!$user or !method_exists($user,'UserName')) return;
1681 // This fails with php5 and a WIKI_ID cookie:
1682 $userid = $user->UserName();
1683 $email = $user->_prefs->get('email');
1684 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1685 // check existing notify hash and possibly delete pages for email
1686 if (!empty($data)) {
1687 foreach ($data as $page => $users) {
1688 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1689 unset($data[$page][$userid]);
1691 if (count($data[$page]) == 0)
1692 unset($data[$page]);
1695 // add the new pages
1696 if (!empty($pages)) {
1697 foreach ($pages as $page) {
1698 if (!isset($data[$page]))
1699 $data[$page] = array();
1700 if (!isset($data[$page][$userid])) {
1701 // should we really store the verification notice here or
1702 // check it dynamically at every page->save?
1704 $data[$page][$userid] = array('email' => $email,
1705 'verified' => $verified);
1707 $data[$page][$userid] = array('email' => $email);
1712 // store users changes
1713 $dbh->set('notify',$data);
1716 /** split the user-given comma or whitespace delimited pagenames
1719 function _page_split($value) {
1720 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1724 class _UserPreference_email
1725 extends _UserPreference
1727 function sanify($value) {
1728 // check for valid email address
1729 if ($this->get('email') == $value and $this->getraw('emailVerified'))
1732 if ($value == 1 or $value === true)
1734 list($ok,$msg) = ValidateMail($value,'noconnect');
1738 trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
1739 return $this->default_value;
1743 /** Side-effect on email changes:
1744 * Send a verification mail or for now just a notification email.
1745 * For true verification (value = 2), we'd need a mailserver hook.
1747 function update($value) {
1748 if (!empty($this->_init)) return;
1749 $verified = $this->getraw('emailVerified');
1751 if (($value == 1 or $value === true) and $verified)
1753 if (!empty($value) and !$verified) {
1754 list($ok,$msg) = ValidateMail($value);
1755 if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
1756 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1757 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) {
1758 $this->set('emailVerified',1);
1760 trigger_error($msg, E_USER_WARNING);
1766 /** Check for valid email address
1767 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1768 Note: too strict, Bug #1053681
1770 function ValidateMail($email, $noconnect=false) {
1772 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1774 // if this check is too strict (like invalid mail addresses in a local network only)
1775 // uncomment the following line:
1776 //return array(true,"not validated");
1777 // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1781 // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1782 // addresses, from the Perl module Mail::RFC822::Address, reduced to
1783 // accept single RFC822 addresses without comments only. (The original
1784 // accepts groups and properly commented addresses also.)
1785 $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1787 $specials = '()<>@,;:\\\\".\\[\\]';
1788 $controls = '\\000-\\031';
1790 $dtext = "[^\\[\\]\\r\\\\]";
1791 $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1793 $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1795 $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1796 $word = "(?:$atom|$quoted_string)";
1797 $localpart = "$word(?:\\.$lwsp*$word)*";
1799 $sub_domain = "(?:$atom|$domain_literal)";
1800 $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1802 $addr_spec = "$localpart\@$lwsp*$domain";
1805 $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1806 $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1807 $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1809 $rfc822re = "/$lwsp*$mailbox/";
1810 unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1811 $atom, $word, $quoted_string);
1812 unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1814 if (!preg_match($rfc822re, $email)) {
1816 $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
1820 return array(true, sprintf(_("E-Mail address '%s' is properly formatted"), $email));
1822 list ( $Username, $Domain ) = split ("@", $email);
1823 //Todo: getmxrr workaround on windows or manual input field to verify it manually
1824 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1825 $ConnectAddress = $MXHost[0];
1827 $ConnectAddress = $Domain;
1828 if (isset($EMailHosts[ $Domain ])) {
1829 $ConnectAddress = $EMailHosts[ $Domain ];
1832 $Connect = @fsockopen ( $ConnectAddress, 25 );
1834 if (ereg("^220", $Out = fgets($Connect, 1024))) {
1835 fputs ($Connect, "HELO $HTTP_HOST\r\n");
1836 $Out = fgets ( $Connect, 1024 );
1837 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
1838 $From = fgets ( $Connect, 1024 );
1839 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
1840 $To = fgets ($Connect, 1024);
1841 fputs ($Connect, "QUIT\r\n");
1843 if (!ereg ("^250", $From)) {
1845 $result[1]="Server rejected address: ". $From;
1848 if (!ereg ( "^250", $To )) {
1850 $result[1]="Server rejected address: ". $To;
1855 $result[1] = "No response from server";
1860 $result[1]="Can not connect E-Mail server.";
1864 $result[1]="E-Mail address '$email' appears to be valid.";
1866 } // end of function
1868 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1873 * This object holds the $request->_prefs subobjects.
1874 * A simple packed array of non-default values get's stored as cookie,
1875 * homepage, or database, which are converted to the array of
1877 * We don't store the objects, because otherwise we will
1878 * not be able to upgrade any subobject. And it's a waste of space also.
1881 class UserPreferences
1883 function UserPreferences($saved_prefs = false) {
1884 // userid stored too, to ensure the prefs are being loaded for
1885 // the correct (currently signing in) userid if stored in a
1887 // Update: for db prefs we disallow passwd.
1888 // userid is needed for pref reflexion. current pref must know its username,
1889 // if some app needs prefs from different users, different from current user.
1892 'userid' => new _UserPreference(''),
1893 'passwd' => new _UserPreference(''),
1894 'autologin' => new _UserPreference_bool(),
1895 //'emailVerified' => new _UserPreference_emailVerified(),
1896 //fixed: store emailVerified as email parameter, 1.3.8
1897 'email' => new _UserPreference_email(''),
1898 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1899 'theme' => new _UserPreference_theme(THEME),
1900 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1901 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1903 EDITWIDTH_MAX_COLS),
1904 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1905 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1906 EDITHEIGHT_MIN_ROWS,
1907 EDITHEIGHT_MAX_ROWS),
1908 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1909 TIMEOFFSET_MIN_HOURS,
1910 TIMEOFFSET_MAX_HOURS),
1911 'relativeDates' => new _UserPreference_bool(),
1912 'googleLink' => new _UserPreference_bool(), // 1.3.10
1913 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1915 // add custom theme-specific pref types:
1916 // FIXME: on theme changes the wiki_user session pref object will fail.
1917 // We will silently ignore this.
1918 if (!empty($customUserPreferenceColumns))
1919 $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
1921 if (isset($this->_method) and $this->_method == 'SQL') {
1922 //unset($this->_prefs['userid']);
1923 unset($this->_prefs['passwd']);
1926 if (is_array($saved_prefs)) {
1927 foreach ($saved_prefs as $name => $value)
1928 $this->set($name, $value);
1932 function _getPref($name) {
1933 if ($name == 'emailVerified')
1935 if (!isset($this->_prefs[$name])) {
1936 if ($name == 'passwd2') return false;
1937 if ($name == 'passwd') return false;
1938 trigger_error("$name: unknown preference", E_USER_NOTICE);
1941 return $this->_prefs[$name];
1944 // get the value or default_value of the subobject
1945 function get($name) {
1946 if ($_pref = $this->_getPref($name))
1947 if ($name == 'emailVerified')
1948 return $_pref->getraw($name);
1950 return $_pref->get($name);
1955 // check and set the new value in the subobject
1956 function set($name, $value) {
1957 $pref = $this->_getPref($name);
1958 if ($pref === false)
1961 /* do it here or outside? */
1962 if ($name == 'passwd' and
1963 defined('PASSWORD_LENGTH_MINIMUM') and
1964 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1965 //TODO: How to notify the user?
1969 if ($name == 'theme' and $value == '')
1972 // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
1973 if ((!$value and $pref->default_value)
1974 or ($value and !isset($pref->{$name})) // bug #1355533
1975 or ($value and ($pref->{$name} != $pref->default_value)))
1977 if ($name == 'emailVerified') $newvalue = $value;
1978 else $newvalue = $pref->sanify($value);
1979 $pref->set($name, $newvalue);
1981 $this->_prefs[$name] =& $pref;
1985 * use init to avoid update on set
1987 function updatePrefs($prefs, $init = false) {
1989 if ($init) $this->_init = $init;
1990 if (is_object($prefs)) {
1991 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
1992 $obj->_init = $init;
1993 if ($obj->get($type) !== $prefs->get($type)) {
1994 if ($obj->set($type, $prefs->get($type)))
1997 foreach (array_keys($this->_prefs) as $type) {
1998 $obj =& $this->_prefs[$type];
1999 $obj->_init = $init;
2000 if ($prefs->get($type) !== $obj->get($type)) {
2001 // special systemdefault prefs: (probably not needed)
2002 if ($type == 'theme' and $prefs->get($type) == '' and
2003 $obj->get($type) == THEME) continue;
2004 if ($type == 'lang' and $prefs->get($type) == '' and
2005 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2006 if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2010 } elseif (is_array($prefs)) {
2011 //unset($this->_prefs['userid']);
2013 if (isset($this->_method) and
2014 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2015 unset($this->_prefs['passwd']);
2018 // emailVerified at first, the rest later
2019 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2020 $obj->_init = $init;
2021 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2022 if ($obj->set($type,$prefs[$type]))
2025 foreach (array_keys($this->_prefs) as $type) {
2026 $obj =& $this->_prefs[$type];
2027 $obj->_init = $init;
2028 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2029 $prefs[$type] = false;
2030 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2031 $prefs[$type] = (int) $prefs[$type];
2032 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2033 // special systemdefault prefs:
2034 if ($type == 'theme' and $prefs[$type] == '' and
2035 $obj->get($type) == THEME) continue;
2036 if ($type == 'lang' and $prefs[$type] == '' and
2037 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2038 if ($obj->set($type,$prefs[$type]))
2046 // For now convert just array of objects => array of values
2047 // Todo: the specialized subobjects must override this.
2050 foreach ($this->_prefs as $name => $object) {
2051 if ($value = $object->getraw($name))
2052 $prefs[$name] = $value;
2053 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2054 $prefs['emailVerified'] = $value;
2055 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2056 if (strlen($value) != strlen(crypt('test')))
2057 $prefs['passwd'] = crypt($value);
2058 else // already crypted
2059 $prefs['passwd'] = $value;
2062 return $this->pack($prefs);
2065 // packed string or array of values => array of values
2066 // Todo: the specialized subobjects must override this.
2067 function retrieve($packed) {
2068 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2069 $packed = unserialize($packed);
2070 if (!is_array($packed)) return false;
2072 foreach ($packed as $name => $packed_pref) {
2073 if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2074 //legacy: check if it's an old array of objects
2075 // Looks like a serialized object.
2076 // This might fail if the object definition does not exist anymore.
2077 // object with ->$name and ->default_value vars.
2078 $pref = @unserialize($packed_pref);
2080 $pref = @unserialize(base64_decode($packed_pref));
2081 $prefs[$name] = $pref->get($name);
2082 // fix old-style prefs
2083 } elseif (is_numeric($name) and is_array($packed_pref)) {
2084 if (count($packed_pref) == 1) {
2085 list($name,$value) = each($packed_pref);
2086 $prefs[$name] = $value;
2089 $prefs[$name] = @unserialize($packed_pref);
2090 if (empty($prefs[$name]))
2091 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2092 // patched by frederik@pandora.be
2093 if (empty($prefs[$name]))
2094 $prefs[$name] = $packed_pref;
2101 * Check if the given prefs object is different from the current prefs object
2103 function isChanged($other) {
2104 foreach ($this->_prefs as $type => $obj) {
2105 if ($obj->get($type) !== $other->get($type))
2111 function defaultPreferences() {
2113 foreach ($this->_prefs as $key => $obj) {
2114 $prefs[$key] = $obj->default_value;
2121 return $this->_prefs;
2124 function pack($nonpacked) {
2125 return serialize($nonpacked);
2128 function unpack($packed) {
2131 //$packed = base64_decode($packed);
2132 if (substr($packed, 0, 2) == "O:") {
2133 // Looks like a serialized object
2134 return unserialize($packed);
2136 if (substr($packed, 0, 2) == "a:") {
2137 return unserialize($packed);
2139 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2145 return wikihash($this->_prefs);
2149 /** TODO: new pref storage classes
2150 * These are currently user specific and should be rewritten to be pref specific.
2151 * i.e. $this == $user->_prefs
2154 class CookieUserPreferences
2155 extends UserPreferences
2157 function CookieUserPreferences ($saved_prefs = false) {
2158 //_AnonUser::_AnonUser('',$saved_prefs);
2159 UserPreferences::UserPreferences($saved_prefs);
2163 class PageUserPreferences
2164 extends UserPreferences
2166 function PageUserPreferences ($saved_prefs = false) {
2167 UserPreferences::UserPreferences($saved_prefs);
2171 class PearDbUserPreferences
2172 extends UserPreferences
2174 function PearDbUserPreferences ($saved_prefs = false) {
2175 UserPreferences::UserPreferences($saved_prefs);
2179 class AdoDbUserPreferences
2180 extends UserPreferences
2182 function AdoDbUserPreferences ($saved_prefs = false) {
2183 UserPreferences::UserPreferences($saved_prefs);
2185 function getPreferences() {
2186 // override the generic slow method here for efficiency
2187 _AnonUser::getPreferences();
2188 $this->getAuthDbh();
2189 if (isset($this->_select)) {
2190 $dbh = & $this->_auth_dbi;
2191 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2195 $prefs_blob = $rs->fields['pref_blob'];
2197 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2198 $updated = $this->_prefs->updatePrefs($restored_from_db);
2199 //$this->_prefs = new UserPreferences($restored_from_db);
2200 return $this->_prefs;
2204 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2205 if ($restored_from_page = $this->_prefs->retrieve
2206 ($this->_HomePagehandle->get('pref'))) {
2207 $updated = $this->_prefs->updatePrefs($restored_from_page);
2208 //$this->_prefs = new UserPreferences($restored_from_page);
2209 return $this->_prefs;
2212 return $this->_prefs;
2217 // $Log: not supported by cvs2svn $
2218 // Revision 1.146 2007/08/25 18:34:08 rurban
2219 // add LOGIN_LOG to check possible external auth problems
2221 // Revision 1.145 2007/06/07 16:56:27 rurban
2222 // protect against empty username
2224 // Revision 1.144 2007/06/01 06:36:57 rurban
2225 // allow space in user names. backends should tighten it
2227 // Revision 1.143 2007/05/24 18:37:53 rurban
2228 // silence AdminUser HomePagehandle warning
2230 // Revision 1.142 2007/05/15 16:32:34 rurban
2231 // Refactor class upgrading at ->UserExists
2233 // Revision 1.141 2007/05/13 18:31:24 rurban
2234 // Refactor UpgradeUser. Added EMailHosts
2236 // Revision 1.140 2006/12/22 01:20:14 rurban
2237 // Automatically create a Users homepage, when no SQL method exists
2238 // not to rely on cookies.
2240 // Revision 1.139 2006/09/03 09:55:37 rurban
2241 // Remove too early and too strict isValidName check in _PassUser. This really should be done in
2242 // the method, when we know it. This fixes NTLM auth. (userid=domain\user)
2244 // Revision 1.138 2006/06/18 11:02:55 rurban
2245 // pref->value > -name, fix bug #1355533
2247 // Revision 1.137 2006/05/03 06:05:37 rurban
2248 // Fix default preferences for editheight maxrows, by Manuel Vacelet.
2250 // Revision 1.136 2006/04/16 11:07:48 rurban
2251 // Dont crypt the passwd twice on storing prefs. Patch by Thomas Harding.
2252 // Fixes bug #1327470
2254 // Revision 1.135 2006/03/19 16:26:39 rurban
2255 // fix DBAUTH arguments to be position independent, fixes bug #1358973
2257 // Revision 1.134 2006/03/19 15:01:00 rurban
2258 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2260 // Revision 1.133 2006/03/07 18:39:21 rurban
2261 // add PdoDb, rename hash to wikihash (php-5.1), fix output of Homepage prefs update
2263 // Revision 1.132 2006/03/04 13:19:12 rurban
2264 // fix for fatal error on empty pref value (sign out). Thanks to Jim Ford and Joel Schaubert. rename hash for php-5.1
2266 // Revision 1.131 2005/10/12 06:16:48 rurban
2267 // add new _insert statement
2269 // Revision 1.129 2005/06/10 06:10:35 rurban
2270 // ensure Update Preferences gets through
2272 // Revision 1.128 2005/06/05 05:38:02 rurban
2273 // Default ENABLE_DOUBLECLICKEDIT = false. Moved to UserPreferences
2275 // Revision 1.127 2005/04/02 18:01:41 uckelman
2276 // Fixed regex for RFC822 addresses.
2278 // Revision 1.126 2005/02/28 20:30:46 rurban
2279 // some stupid code for _AdminUser (probably not needed)
2281 // Revision 1.125 2005/02/08 13:25:50 rurban
2282 // encrypt password. fix strict logic.
2283 // both bugs reported by Mikhail Vladimirov
2285 // Revision 1.124 2005/01/30 23:11:00 rurban
2286 // allow self-creating passuser on login
2288 // Revision 1.123 2005/01/25 06:58:21 rurban
2291 // Revision 1.122 2005/01/08 22:51:56 rurban
2292 // remove deprecated workaround
2294 // Revision 1.121 2004/12/19 00:58:01 rurban
2295 // Enforce PASSWORD_LENGTH_MINIMUM in almost all PassUser checks,
2296 // Provide an errormessage if so. Just PersonalPage and BogoLogin not.
2297 // Simplify httpauth logout handling and set sessions for all methods.
2298 // fix main.php unknown index "x" getLevelDescription() warning.
2300 // Revision 1.120 2004/12/17 12:31:57 rurban
2301 // better logout, fake httpauth not yet
2303 // Revision 1.119 2004/11/21 11:59:17 rurban
2304 // remove final \n to be ob_cache independent
2306 // Revision 1.118 2004/11/19 19:22:03 rurban
2307 // ModeratePage part1: change status
2309 // Revision 1.117 2004/11/10 15:29:21 rurban
2310 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
2311 // * ACCESS_LOG_SQL: fix cause request not yet initialized
2312 // * WikiDB: moved SQL specific methods upwards
2313 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
2314 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
2316 // Revision 1.116 2004/11/05 21:03:27 rurban
2317 // new DEBUG flag: _DEBUG_LOGIN (64)
2318 // verbose login debug-msg (settings and reason for failure)
2320 // Revision 1.115 2004/11/05 20:53:35 rurban
2321 // login cleanup: better debug msg on failing login,
2322 // checked password less immediate login (bogo or anon),
2323 // checked olduser pref session error,
2324 // better PersonalPage without password warning on minimal password length=0
2325 // (which is default now)
2327 // Revision 1.114 2004/11/05 16:15:57 rurban
2328 // forgot the BogoLogin inclusion with the latest rewrite
2330 // Revision 1.113 2004/11/03 17:13:49 rurban
2331 // make it easier to disable EmailVerification
2334 // Revision 1.112 2004/11/01 10:43:57 rurban
2335 // seperate PassUser methods into seperate dir (memory usage)
2336 // fix WikiUser (old) overlarge data session
2337 // remove wikidb arg from various page class methods, use global ->_dbi instead
2340 // Revision 1.111 2004/10/21 21:03:50 rurban
2341 // isAdmin must be signed and authenticated
2342 // comment out unused sections (memory)
2344 // Revision 1.110 2004/10/14 19:19:33 rurban
2345 // loadsave: check if the dumped file will be accessible from outside.
2346 // and some other minor fixes. (cvsclient native not yet ready)
2348 // Revision 1.109 2004/10/07 16:08:58 rurban
2349 // fixed broken FileUser session handling.
2350 // thanks to Arnaud Fontaine for detecting this.
2351 // enable file user Administrator membership.
2353 // Revision 1.108 2004/10/05 17:00:04 rurban
2354 // support paging for simple lists
2355 // fix RatingDb sql backend.
2356 // remove pages from AllPages (this is ListPages then)
2358 // Revision 1.107 2004/10/04 23:42:15 rurban
2359 // HttpAuth admin group logic. removed old logs
2361 // Revision 1.106 2004/07/01 08:49:38 rurban
2362 // obsolete php5-patch.php: minor php5 login problem though
2364 // Revision 1.105 2004/06/29 06:48:03 rurban
2365 // Improve LDAP auth and GROUP_LDAP membership:
2366 // no error message on false password,
2367 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2368 // fixed two group queries (this -> user)
2369 // stdlib: ConvertOldMarkup still flawed
2371 // Revision 1.104 2004/06/28 15:39:37 rurban
2372 // fixed endless recursion in WikiGroup: isAdmin()
2374 // Revision 1.103 2004/06/28 15:01:07 rurban
2375 // fixed LDAP_SET_OPTION handling, LDAP error on connection problem
2377 // Revision 1.102 2004/06/27 10:23:48 rurban
2378 // typo detected by Philippe Vanhaesendonck
2380 // Revision 1.101 2004/06/25 14:29:19 rurban
2381 // WikiGroup refactoring:
2382 // global group attached to user, code for not_current user.
2383 // improved helpers for special groups (avoid double invocations)
2384 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2385 // fixed a XHTML validation error on userprefs.tmpl
2387 // Revision 1.100 2004/06/21 06:29:35 rurban
2388 // formatting: linewrap only
2390 // Revision 1.99 2004/06/20 15:30:05 rurban
2391 // get_class case-sensitivity issues
2393 // Revision 1.98 2004/06/16 21:24:31 rurban
2394 // do not display no-connect warning: #2662
2396 // Revision 1.97 2004/06/16 13:21:16 rurban
2397 // stabilize on failing ldap queries or bind
2399 // Revision 1.96 2004/06/16 12:42:06 rurban
2400 // fix homepage prefs
2402 // Revision 1.95 2004/06/16 10:38:58 rurban
2403 // Disallow refernces in calls if the declaration is a reference
2404 // ("allow_call_time_pass_reference clean").
2405 // PhpWiki is now allow_call_time_pass_reference = Off clean,
2406 // but several external libraries may not.
2407 // In detail these libs look to be affected (not tested):
2411 // Revision 1.94 2004/06/15 10:40:35 rurban
2412 // minor WikiGroup cleanup: no request param, start of current user independency
2414 // Revision 1.93 2004/06/15 09:15:52 rurban
2415 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
2416 // fix encrypted usage, actually store and retrieve them from db
2417 // fix bogologin with passwd set.
2418 // fix php crashes with call-time pass-by-reference (references wrongly used
2419 // in declaration AND call). This affected mainly Apache2 and IIS.
2420 // (Thanks to John Cole to detect this!)
2422 // Revision 1.92 2004/06/14 11:31:36 rurban
2423 // renamed global $Theme to $WikiTheme (gforge nameclash)
2424 // inherit PageList default options from PageList
2425 // default sortby=pagename
2426 // use options in PageList_Selectable (limit, sortby, ...)
2427 // added action revert, with button at action=diff
2428 // added option regex to WikiAdminSearchReplace
2430 // Revision 1.91 2004/06/08 14:57:43 rurban
2431 // stupid ldap bug detected by John Cole
2433 // Revision 1.90 2004/06/08 09:31:15 rurban
2434 // fixed typo detected by lucidcarbon (line 1663 assertion)
2436 // Revision 1.89 2004/06/06 16:58:51 rurban
2437 // added more required ActionPages for foreign languages
2438 // install now english ActionPages if no localized are found. (again)
2439 // fixed default anon user level to be 0, instead of -1
2440 // (wrong "required administrator to view this page"...)
2442 // Revision 1.88 2004/06/04 20:32:53 rurban
2443 // Several locale related improvements suggested by Pierrick Meignen
2444 // LDAP fix by John Cole
2445 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2447 // Revision 1.87 2004/06/04 12:40:21 rurban
2448 // Restrict valid usernames to prevent from attacks against external auth or compromise
2450 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
2451 // Fxied more warnings
2453 // Revision 1.86 2004/06/03 18:06:29 rurban
2454 // fix file locking issues (only needed on write)
2455 // fixed immediate LANG and THEME in-session updates if not stored in prefs
2456 // advanced editpage toolbars (search & replace broken)
2458 // Revision 1.85 2004/06/03 12:46:03 rurban
2459 // fix signout, level must be 0 not -1
2461 // Revision 1.84 2004/06/03 12:36:03 rurban
2462 // fix eval warning on signin
2464 // Revision 1.83 2004/06/03 10:18:19 rurban
2465 // fix User locking issues, new config ENABLE_PAGEPERM
2467 // Revision 1.82 2004/06/03 09:39:51 rurban
2468 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
2470 // Revision 1.81 2004/06/02 18:01:45 rurban
2471 // init global FileFinder to add proper include paths at startup
2472 // adds PHPWIKI_DIR if started from another dir, lib/pear also
2473 // fix slashify for Windows
2474 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
2476 // Revision 1.80 2004/06/02 14:20:27 rurban
2477 // fix adodb DbPassUser login
2479 // Revision 1.79 2004/06/01 15:27:59 rurban
2480 // AdminUser only ADMIN_USER not member of Administrators
2481 // some RateIt improvements by dfrankow
2482 // edit_toolbar buttons
2484 // Revision 1.78 2004/05/27 17:49:06 rurban
2485 // renamed DB_Session to DbSession (in CVS also)
2486 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
2487 // remove leading slash in error message
2488 // added force_unlock parameter to File_Passwd (no return on stale locks)
2489 // fixed adodb session AffectedRows
2490 // added FileFinder helpers to unify local filenames and DATA_PATH names
2491 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
2493 // Revision 1.77 2004/05/18 14:49:51 rurban
2494 // Simplified strings for easier translation
2496 // Revision 1.76 2004/05/18 13:30:04 rurban
2497 // prevent from endless loop with oldstyle warnings
2499 // Revision 1.75 2004/05/16 22:07:35 rurban
2500 // check more config-default and predefined constants
2501 // various PagePerm fixes:
2502 // fix default PagePerms, esp. edit and view for Bogo and Password users
2503 // implemented Creator and Owner
2504 // BOGOUSERS renamed to BOGOUSER
2505 // fixed syntax errors in signin.tmpl
2507 // Revision 1.74 2004/05/15 19:48:33 rurban
2508 // fix some too loose PagePerms for signed, but not authenticated users
2509 // (admin, owner, creator)
2510 // no double login page header, better login msg.
2511 // moved action_pdf to lib/pdf.php
2513 // Revision 1.73 2004/05/15 18:31:01 rurban
2514 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
2516 // Revision 1.72 2004/05/12 10:49:55 rurban
2517 // require_once fix for those libs which are loaded before FileFinder and
2518 // its automatic include_path fix, and where require_once doesn't grok
2519 // dirname(__FILE__) != './lib'
2520 // upgrade fix with PearDB
2521 // navbar.tmpl: remove spaces for IE button alignment
2523 // Revision 1.71 2004/05/10 12:34:47 rurban
2524 // stabilize DbAuthParam statement pre-prozessor:
2525 // try old-style and new-style (double-)quoting
2526 // reject unknown $variables
2527 // use ->prepare() for all calls (again)
2529 // Revision 1.70 2004/05/06 19:26:16 rurban
2530 // improve stability, trying to find the InlineParser endless loop on sf.net
2532 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
2534 // Revision 1.69 2004/05/06 13:56:40 rurban
2535 // Enable the Administrators group, and add the WIKIPAGE group default root page.
2537 // Revision 1.68 2004/05/05 13:37:54 rurban
2538 // Support to remove all UserPreferences
2540 // Revision 1.66 2004/05/03 21:44:24 rurban
2541 // fixed sf,net bug #947264: LDAP options are constants, not strings!
2543 // Revision 1.65 2004/05/03 13:16:47 rurban
2544 // fixed UserPreferences update, esp for boolean and int
2546 // Revision 1.64 2004/05/02 15:10:06 rurban
2547 // new finally reliable way to detect if /index.php is called directly
2548 // and if to include lib/main.php
2549 // new global AllActionPages
2550 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
2551 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
2552 // PageGroupTestOne => subpages
2553 // renamed PhpWikiRss to PhpWikiRecentChanges
2554 // more docs, default configs, ...
2556 // Revision 1.63 2004/05/01 15:59:29 rurban
2557 // more php-4.0.6 compatibility: superglobals
2559 // Revision 1.62 2004/04/29 18:31:24 rurban
2560 // Prevent from warning where no db pref was previously stored.
2562 // Revision 1.61 2004/04/29 17:18:19 zorloc
2563 // Fixes permission failure issues. With PagePermissions and Disabled Actions when user did not have permission WIKIAUTH_FORBIDDEN was returned. In WikiUser this was ok because WIKIAUTH_FORBIDDEN had a value of 11 -- thus no user could perform that action. But WikiUserNew has a WIKIAUTH_FORBIDDEN value of -1 -- thus a user without sufficent permission to do anything. The solution is a new high value permission level (WIKIAUTH_UNOBTAINABLE) to be the default level for access failure.
2565 // Revision 1.60 2004/04/27 18:20:54 rurban
2566 // sf.net patch #940359 by rassie
2568 // Revision 1.59 2004/04/26 12:35:21 rurban
2569 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
2570 // File_Passwd is already loaded
2572 // Revision 1.58 2004/04/20 17:08:28 rurban
2573 // Some IniConfig fixes: prepend our private lib/pear dir
2574 // switch from " to ' in the auth statements
2575 // use error handling.
2576 // WikiUserNew changes for the new "'$variable'" syntax
2577 // in the statements
2578 // TODO: optimization to put config vars into the session.
2580 // Revision 1.57 2004/04/19 18:27:45 rurban
2581 // Prevent from some PHP5 warnings (ref args, no :: object init)
2582 // php5 runs now through, just one wrong XmlElement object init missing
2583 // Removed unneccesary UpgradeUser lines
2584 // Changed WikiLink to omit version if current (RecentChanges)
2586 // Revision 1.56 2004/04/19 09:13:24 rurban
2587 // new pref: googleLink
2589 // Revision 1.54 2004/04/18 00:24:45 rurban
2590 // re-use our simple prepare: just for table prefix warnings
2592 // Revision 1.53 2004/04/12 18:29:15 rurban
2593 // exp. Session auth for already authenticated users from another app
2595 // Revision 1.52 2004/04/12 13:04:50 rurban
2596 // added auth_create: self-registering Db users
2598 // removed rating recommendations
2599 // ziplib reformatting
2601 // Revision 1.51 2004/04/11 10:42:02 rurban
2602 // pgsrc/CreatePagePlugin
2604 // Revision 1.50 2004/04/10 05:34:35 rurban
2607 // Revision 1.49 2004/04/07 23:13:18 rurban
2608 // fixed pear/File_Passwd for Windows
2609 // fixed FilePassUser sessions (filehandle revive) and password update
2611 // Revision 1.48 2004/04/06 20:00:10 rurban
2612 // Cleanup of special PageList column types
2613 // Added support of plugin and theme specific Pagelist Types
2614 // Added support for theme specific UserPreferences
2615 // Added session support for ip-based throttling
2616 // sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
2617 // Enhanced postgres schema
2618 // Added DB_Session_dba support
2620 // Revision 1.47 2004/04/02 15:06:55 rurban
2621 // fixed a nasty ADODB_mysql session update bug
2622 // improved UserPreferences layout (tabled hints)
2623 // fixed UserPreferences auth handling
2624 // improved auth stability
2625 // improved old cookie handling: fixed deletion of old cookies with paths
2627 // Revision 1.46 2004/04/01 06:29:51 rurban
2629 // RateIt also for ADODB
2635 // c-basic-offset: 4
2636 // c-hanging-comment-ender-p: nil
2637 // indent-tabs-mode: nil