3 /* Copyright (C) 2004,2005,2006,2007,2009 $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.
97 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
98 define('WIKIAUTH_ANON', 0); // Not signed in.
99 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
100 define('WIKIAUTH_USER', 2); // Bogo user with a password.
101 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
102 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
104 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
105 //if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
106 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
107 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
108 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
110 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
111 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
112 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
114 define('TIMEOFFSET_MIN_HOURS', -26);
115 define('TIMEOFFSET_MAX_HOURS', 26);
116 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
118 /* EMAIL VERIFICATION
119 * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
120 * Provide some overrides here.
121 * ( username @ ) domain => mail-domain
123 $EMailHosts = array('avl.com' => 'mail.avl.com');
126 * There are be the following constants in config/config.ini to
127 * establish login parameters:
129 * ALLOW_ANON_USER default true
130 * ALLOW_ANON_EDIT default true
131 * ALLOW_BOGO_LOGIN default true
132 * ALLOW_USER_PASSWORDS default true
133 * PASSWORD_LENGTH_MINIMUM default 0
135 * To require user passwords for editing:
136 * ALLOW_ANON_USER = true
137 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
138 * ALLOW_BOGO_LOGIN = false
139 * ALLOW_USER_PASSWORDS = true
141 * To establish a COMPLETELY private wiki, such as an internal
143 * ALLOW_ANON_USER = false
144 * (and probably require user passwords as described above). In this
145 * case the user will be prompted to login immediately upon accessing
148 * There are other possible combinations, but the typical wiki (such
149 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
154 // The last object in the row is the bad guy...
155 if (!is_array($USER_AUTH_ORDER))
156 $USER_AUTH_ORDER = array("Forbidden");
158 $USER_AUTH_ORDER[] = "Forbidden";
160 // Local convenience functions.
161 function _isAnonUserAllowed() {
162 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
164 function _isBogoUserAllowed() {
165 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
167 function _isUserPasswordsAllowed() {
168 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
171 // Possibly upgrade userobject functions.
172 function _determineAdminUserOrOtherUser($UserName) {
173 // Sanity check. User name is a condition of the definition of the
174 // _AdminUser, _BogoUser and _passuser.
176 return $GLOBALS['ForbiddenUser'];
178 //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
179 //$group = &WikiGroup::getGroup($GLOBALS['request']);
180 if ($UserName == ADMIN_USER)
181 return new _AdminUser($UserName);
182 /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
183 return _determineBogoUserOrPassUser($UserName);
187 return _determineBogoUserOrPassUser($UserName);
190 function _determineBogoUserOrPassUser($UserName) {
191 global $ForbiddenUser;
193 // Sanity check. User name is a condition of the definition of
194 // _BogoUser and _PassUser.
196 return $ForbiddenUser;
198 // Check for password and possibly upgrade user object.
199 // $_BogoUser = new _BogoUser($UserName);
200 if (_isBogoUserAllowed() and isWikiWord($UserName)) {
201 include_once("lib/WikiUser/BogoLogin.php");
202 $_BogoUser = new _BogoLoginPassUser($UserName);
203 if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
206 if (_isUserPasswordsAllowed()) {
207 // PassUsers override BogoUsers if a password is stored
208 if (isset($_BogoUser) and isset($_BogoUser->_prefs)
209 and $_BogoUser->_prefs->get('passwd'))
210 return new _PassUser($UserName, $_BogoUser->_prefs);
212 $_PassUser = new _PassUser($UserName,
213 isset($_BogoUser) ? $_BogoUser->_prefs : false);
214 if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
215 if (isset($GLOBALS['request']->_user_class))
216 $class = $GLOBALS['request']->_user_class;
217 elseif (strtolower(get_class($_PassUser)) == "_passuser")
218 $class = $_PassUser->nextClass();
220 $class = get_class($_PassUser);
221 if ($user = new $class($UserName, $_PassUser->_prefs)) {
229 // No Bogo- or PassUser exists, or
230 // passwords are not allowed, and bogo is disallowed too.
231 // (Only the admin can sign in).
232 return $ForbiddenUser;
236 * Primary WikiUser function, called by lib/main.php.
238 * This determines the user's type and returns an appropriate user
239 * object. lib/main.php then querys the resultant object for password
240 * validity as necessary.
242 * If an _AnonUser object is returned, the user may only browse pages
243 * (and save prefs in a cookie).
245 * To disable access but provide prefs the global $ForbiddenUser class
246 * is returned. (was previously false)
249 function WikiUser ($UserName = '') {
250 global $ForbiddenUser, $HTTP_SESSION_VARS;
252 //Maybe: Check sessionvar for username & save username into
253 //sessionvar (may be more appropriate to do this in lib/main.php).
255 $ForbiddenUser = new _ForbiddenUser($UserName);
256 // Found a user name.
257 return _determineAdminUserOrOtherUser($UserName);
259 elseif (!empty($HTTP_SESSION_VARS['userid'])) {
260 // Found a user name.
261 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
262 return _determineAdminUserOrOtherUser($_SESSION['userid']);
265 // Check for autologin pref in cookie and possibly upgrade
266 // user object to another type.
267 $_AnonUser = new _AnonUser();
268 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
269 // Found a user name.
270 $ForbiddenUser = new _ForbiddenUser($UserName);
271 return _determineAdminUserOrOtherUser($UserName);
274 $ForbiddenUser = new _ForbiddenUser();
275 if (_isAnonUserAllowed())
277 return $ForbiddenUser; // User must sign in to browse pages.
279 return $ForbiddenUser; // User must sign in with a password.
282 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
283 . "Unexpectedly, an appropriate user class could not be determined.");
284 return $ForbiddenUser; // Failsafe.
289 * WikiUser.php use the name 'WikiUser'
291 function WikiUserClassname() {
297 * Upgrade olduser by copying properties from user to olduser.
298 * We are not sure yet, for which php's a simple $this = $user works reliably,
299 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
300 * that's why try it the hard way.
302 function UpgradeUser ($user, $newuser) {
303 if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) {
304 // populate the upgraded class $newuser with the values from the current user object
305 //only _auth_level, _current_method, _current_index,
306 if (!empty($user->_level) and
307 $user->_level > $newuser->_level)
308 $newuser->_level = $user->_level;
309 if (!empty($user->_current_index) and
310 $user->_current_index > $newuser->_current_index) {
311 $newuser->_current_index = $user->_current_index;
312 $newuser->_current_method = $user->_current_method;
314 if (!empty($user->_authmethod))
315 $newuser->_authmethod = $user->_authmethod;
316 $GLOBALS['request']->_user_class = get_class($newuser);
318 foreach (get_object_vars($user) as $k => $v) {
319 if (!empty($v)) $olduser->$k = $v;
322 $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
323 //$GLOBALS['request']->_user = $olduser;
331 * Probably not needed, since we use the various user objects methods so far.
332 * Anyway, here it is, looping through all available objects.
334 function UserExists ($UserName) {
336 if (!($user = $request->getUser()))
337 $user = WikiUser($UserName);
340 if ($user->userExists($UserName)) {
341 $request->_user = $user;
344 if (isa($user,'_BogoUser'))
345 $user = new _PassUser($UserName,$user->_prefs);
346 $class = $user->nextClass();
347 if ($user = new $class($UserName, $user->_prefs)) {
348 return $user->userExists($UserName);
350 $request->_user = $GLOBALS['ForbiddenUser'];
354 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
357 * Base WikiUser class.
362 var $_level = WIKIAUTH_ANON;
364 var $_HomePagehandle = false;
367 function _WikiUser($UserName='', $prefs=false) {
369 $this->_userid = $UserName;
370 $this->_HomePagehandle = false;
372 $this->hasHomePage();
374 if (empty($this->_prefs)) {
375 if ($prefs) $this->_prefs = $prefs;
376 else $this->getPreferences();
380 function UserName() {
381 if (!empty($this->_userid))
382 return $this->_userid;
385 function getPreferences() {
386 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
387 . "New subclasses of _WikiUser must override this function.");
391 function setPreferences($prefs, $id_only) {
392 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
394 . "New subclasses of _WikiUser must override this function.");
398 function userExists() {
399 return $this->hasHomePage();
402 function checkPass($submitted_password) {
403 // By definition, an undefined user class cannot sign in.
404 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
406 . "New subclasses of _WikiUser must override this function.");
410 // returns page_handle to user's home page or false if none
411 function hasHomePage() {
412 if ($this->_userid) {
413 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
414 return $this->_HomePagehandle->exists();
417 // check db again (maybe someone else created it since
420 $this->_HomePagehandle = $request->getPage($this->_userid);
421 return $this->_HomePagehandle->exists();
429 function createHomePage() {
431 $versiondata = array('author' => ADMIN_USER);
432 $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.").
433 "\n{{Template/UserPage}}",
435 $request->_dbi->touch();
436 $this->_HomePagehandle = $request->getPage($this->_userid);
439 // innocent helper: case-insensitive position in _auth_methods
440 function array_position ($string, $array) {
441 $string = strtolower($string);
442 for ($found = 0; $found < count($array); $found++) {
443 if (strtolower($array[$found]) == $string)
449 function nextAuthMethodIndex() {
450 if (empty($this->_auth_methods))
451 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
452 if (empty($this->_current_index)) {
453 if (strtolower(get_class($this)) != '_passuser') {
454 $this->_current_method = substr(get_class($this),1,-8);
455 $this->_current_index = $this->array_position($this->_current_method,
456 $this->_auth_methods);
458 $this->_current_index = -1;
461 $this->_current_index++;
462 if ($this->_current_index >= count($this->_auth_methods))
464 $this->_current_method = $this->_auth_methods[$this->_current_index];
465 return $this->_current_index;
468 function AuthMethod($index = false) {
469 return $this->_auth_methods[ $index === false
470 ? count($this->_auth_methods)-1
474 // upgrade the user object
475 function nextClass() {
476 $method = $this->AuthMethod($this->nextAuthMethodIndex());
477 include_once("lib/WikiUser/$method.php");
478 return "_".$method."PassUser";
481 //Fixme: for _HttpAuthPassUser
482 function PrintLoginForm (&$request, $args, $fail_message = false,
483 $seperate_page = false) {
484 include_once('lib/Template.php');
485 // Call update_locale in case the system's default language is not 'en'.
486 // (We have no user pref for lang at this point yet, no one is logged in.)
487 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
488 update_locale(DEFAULT_LANGUAGE);
489 $userid = $this->_userid;
491 extract($args); // fixme
493 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
495 $pagename = $request->getArg('pagename');
497 $login = Template('login',
498 compact('pagename', 'userid', 'require_level',
499 'fail_message', 'pass_required', 'nocache'));
500 // check if the html template was already processed
501 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
502 if ($seperate_page) {
503 $page = $request->getPage($pagename);
504 $revision = $page->getCurrentRevision();
505 return GeneratePage($login,_("Sign In"), $revision);
507 return $login->printExpansion();
511 /** Signed in but not password checked or empty password.
513 function isSignedIn() {
514 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
517 /** This is password checked for sure.
519 function isAuthenticated() {
520 //return isa($this,'_PassUser');
521 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
522 return $this->_level >= WIKIAUTH_BOGO;
525 function isAdmin () {
527 if ($this->_level == WIKIAUTH_ADMIN) return true;
528 if (!$this->isSignedIn()) return false;
529 if (!$this->isAuthenticated()) return false;
531 if (!$group) $group = &$GLOBALS['request']->getGroup();
532 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
535 /** Name or IP for a signed user. UserName could come from a cookie e.g.
538 return ( $this->UserName()
540 : $GLOBALS['request']->get('REMOTE_ADDR') );
543 /** Name for an authenticated user. No IP here.
545 function getAuthenticatedId() {
546 return ( $this->isAuthenticated()
548 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
551 function hasAuthority ($require_level) {
552 return $this->_level >= $require_level;
555 /* This is quite restrictive and not according the login description online.
556 Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
557 The backends may loosen or tighten this.
559 function isValidName ($userid = false) {
560 if (!$userid) $userid = $this->_userid;
561 if (!$userid) return false;
562 if (defined('GFORGE') and GFORGE) {
565 return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
569 * Called on an auth_args POST request, such as login, logout or signin.
570 * TODO: Check BogoLogin users with empty password. (self-signed users)
572 function AuthCheck ($postargs) {
573 // Normalize args, and extract.
574 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
576 foreach ($keys as $key)
577 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
579 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
581 if ($logout) { // Log out
582 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
584 $zone_offset = Request_AccessLogEntry::_zone_offset();
585 $ncsa_time = date("d/M/Y:H:i:s", time());
586 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
587 (string) $request->get('REMOTE_HOST'),
588 (string) $request->_user->_userid,
589 $ncsa_time, $zone_offset,
590 "logout ".get_class($request->_user),
592 (string) $request->get('HTTP_REFERER'),
593 (string) $request->get('HTTP_USER_AGENT')
595 if (($fp = fopen(LOGIN_LOG, "a"))) {
597 fputs($fp, "$entry\n");
600 //error_log("$entry\n", 3, LOGIN_LOG);
602 if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
603 $GLOBALS['request']->_user->logout();
605 $user = new _AnonUser();
607 $user->_level = WIKIAUTH_ANON;
610 return false; // User hit cancel button.
611 elseif (!$login && !$userid)
612 return false; // Nothing to do?
614 if (!$this->isValidName($userid))
615 return _("Invalid username.");;
617 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
619 if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
621 $zone_offset = Request_AccessLogEntry::_zone_offset();
622 $ncsa_time = date("d/M/Y:H:i:s", time());
623 $manglepasswd = $passwd;
624 for ($i=0; $i<strlen($manglepasswd); $i++) {
625 $c = substr($manglepasswd,$i,1);
626 if (ord($c) < 32) $manglepasswd[$i] = "<";
627 elseif ($c == '*') $manglepasswd[$i] = "*";
628 elseif ($c == '?') $manglepasswd[$i] = "?";
629 elseif ($c == '(') $manglepasswd[$i] = "(";
630 elseif ($c == ')') $manglepasswd[$i] = ")";
631 elseif ($c == "\\") $manglepasswd[$i] = "\\";
632 elseif (ord($c) < 127) $manglepasswd[$i] = "x";
633 elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
635 if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
636 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
637 $request->get('REMOTE_HOST'),
638 (string) $request->_user->_userid,
639 $ncsa_time, $zone_offset,
640 "login $userid/$manglepasswd => $authlevel ".get_class($request->_user),
641 $authlevel > 0 ? "200" : "403",
642 (string) $request->get('HTTP_REFERER'),
643 (string) $request->get('HTTP_USER_AGENT')
645 if (($fp = fopen(LOGIN_LOG, "a"))) {
647 fputs($fp, "$entry\n");
650 //error_log("$entry\n", 3, LOGIN_LOG);
653 if ($authlevel <= 0) { // anon or forbidden
655 return _("Invalid password.");
657 return _("Invalid password or userid.");
658 } elseif ($authlevel < $require_level) { // auth ok, but not enough
659 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
662 $class = "_" . $this->_current_method . "PassUser";
663 include_once("lib/WikiUser/".$this->_current_method.".php");
664 $user = new $class($userid,$this->_prefs);
665 if (!check_php_version(5))
666 eval("\$this = \$user;");
667 // /*PHP5 patch*/$this = $user;
668 $this->_level = $authlevel;
671 $this->_userid = $userid;
672 $this->_level = $authlevel;
673 return _("Insufficient permissions.");
677 //$user = $GLOBALS['request']->_user;
678 if (!empty($this->_current_method) and
679 strtolower(get_class($this)) == '_passuser')
682 $class = "_" . $this->_current_method . "PassUser";
683 include_once("lib/WikiUser/".$this->_current_method.".php");
684 $user = new $class($userid, $this->_prefs);
685 if (!check_php_version(5))
686 eval("\$this = \$user;");
687 // /*PHP5 patch*/$this = $user;
688 $user->_level = $authlevel;
691 $this->_userid = $userid;
692 $this->_level = $authlevel;
699 * Not authenticated in user, but he may be signed in. Basicly with view access only.
700 * prefs are stored in cookies, but only the userid.
705 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
707 /** Anon only gets to load and save prefs in a cookie, that's it.
709 function getPreferences() {
712 if (empty($this->_prefs))
713 $this->_prefs = new UserPreferences;
714 $UserName = $this->UserName();
716 // Try to read deprecated 1.3.x style cookies
717 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
718 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
719 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
721 . sprintf("%s='%s'", WIKI_NAME, $cookie)
723 . _("Default preferences will be used."),
727 * Only set if it matches the UserName who is
728 * signing in or if this really is an Anon login (no
729 * username). (Remember, _BogoUser and higher inherit this
732 if (! $UserName || $UserName == @$unboxedcookie['userid']) {
733 $updated = $this->_prefs->updatePrefs($unboxedcookie);
734 //$this->_prefs = new UserPreferences($unboxedcookie);
735 $UserName = @$unboxedcookie['userid'];
736 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
737 $this->_userid = $UserName;
741 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
743 $request->deleteCookieVar(WIKI_NAME);
745 // Try to read deprecated 1.3.4 style cookies
746 if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
747 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
748 if (! $UserName || $UserName == $unboxedcookie['userid']) {
749 $updated = $this->_prefs->updatePrefs($unboxedcookie);
750 //$this->_prefs = new UserPreferences($unboxedcookie);
751 $UserName = $unboxedcookie['userid'];
752 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
753 $this->_userid = $UserName;
758 $request->deleteCookieVar("WIKI_PREF2");
762 // Try reading userid from old PhpWiki cookie formats:
763 if ($cookie = $request->cookies->get_old(getCookieName())) {
764 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
766 elseif (is_array($cookie) and !empty($cookie['userid']))
767 $UserName = $cookie['userid'];
769 if (! $UserName and !headers_sent())
770 $request->deleteCookieVar(getCookieName());
772 $this->_userid = $UserName;
775 // initializeTheme() needs at least an empty object
777 if (empty($this->_prefs))
778 $this->_prefs = new UserPreferences;
780 return $this->_prefs;
783 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
785 * Allow for multiple wikis in same domain. Encode only the
786 * _prefs array of the UserPreference object. Ideally the
787 * prefs array should just be imploded into a single string or
788 * something so it is completely human readable by the end
789 * user. In that case stricter error checking will be needed
790 * when loading the cookie.
792 function setPreferences($prefs, $id_only=false) {
793 if (!is_object($prefs)) {
794 if (is_object($this->_prefs)) {
795 $updated = $this->_prefs->updatePrefs($prefs);
796 $prefs =& $this->_prefs;
798 // update the prefs values from scratch. This could leed to unnecessary
799 // side-effects: duplicate emailVerified, ...
800 $this->_prefs = new UserPreferences($prefs);
804 if (!isset($this->_prefs))
805 $this->_prefs =& $prefs;
807 $updated = $this->_prefs->isChanged($prefs);
810 if ($id_only and !headers_sent()) {
812 // new 1.3.8 policy: no array cookies, only plain userid string as in
813 // the pre 1.3.x versions.
814 // prefs should be stored besides the session in the homepagehandle or in a db.
815 $request->setCookieVar(getCookieName(), $this->_userid,
816 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
817 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
818 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
821 if (is_object($prefs)) {
822 $packed = $prefs->store();
823 $unpacked = $prefs->unpack($packed);
824 if (count($unpacked)) {
825 foreach (array('_method','_select','_update','_insert') as $param) {
826 if (!empty($this->_prefs->{$param}))
827 $prefs->{$param} = $this->_prefs->{$param};
829 $this->_prefs = $prefs;
835 function userExists() {
839 function checkPass($submitted_password) {
841 // this might happen on a old-style signin button.
843 // By definition, the _AnonUser does not HAVE a password
844 // (compared to _BogoUser, who has an EMPTY password).
845 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
846 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
847 . "New subclasses of _WikiUser must override this function.");
854 * Helper class to finish the PassUser auth loop.
855 * This is added automatically to USER_AUTH_ORDER.
860 var $_level = WIKIAUTH_FORBIDDEN;
862 function checkPass($submitted_password) {
863 return WIKIAUTH_FORBIDDEN;
866 function userExists() {
867 if ($this->_HomePagehandle) return true;
873 * Do NOT extend _BogoUser to other classes, for checkPass()
874 * security. (In case of defects in code logic of the new class!)
875 * The intermediate step between anon and passuser.
876 * We also have the _BogoLoginPassUser class with stricter
877 * password checking, which fits into the auth loop.
878 * Note: This class is not called anymore by WikiUser()
883 function userExists() {
884 if (isWikiWord($this->_userid)) {
885 $this->_level = WIKIAUTH_BOGO;
888 $this->_level = WIKIAUTH_ANON;
893 function checkPass($submitted_password) {
894 // By definition, BogoUser has an empty password.
896 return $this->_level;
903 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
905 * The classes for all subsequent auth methods extend from this class.
906 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
907 * the three auth method policies first-only, strict and stacked
908 * and the two methods for prefs: homepage or database,
909 * if $DBAuthParams['pref_select'] is defined.
911 * Default is PersonalPage auth and prefs.
913 * @author: Reini Urban
917 var $_auth_dbi, $_prefs;
918 var $_current_method, $_current_index;
920 // check and prepare the auth and pref methods only once
921 function _PassUser($UserName='', $prefs=false) {
922 //global $DBAuthParams, $DBParams;
924 /*if (!$this->isValidName($UserName))
926 $this->_userid = $UserName;
927 if ($this->hasHomePage())
928 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
930 $this->_authmethod = substr(get_class($this),1,-8);
931 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
933 // Check the configured Prefs methods
934 $dbi = $this->getAuthDbh();
935 $dbh = $GLOBALS['request']->getDbh();
938 and !isset($this->_prefs->_select)
939 and $dbh->getAuthParam('pref_select'))
941 if (!$this->_prefs) {
942 $this->_prefs = new UserPreferences();
945 $this->_prefs->_method = $dbh->getParam('dbtype');
946 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
948 if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
949 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
950 array("userid", "pref_blob"));
953 if (!$this->_prefs) {
954 $this->_prefs = new UserPreferences();
957 $this->_prefs->_method = 'HomePage';
960 if (! $this->_prefs or isset($need_pref) ) {
961 if ($prefs) $this->_prefs = $prefs;
962 else $this->getPreferences();
965 // Upgrade to the next parent _PassUser class. Avoid recursion.
966 if ( strtolower(get_class($this)) === '_passuser' ) {
967 //auth policy: Check the order of the configured auth methods
968 // 1. first-only: Upgrade the class here in the constructor
969 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
970 /// in the previous PhpWiki releases (slow)
971 // 3. strict: upgrade the class after checking the user existance in userExists()
972 // 4. stacked: upgrade the class after the password verification in checkPass()
973 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
974 //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
975 if (defined('USER_AUTH_POLICY')) {
976 // policy 1: only pre-define one method for all users
977 if (USER_AUTH_POLICY === 'first-only') {
978 $class = $this->nextClass();
979 return new $class($UserName,$this->_prefs);
981 // Use the default behaviour from the previous versions:
982 elseif (USER_AUTH_POLICY === 'old') {
983 // Default: try to be smart
984 // On php5 we can directly return and upgrade the Object,
985 // before we have to upgrade it manually.
986 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
987 include_once("lib/WikiUser/HttpAuth.php");
988 if (check_php_version(5))
989 return new _HttpAuthPassUser($UserName,$this->_prefs);
991 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
992 eval("\$this = \$user;");
993 // /*PHP5 patch*/$this = $user;
996 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
997 $dbh->getAuthParam('auth_check') and
998 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
999 if (check_php_version(5))
1000 return new _DbPassUser($UserName,$this->_prefs);
1002 $user = new _DbPassUser($UserName,$this->_prefs);
1003 eval("\$this = \$user;");
1004 // /*PHP5 patch*/$this = $user;
1007 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1008 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
1009 function_exists('ldap_connect')) {
1010 include_once("lib/WikiUser/LDAP.php");
1011 if (check_php_version(5))
1012 return new _LDAPPassUser($UserName,$this->_prefs);
1014 $user = new _LDAPPassUser($UserName,$this->_prefs);
1015 eval("\$this = \$user;");
1016 // /*PHP5 patch*/$this = $user;
1019 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1020 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
1021 include_once("lib/WikiUser/IMAP.php");
1022 if (check_php_version(5))
1023 return new _IMAPPassUser($UserName,$this->_prefs);
1025 $user = new _IMAPPassUser($UserName,$this->_prefs);
1026 eval("\$this = \$user;");
1027 // /*PHP5 patch*/$this = $user;
1030 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1031 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
1032 include_once("lib/WikiUser/File.php");
1033 if (check_php_version(5))
1034 return new _FilePassUser($UserName, $this->_prefs);
1036 $user = new _FilePassUser($UserName, $this->_prefs);
1037 eval("\$this = \$user;");
1038 // /*PHP5 patch*/$this = $user;
1042 include_once("lib/WikiUser/PersonalPage.php");
1043 if (check_php_version(5))
1044 return new _PersonalPagePassUser($UserName,$this->_prefs);
1046 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
1047 eval("\$this = \$user;");
1048 // /*PHP5 patch*/$this = $user;
1054 // else use the page methods defined in _PassUser.
1060 function getAuthDbh () {
1061 global $request; //, $DBParams, $DBAuthParams;
1063 $dbh = $request->getDbh();
1064 // session restauration doesn't re-connect to the database automatically,
1065 // so dirty it here, to force a reconnect.
1066 if (isset($this->_auth_dbi)) {
1067 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1068 unset($this->_auth_dbi);
1069 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1070 unset($this->_auth_dbi);
1072 if (empty($this->_auth_dbi)) {
1073 if ($dbh->getParam('dbtype') != 'SQL'
1074 and $dbh->getParam('dbtype') != 'ADODB'
1075 and $dbh->getParam('dbtype') != 'PDO')
1077 if (empty($GLOBALS['DBAuthParams']))
1079 if (!$dbh->getAuthParam('auth_dsn')) {
1080 $dbh = $request->getDbh(); // use phpwiki database
1081 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1082 $dbh = $request->getDbh(); // same phpwiki database
1083 } else { // use another external database handle. needs PHP >= 4.1
1084 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1085 $local_params['dsn'] = $local_params['auth_dsn'];
1086 $dbh = WikiDB::open($local_params);
1088 $this->_auth_dbi =& $dbh->_backend->_dbh;
1090 return $this->_auth_dbi;
1093 function _normalize_stmt_var($var, $oldstyle = false) {
1094 static $valid_variables = array('userid','password','pref_blob','groupname');
1095 // old-style: "'$userid'"
1096 // new-style: '"\$userid"' or just "userid"
1097 $new = str_replace(array("'",'"','\$','$'),'',$var);
1098 if (!in_array($new, $valid_variables)) {
1099 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1102 return !$oldstyle ? "'$".$new."'" : '\$'.$new;
1105 // TODO: use it again for the auth and member tables
1106 // sprintfstyle vs prepare style: %s or ?
1107 // multiple vars should be executed via prepare(?,?)+execute,
1108 // single vars with execute(sprintf(quote(var)))
1109 // help with position independency
1110 function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) {
1112 $dbi = $request->getDbh();
1113 $this->getAuthDbh();
1114 // "'\$userid"' => %s
1115 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1116 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1118 if (is_array($variables)) {
1119 //$sprintfstyle = false;
1120 for ($i=0; $i < count($variables); $i++) {
1121 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1123 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1124 $variables[$i], $stmt), E_USER_WARNING);
1125 $variables[$i] = $var;
1126 if (!$var) $new[] = '';
1128 $s = "%" . ($i+1) . "s";
1129 $new[] = $sprintfstyle ? $s : "?";
1133 $var = $this->_normalize_stmt_var($variables, $oldstyle);
1135 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1136 $variables, $stmt), E_USER_WARNING);
1138 if (!$var) $new = '';
1139 else $new = $sprintfstyle ? '%s' : "?";
1141 $prefix = $dbi->getParam('prefix');
1142 // probably prefix table names if in same database
1143 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1144 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1146 if (!stristr($stmt, $prefix)) {
1148 $stmt = str_replace(array(" user "," pref "," member "),
1149 array(" ".$prefix."user ",
1150 " ".$prefix."pref ",
1151 " ".$prefix."member "), $stmt);
1152 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1153 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt",
1157 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1158 // Simple sprintf-style.
1159 $new_stmt = str_replace($variables, $new, $stmt);
1160 if ($new_stmt == $stmt) {
1162 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1163 $stmt), E_USER_WARNING);
1165 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1166 $stmt), E_USER_WARNING);
1167 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1173 function getPreferences() {
1174 if (!empty($this->_prefs->_method)) {
1175 if ($this->_prefs->_method == 'ADODB') {
1176 // FIXME: strange why this should be needed...
1177 include_once("lib/WikiUser/Db.php");
1178 include_once("lib/WikiUser/AdoDb.php");
1179 return _AdoDbPassUser::getPreferences();
1180 } elseif ($this->_prefs->_method == 'SQL') {
1181 include_once("lib/WikiUser/Db.php");
1182 include_once("lib/WikiUser/PearDb.php");
1183 return _PearDbPassUser::getPreferences();
1184 } elseif ($this->_prefs->_method == 'PDO') {
1185 include_once("lib/WikiUser/Db.php");
1186 include_once("lib/WikiUser/PdoDb.php");
1187 return _PdoDbPassUser::getPreferences();
1191 // We don't necessarily have to read the cookie first. Since
1192 // the user has a password, the prefs stored in the homepage
1193 // cannot be arbitrarily altered by other Bogo users.
1194 _AnonUser::getPreferences();
1195 // User may have deleted cookie, retrieve from his
1196 // PersonalPage if there is one.
1197 if (!empty($this->_HomePagehandle)) {
1198 if ($restored_from_page = $this->_prefs->retrieve
1199 ($this->_HomePagehandle->get('pref'))) {
1200 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1201 //$this->_prefs = new UserPreferences($restored_from_page);
1202 return $this->_prefs;
1205 return $this->_prefs;
1208 function setPreferences($prefs, $id_only=false) {
1209 if (!empty($this->_prefs->_method)) {
1210 if ($this->_prefs->_method == 'ADODB') {
1211 // FIXME: strange why this should be needed...
1212 include_once("lib/WikiUser/Db.php");
1213 include_once("lib/WikiUser/AdoDb.php");
1214 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1216 elseif ($this->_prefs->_method == 'SQL') {
1217 include_once("lib/WikiUser/Db.php");
1218 include_once("lib/WikiUser/PearDb.php");
1219 return _PearDbPassUser::setPreferences($prefs, $id_only);
1221 elseif ($this->_prefs->_method == 'PDO') {
1222 include_once("lib/WikiUser/Db.php");
1223 include_once("lib/WikiUser/PdoDb.php");
1224 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1227 if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1228 // Encode only the _prefs array of the UserPreference object
1229 // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1230 if (empty($this->_HomePagehandle)) {
1231 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1233 if (! $this->_HomePagehandle->exists() ) {
1234 $this->createHomePage();
1236 if (!empty($this->_HomePagehandle) and !$id_only) {
1237 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1243 function mayChangePass() {
1247 //The default method is getting the password from prefs.
1248 // child methods obtain $stored_password from external auth.
1249 function userExists() {
1250 //if ($this->_HomePagehandle) return true;
1251 if (strtolower(get_class($this)) == "_passuser") {
1252 $class = $this->nextClass();
1253 $user = new $class($this->_userid, $this->_prefs);
1258 if (!check_php_version(5))
1259 eval("\$this = \$user;");
1260 $user = UpgradeUser($this, $user);
1261 if ($user->userExists()) {
1262 $user = UpgradeUser($this, $user);
1265 // prevent endless loop. does this work on all PHP's?
1266 // it just has to set the classname, what it correctly does.
1267 $class = $user->nextClass();
1268 if ($class == "_ForbiddenPassUser")
1274 //The default method is getting the password from prefs.
1275 // child methods obtain $stored_password from external auth.
1276 function checkPass($submitted_password) {
1277 $stored_password = $this->_prefs->get('passwd');
1278 if ($this->_checkPass($submitted_password, $stored_password)) {
1279 $this->_level = WIKIAUTH_USER;
1280 return $this->_level;
1282 if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1283 $this->_level = WIKIAUTH_FORBIDDEN;
1284 return $this->_level;
1286 return $this->_tryNextPass($submitted_password);
1291 function _checkPassLength($submitted_password) {
1292 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1293 trigger_error(_("The length of the password is shorter than the system policy allows."));
1300 * The basic password checker for all PassUser objects.
1301 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1302 * Empty passwords are always false!
1303 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1304 * @see UserPreferences::set
1306 * DBPassUser password's have their own crypt definition.
1307 * That's why DBPassUser::checkPass() doesn't call this method, if
1308 * the db password method is 'plain', which means that the DB SQL
1309 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1310 * don't store plain passwords in the DB.
1312 * TODO: remove crypt() function check from config.php:396 ??
1314 function _checkPass($submitted_password, $stored_password) {
1315 if (!empty($submitted_password)) {
1316 // This works only on plaintext passwords.
1317 if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1318 // With the EditMetaData plugin
1319 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."));
1322 if (!$this->_checkPassLength($submitted_password)) {
1325 if (ENCRYPTED_PASSWD) {
1326 // Verify against encrypted password.
1327 if (function_exists('crypt')) {
1328 if (crypt($submitted_password, $stored_password) == $stored_password )
1329 return true; // matches encrypted password
1334 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1335 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1341 // Verify against cleartext password.
1342 if ($submitted_password == $stored_password)
1345 // Check whether we forgot to enable ENCRYPTED_PASSWD
1346 if (function_exists('crypt')) {
1347 if (crypt($submitted_password, $stored_password) == $stored_password) {
1348 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1359 /** The default method is storing the password in prefs.
1360 * Child methods (DB, File) may store in external auth also, but this
1361 * must be explicitly enabled.
1362 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1364 function changePass($submitted_password) {
1365 $stored_password = $this->_prefs->get('passwd');
1366 // check if authenticated
1367 if (!$this->isAuthenticated()) return false;
1368 if (ENCRYPTED_PASSWD) {
1369 $submitted_password = crypt($submitted_password);
1371 // check other restrictions, with side-effects only.
1372 $result = $this->_checkPass($submitted_password, $stored_password);
1373 if ($stored_password != $submitted_password) {
1374 $this->_prefs->set('passwd', $submitted_password);
1375 //update the storage (session, homepage, ...)
1376 $this->SetPreferences($this->_prefs);
1379 //Todo: return an error msg to the caller what failed?
1380 // same password or no privilege
1381 return ENCRYPTED_PASSWD ? true : false;
1384 function _tryNextPass($submitted_password) {
1385 if (DEBUG & _DEBUG_LOGIN) {
1386 $class = strtolower(get_class($this));
1387 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1388 $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1390 if (USER_AUTH_POLICY === 'strict') {
1391 $class = $this->nextClass();
1392 if ($user = new $class($this->_userid,$this->_prefs)) {
1393 if ($user->userExists()) {
1394 return $user->checkPass($submitted_password);
1398 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1399 $class = $this->nextClass();
1400 if ($user = new $class($this->_userid,$this->_prefs))
1401 return $user->checkPass($submitted_password);
1403 return $this->_level;
1406 function _tryNextUser() {
1407 if (DEBUG & _DEBUG_LOGIN) {
1408 $class = strtolower(get_class($this));
1409 if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1410 $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1412 if (USER_AUTH_POLICY === 'strict'
1413 or USER_AUTH_POLICY === 'stacked') {
1414 $class = $this->nextClass();
1415 while ($user = new $class($this->_userid, $this->_prefs)) {
1416 if (!check_php_version(5))
1417 eval("\$this = \$user;");
1418 $user = UpgradeUser($this, $user);
1419 if ($user->userExists()) {
1420 $user = UpgradeUser($this, $user);
1423 $class = $this->nextClass();
1432 * Insert more auth classes here...
1433 * For example a customized db class for another db connection
1434 * or a socket-based auth server.
1440 * For security, this class should not be extended. Instead, extend
1441 * from _PassUser (think of this as unix "root").
1443 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1444 * Other members of the Administrators group must raise their level otherwise somehow.
1445 * Currently every member is a AdminUser, which will not work for the various
1451 function mayChangePass() {
1454 function checkPass($submitted_password) {
1455 if ($this->_userid == ADMIN_USER)
1456 $stored_password = ADMIN_PASSWD;
1458 // Should not happen! Only ADMIN_USER should use this class.
1459 // return $this->_tryNextPass($submitted_password); // ???
1460 // TODO: safety check if really member of the ADMIN group?
1461 $stored_password = $this->_pref->get('passwd');
1463 if ($this->_checkPass($submitted_password, $stored_password)) {
1464 $this->_level = WIKIAUTH_ADMIN;
1465 if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1467 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1469 return $this->_level;
1471 return $this->_tryNextPass($submitted_password);
1472 //$this->_level = WIKIAUTH_ANON;
1473 //return $this->_level;
1477 function storePass($submitted_password) {
1478 if ($this->_userid == ADMIN_USER)
1481 // should not happen! only ADMIN_USER should use this class.
1482 return parent::storePass($submitted_password);
1487 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1489 * Various data classes for the preference types,
1490 * to support get, set, sanify (range checking, ...)
1491 * update() will do the neccessary side-effects if a
1492 * setting gets changed (theme, language, ...)
1495 class _UserPreference
1499 function _UserPreference ($default_value) {
1500 $this->default_value = $default_value;
1503 function sanify ($value) {
1504 return (string)$value;
1507 function get ($name) {
1508 if (isset($this->{$name}))
1509 return $this->{$name};
1511 return $this->default_value;
1514 function getraw ($name) {
1515 if (!empty($this->{$name}))
1516 return $this->{$name};
1519 // stores the value as $this->$name, and not as $this->value (clever?)
1520 function set ($name, $value) {
1522 $value = $this->sanify($value);
1523 if ($this->get($name) != $value) {
1524 $this->update($value);
1527 if ($value != $this->default_value) {
1528 $this->{$name} = $value;
1530 unset($this->{$name});
1535 // default: no side-effects
1536 function update ($value) {
1541 class _UserPreference_numeric
1542 extends _UserPreference
1544 function _UserPreference_numeric ($default, $minval = false,
1546 $this->_UserPreference((double)$default);
1547 $this->_minval = (double)$minval;
1548 $this->_maxval = (double)$maxval;
1551 function sanify ($value) {
1552 $value = (double)$value;
1553 if ($this->_minval !== false && $value < $this->_minval)
1554 $value = $this->_minval;
1555 if ($this->_maxval !== false && $value > $this->_maxval)
1556 $value = $this->_maxval;
1561 class _UserPreference_int
1562 extends _UserPreference_numeric
1564 function _UserPreference_int ($default, $minval = false, $maxval = false) {
1565 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1568 function sanify ($value) {
1569 return (int)parent::sanify((int)$value);
1573 class _UserPreference_bool
1574 extends _UserPreference
1576 function _UserPreference_bool ($default = false) {
1577 $this->_UserPreference((bool)$default);
1580 function sanify ($value) {
1581 if (is_array($value)) {
1582 /* This allows for constructs like:
1584 * <input type="hidden" name="pref[boolPref][]" value="0" />
1585 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1587 * (If the checkbox is not checked, only the hidden input
1588 * gets sent. If the checkbox is sent, both inputs get
1591 foreach ($value as $val) {
1597 return (bool) $value;
1601 class _UserPreference_language
1602 extends _UserPreference
1604 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1605 $this->_UserPreference($default);
1608 // FIXME: check for valid locale
1609 function sanify ($value) {
1610 // Revert to DEFAULT_LANGUAGE if user does not specify
1611 // language in UserPreferences or chooses <system language>.
1612 if ($value == '' or empty($value))
1613 $value = DEFAULT_LANGUAGE;
1615 return (string) $value;
1618 function update ($newvalue) {
1619 if (! $this->_init ) {
1620 // invalidate etag to force fresh output
1621 $GLOBALS['request']->setValidators(array('%mtime' => false));
1622 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1627 class _UserPreference_theme
1628 extends _UserPreference
1630 function _UserPreference_theme ($default = THEME) {
1631 $this->_UserPreference($default);
1634 function sanify ($value) {
1635 if (!empty($value) and FindFile($this->_themefile($value)))
1637 return $this->default_value;
1640 function update ($newvalue) {
1642 // invalidate etag to force fresh output
1643 if (! $this->_init )
1644 $GLOBALS['request']->setValidators(array('%mtime' => false));
1646 include_once($this->_themefile($newvalue));
1647 if (empty($WikiTheme))
1648 include_once($this->_themefile(THEME));
1651 function _themefile ($theme) {
1652 return "themes/$theme/themeinfo.php";
1656 class _UserPreference_notify
1657 extends _UserPreference
1659 function sanify ($value) {
1663 return $this->default_value;
1666 /** update to global user prefs: side-effect on set notify changes
1667 * use a global_data notify hash:
1668 * notify = array('pagematch' => array(userid => ('email' => mail,
1669 * 'verified' => 0|1),
1673 function update ($value) {
1674 if (!empty($this->_init)) return;
1675 $dbh = $GLOBALS['request']->getDbh();
1676 $notify = $dbh->get('notify');
1681 // expand to existing pages only or store matches?
1682 // for now we store (glob-style) matches which is easier for the user
1683 $pages = $this->_page_split($value);
1684 // Limitation: only current user.
1685 $user = $GLOBALS['request']->getUser();
1686 if (!$user or !method_exists($user,'UserName')) return;
1687 // This fails with php5 and a WIKI_ID cookie:
1688 $userid = $user->UserName();
1689 $email = $user->_prefs->get('email');
1690 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1691 // check existing notify hash and possibly delete pages for email
1692 if (!empty($data)) {
1693 foreach ($data as $page => $users) {
1694 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1695 unset($data[$page][$userid]);
1697 if (count($data[$page]) == 0)
1698 unset($data[$page]);
1701 // add the new pages
1702 if (!empty($pages)) {
1703 foreach ($pages as $page) {
1704 if (!isset($data[$page]))
1705 $data[$page] = array();
1706 if (!isset($data[$page][$userid])) {
1707 // should we really store the verification notice here or
1708 // check it dynamically at every page->save?
1710 $data[$page][$userid] = array('email' => $email,
1711 'verified' => $verified);
1713 $data[$page][$userid] = array('email' => $email);
1718 // store users changes
1719 $dbh->set('notify',$data);
1722 /** split the user-given comma or whitespace delimited pagenames
1725 function _page_split($value) {
1726 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1730 class _UserPreference_email
1731 extends _UserPreference
1733 function sanify($value) {
1735 // email address is already checked by Gforge
1736 if (defined('GFORGE') and GFORGE) {
1739 // check for valid email address
1740 if ($this->get('email') == $value and $this->getraw('emailVerified'))
1743 if ($value == 1 or $value === true)
1745 list($ok,$msg) = ValidateMail($value,'noconnect');
1749 trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
1750 return $this->default_value;
1754 /** Side-effect on email changes:
1755 * Send a verification mail or for now just a notification email.
1756 * For true verification (value = 2), we'd need a mailserver hook.
1758 function update($value) {
1759 // email address is already checked by Gforge
1760 if (defined('GFORGE') and GFORGE) {
1763 if (!empty($this->_init)) return;
1764 $verified = $this->getraw('emailVerified');
1766 if (($value == 1 or $value === true) and $verified)
1768 if (!empty($value) and !$verified) {
1769 list($ok,$msg) = ValidateMail($value);
1770 if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
1771 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1772 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) {
1773 $this->set('emailVerified',1);
1775 trigger_error($msg, E_USER_WARNING);
1780 function get($name) {
1781 // get email address from Gforge
1782 if (defined('GFORGE') && GFORGE && session_loggedin()) {
1783 $user = session_get_user();
1784 return $user->getEmail();
1792 /** Check for valid email address
1793 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1794 Note: too strict, Bug #1053681
1796 function ValidateMail($email, $noconnect=false) {
1798 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1800 // if this check is too strict (like invalid mail addresses in a local network only)
1801 // uncomment the following line:
1802 //return array(true,"not validated");
1803 // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1807 // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1808 // addresses, from the Perl module Mail::RFC822::Address, reduced to
1809 // accept single RFC822 addresses without comments only. (The original
1810 // accepts groups and properly commented addresses also.)
1811 $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1813 $specials = '()<>@,;:\\\\".\\[\\]';
1814 $controls = '\\000-\\031';
1816 $dtext = "[^\\[\\]\\r\\\\]";
1817 $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1819 $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1821 $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1822 $word = "(?:$atom|$quoted_string)";
1823 $localpart = "$word(?:\\.$lwsp*$word)*";
1825 $sub_domain = "(?:$atom|$domain_literal)";
1826 $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1828 $addr_spec = "$localpart\@$lwsp*$domain";
1831 $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1832 $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1833 $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1835 $rfc822re = "/$lwsp*$mailbox/";
1836 unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1837 $atom, $word, $quoted_string);
1838 unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1840 if (!preg_match($rfc822re, $email)) {
1842 $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
1846 return array(true, sprintf(_("E-Mail address '%s' is properly formatted"), $email));
1848 list ( $Username, $Domain ) = split ("@", $email);
1849 //Todo: getmxrr workaround on windows or manual input field to verify it manually
1850 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1851 $ConnectAddress = $MXHost[0];
1853 $ConnectAddress = $Domain;
1854 if (isset($EMailHosts[ $Domain ])) {
1855 $ConnectAddress = $EMailHosts[ $Domain ];
1858 $Connect = @fsockopen ( $ConnectAddress, 25 );
1860 if (ereg("^220", $Out = fgets($Connect, 1024))) {
1861 fputs ($Connect, "HELO $HTTP_HOST\r\n");
1862 $Out = fgets ( $Connect, 1024 );
1863 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
1864 $From = fgets ( $Connect, 1024 );
1865 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
1866 $To = fgets ($Connect, 1024);
1867 fputs ($Connect, "QUIT\r\n");
1869 if (!ereg ("^250", $From)) {
1871 $result[1]="Server rejected address: ". $From;
1874 if (!ereg ( "^250", $To )) {
1876 $result[1]="Server rejected address: ". $To;
1881 $result[1] = "No response from server";
1886 $result[1]="Can not connect E-Mail server.";
1890 $result[1]="E-Mail address '$email' appears to be valid.";
1892 } // end of function
1894 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1899 * This object holds the $request->_prefs subobjects.
1900 * A simple packed array of non-default values get's stored as cookie,
1901 * homepage, or database, which are converted to the array of
1903 * We don't store the objects, because otherwise we will
1904 * not be able to upgrade any subobject. And it's a waste of space also.
1907 class UserPreferences
1909 var $notifyPagesAll;
1911 function UserPreferences($saved_prefs = false) {
1912 // userid stored too, to ensure the prefs are being loaded for
1913 // the correct (currently signing in) userid if stored in a
1915 // Update: for db prefs we disallow passwd.
1916 // userid is needed for pref reflexion. current pref must know its username,
1917 // if some app needs prefs from different users, different from current user.
1920 'userid' => new _UserPreference(''),
1921 'passwd' => new _UserPreference(''),
1922 'autologin' => new _UserPreference_bool(),
1923 //'emailVerified' => new _UserPreference_emailVerified(),
1924 //fixed: store emailVerified as email parameter, 1.3.8
1925 'email' => new _UserPreference_email(''),
1926 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1927 'theme' => new _UserPreference_theme(THEME),
1928 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1929 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1931 EDITWIDTH_MAX_COLS),
1932 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1933 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1934 EDITHEIGHT_MIN_ROWS,
1935 EDITHEIGHT_MAX_ROWS),
1936 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1937 TIMEOFFSET_MIN_HOURS,
1938 TIMEOFFSET_MAX_HOURS),
1939 'ownModifications' => new _UserPreference_bool(),
1940 'majorModificationsOnly' => new _UserPreference_bool(),
1941 'relativeDates' => new _UserPreference_bool(),
1942 'googleLink' => new _UserPreference_bool(), // 1.3.10
1943 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1946 // This should be probably be done with $customUserPreferenceColumns
1947 // For now, we use GFORGE define
1948 if (defined('GFORGE') and GFORGE) {
1949 $gforgeprefs = array(
1950 'pageTrail' => new _UserPreference_bool(),
1951 'diffMenuItem' => new _UserPreference_bool(),
1952 'pageInfoMenuItem' => new _UserPreference_bool(),
1953 'pdfMenuItem' => new _UserPreference_bool(),
1954 'lockMenuItem' => new _UserPreference_bool(),
1955 'chownMenuItem' => new _UserPreference_bool(),
1956 'setaclMenuItem' => new _UserPreference_bool(),
1957 'removeMenuItem' => new _UserPreference_bool(),
1958 'renameMenuItem' => new _UserPreference_bool(),
1959 'revertMenuItem' => new _UserPreference_bool(),
1960 'backLinksMenuItem' => new _UserPreference_bool(),
1961 'watchPageMenuItem' => new _UserPreference_bool(),
1962 'recentChangesMenuItem' => new _UserPreference_bool(),
1963 'randomPageMenuItem' => new _UserPreference_bool(),
1964 'likePagesMenuItem' => new _UserPreference_bool(),
1965 'specialPagesMenuItem' => new _UserPreference_bool(),
1967 $this->_prefs = array_merge($this->_prefs, $gforgeprefs);
1970 // add custom theme-specific pref types:
1971 // FIXME: on theme changes the wiki_user session pref object will fail.
1972 // We will silently ignore this.
1973 if (!empty($customUserPreferenceColumns))
1974 $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
1976 if (isset($this->_method) and $this->_method == 'SQL') {
1977 //unset($this->_prefs['userid']);
1978 unset($this->_prefs['passwd']);
1981 if (is_array($saved_prefs)) {
1982 foreach ($saved_prefs as $name => $value)
1983 $this->set($name, $value);
1987 function __clone() {
1988 foreach ($this as $key => $val) {
1989 if (is_object($val) || (is_array($val))) {
1990 $this->{$key} = unserialize(serialize($val));
1995 function _getPref($name) {
1996 if ($name == 'emailVerified')
1998 if (!isset($this->_prefs[$name])) {
1999 if ($name == 'passwd2') return false;
2000 if ($name == 'passwd') return false;
2001 trigger_error("$name: unknown preference", E_USER_NOTICE);
2004 return $this->_prefs[$name];
2007 // get the value or default_value of the subobject
2008 function get($name) {
2009 if ($_pref = $this->_getPref($name))
2010 if ($name == 'emailVerified')
2011 return $_pref->getraw($name);
2013 return $_pref->get($name);
2018 // check and set the new value in the subobject
2019 function set($name, $value) {
2020 $pref = $this->_getPref($name);
2021 if ($pref === false)
2024 /* do it here or outside? */
2025 if ($name == 'passwd' and
2026 defined('PASSWORD_LENGTH_MINIMUM') and
2027 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2028 //TODO: How to notify the user?
2032 if ($name == 'theme' and $value == '')
2035 // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2036 if ((!$value and $pref->default_value)
2037 or ($value and !isset($pref->{$name})) // bug #1355533
2038 or ($value and ($pref->{$name} != $pref->default_value)))
2040 if ($name == 'emailVerified') $newvalue = $value;
2041 else $newvalue = $pref->sanify($value);
2042 $pref->set($name, $newvalue);
2044 $this->_prefs[$name] =& $pref;
2048 * use init to avoid update on set
2050 function updatePrefs($prefs, $init = false) {
2052 if ($init) $this->_init = $init;
2053 if (is_object($prefs)) {
2054 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2055 $obj->_init = $init;
2056 if ($obj->get($type) !== $prefs->get($type)) {
2057 if ($obj->set($type, $prefs->get($type)))
2060 foreach (array_keys($this->_prefs) as $type) {
2061 $obj =& $this->_prefs[$type];
2062 $obj->_init = $init;
2063 if ($prefs->get($type) !== $obj->get($type)) {
2064 // special systemdefault prefs: (probably not needed)
2065 if ($type == 'theme' and $prefs->get($type) == '' and
2066 $obj->get($type) == THEME) continue;
2067 if ($type == 'lang' and $prefs->get($type) == '' and
2068 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2069 if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2073 } elseif (is_array($prefs)) {
2074 //unset($this->_prefs['userid']);
2076 if (isset($this->_method) and
2077 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2078 unset($this->_prefs['passwd']);
2081 // emailVerified at first, the rest later
2082 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2083 $obj->_init = $init;
2084 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2085 if ($obj->set($type,$prefs[$type]))
2088 foreach (array_keys($this->_prefs) as $type) {
2089 $obj =& $this->_prefs[$type];
2090 $obj->_init = $init;
2091 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2092 $prefs[$type] = false;
2093 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2094 $prefs[$type] = (int) $prefs[$type];
2095 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2096 // special systemdefault prefs:
2097 if ($type == 'theme' and $prefs[$type] == '' and
2098 $obj->get($type) == THEME) continue;
2099 if ($type == 'lang' and $prefs[$type] == '' and
2100 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2101 if ($obj->set($type,$prefs[$type]))
2109 // For now convert just array of objects => array of values
2110 // Todo: the specialized subobjects must override this.
2113 foreach ($this->_prefs as $name => $object) {
2114 if ($value = $object->getraw($name))
2115 $prefs[$name] = $value;
2116 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2117 $prefs['emailVerified'] = $value;
2118 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2119 if (strlen($value) != strlen(crypt('test')))
2120 $prefs['passwd'] = crypt($value);
2121 else // already crypted
2122 $prefs['passwd'] = $value;
2126 if (defined('GFORGE') and GFORGE) {
2127 // Merge current notifyPages with notifyPagesAll
2128 // notifyPages are pages to notify in the current project
2129 // while $notifyPagesAll is used to store all the monitored pages.
2130 if (isset($prefs['notifyPages'])) {
2131 $this->notifyPagesAll[PAGE_PREFIX] = $prefs['notifyPages'];
2132 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2136 return $this->pack($prefs);
2139 // packed string or array of values => array of values
2140 // Todo: the specialized subobjects must override this.
2141 function retrieve($packed) {
2142 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2143 $packed = unserialize($packed);
2144 if (!is_array($packed)) return false;
2146 foreach ($packed as $name => $packed_pref) {
2147 if (is_string($packed_pref)
2148 and isSerialized($packed_pref)
2149 and substr($packed_pref, 0, 2) == "O:")
2151 //legacy: check if it's an old array of objects
2152 // Looks like a serialized object.
2153 // This might fail if the object definition does not exist anymore.
2154 // object with ->$name and ->default_value vars.
2155 $pref = @unserialize($packed_pref);
2156 if (is_object($pref))
2157 $prefs[$name] = $pref->get($name);
2158 // fix old-style prefs
2159 } elseif (is_numeric($name) and is_array($packed_pref)) {
2160 if (count($packed_pref) == 1) {
2161 list($name,$value) = each($packed_pref);
2162 $prefs[$name] = $value;
2165 if (isSerialized($packed_pref))
2166 $prefs[$name] = @unserialize($packed_pref);
2167 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2168 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2169 // patched by frederik@pandora.be
2170 if (empty($prefs[$name]))
2171 $prefs[$name] = $packed_pref;
2175 if (defined('GFORGE') and GFORGE) {
2176 // Restore notifyPages from notifyPagesAll
2177 // notifyPages are pages to notify in the current project
2178 // while $notifyPagesAll is used to store all the monitored pages.
2179 if (isset($prefs['notifyPages'])) {
2180 $this->notifyPagesAll = $prefs['notifyPages'];
2181 if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
2182 $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
2184 $prefs['notifyPages'] = '';
2193 * Check if the given prefs object is different from the current prefs object
2195 function isChanged($other) {
2196 foreach ($this->_prefs as $type => $obj) {
2197 if ($obj->get($type) !== $other->get($type))
2203 function defaultPreferences() {
2205 foreach ($this->_prefs as $key => $obj) {
2206 $prefs[$key] = $obj->default_value;
2213 return $this->_prefs;
2216 function pack($nonpacked) {
2217 return serialize($nonpacked);
2220 function unpack($packed) {
2223 //$packed = base64_decode($packed);
2224 if (substr($packed, 0, 2) == "O:") {
2225 // Looks like a serialized object
2226 return unserialize($packed);
2228 if (substr($packed, 0, 2) == "a:") {
2229 return unserialize($packed);
2231 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2237 return wikihash($this->_prefs);
2241 /** TODO: new pref storage classes
2242 * These are currently user specific and should be rewritten to be pref specific.
2243 * i.e. $this == $user->_prefs
2246 class CookieUserPreferences
2247 extends UserPreferences
2249 function CookieUserPreferences ($saved_prefs = false) {
2250 //_AnonUser::_AnonUser('',$saved_prefs);
2251 UserPreferences::UserPreferences($saved_prefs);
2255 class PageUserPreferences
2256 extends UserPreferences
2258 function PageUserPreferences ($saved_prefs = false) {
2259 UserPreferences::UserPreferences($saved_prefs);
2263 class PearDbUserPreferences
2264 extends UserPreferences
2266 function PearDbUserPreferences ($saved_prefs = false) {
2267 UserPreferences::UserPreferences($saved_prefs);
2271 class AdoDbUserPreferences
2272 extends UserPreferences
2274 function AdoDbUserPreferences ($saved_prefs = false) {
2275 UserPreferences::UserPreferences($saved_prefs);
2277 function getPreferences() {
2278 // override the generic slow method here for efficiency
2279 _AnonUser::getPreferences();
2280 $this->getAuthDbh();
2281 if (isset($this->_select)) {
2282 $dbh = & $this->_auth_dbi;
2283 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2287 $prefs_blob = $rs->fields['pref_blob'];
2289 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2290 $updated = $this->_prefs->updatePrefs($restored_from_db);
2291 //$this->_prefs = new UserPreferences($restored_from_db);
2292 return $this->_prefs;
2296 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2297 if ($restored_from_page = $this->_prefs->retrieve
2298 ($this->_HomePagehandle->get('pref'))) {
2299 $updated = $this->_prefs->updatePrefs($restored_from_page);
2300 //$this->_prefs = new UserPreferences($restored_from_page);
2301 return $this->_prefs;
2304 return $this->_prefs;
2312 // c-basic-offset: 4
2313 // c-hanging-comment-ender-p: nil
2314 // indent-tabs-mode: nil