2 rcs_id('$Id: WikiUserNew.php,v 1.89 2004-06-06 16:58:51 rurban Exp $');
3 /* Copyright (C) 2004 $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.
83 * 6) enforced new cookie policy: prefs don't get stored in cookies
84 * anymore, only in homepage and/or database, but always in the
85 * current session. old pref cookies will get deleted.
87 * 7) Certain themes should be able to extend the predefined list
88 * of preferences. Display/editing is done in the theme specific userprefs.tmpl,
89 * but storage must be extended to the Get/SetPreferences methods.
90 * <theme>/themeinfo.php must provide CustomUserPreferences:
91 * A list of name => _UserPreference class pairs.
94 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
95 define('WIKIAUTH_ANON', 0); // Not signed in.
96 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
97 define('WIKIAUTH_USER', 2); // Bogo user with a password.
98 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
99 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
101 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
102 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);
117 * There are be the following constants in config/config.ini to
118 * establish login parameters:
120 * ALLOW_ANON_USER default true
121 * ALLOW_ANON_EDIT default true
122 * ALLOW_BOGO_LOGIN default true
123 * ALLOW_USER_PASSWORDS default true
124 * PASSWORD_LENGTH_MINIMUM default 6 ?
126 * To require user passwords for editing:
127 * ALLOW_ANON_USER = true
128 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
129 * ALLOW_BOGO_LOGIN = false
130 * ALLOW_USER_PASSWORDS = true
132 * To establish a COMPLETELY private wiki, such as an internal
134 * ALLOW_ANON_USER = false
135 * (and probably require user passwords as described above). In this
136 * case the user will be prompted to login immediately upon accessing
139 * There are other possible combinations, but the typical wiki (such
140 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
145 // The last object in the row is the bad guy...
146 if (!is_array($USER_AUTH_ORDER))
147 $USER_AUTH_ORDER = array("Forbidden");
149 $USER_AUTH_ORDER[] = "Forbidden";
151 // Local convenience functions.
152 function _isAnonUserAllowed() {
153 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
155 function _isBogoUserAllowed() {
156 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
158 function _isUserPasswordsAllowed() {
159 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
162 // Possibly upgrade userobject functions.
163 function _determineAdminUserOrOtherUser($UserName) {
164 // Sanity check. User name is a condition of the definition of the
165 // _AdminUser, _BogoUser and _passuser.
167 return $GLOBALS['ForbiddenUser'];
169 //FIXME: check admin membership later at checkPass. now we cannot raise the level.
170 //$group = &WikiGroup::getGroup($GLOBALS['request']);
171 if ($UserName == ADMIN_USER)
172 return new _AdminUser($UserName);
173 /* elseif ($group->isMember(GROUP_ADMIN)) {
174 return _determineBogoUserOrPassUser($UserName);
178 return _determineBogoUserOrPassUser($UserName);
181 function _determineBogoUserOrPassUser($UserName) {
182 global $ForbiddenUser;
184 // Sanity check. User name is a condition of the definition of
185 // _BogoUser and _PassUser.
187 return $ForbiddenUser;
189 // Check for password and possibly upgrade user object.
190 // $_BogoUser = new _BogoUser($UserName);
191 if (_isBogoUserAllowed()) {
192 $_BogoUser = new _BogoLoginPassUser($UserName);
193 if ($_BogoUser->userExists())
196 if (_isUserPasswordsAllowed()) {
197 // PassUsers override BogoUsers if a password is stored
198 if (isset($_BogoUser) and isset($_BogoUser->_prefs) and $_BogoUser->_prefs->get('passwd'))
199 return new _PassUser($UserName,$_BogoUser->_prefs);
201 $_PassUser = new _PassUser($UserName,isset($_BogoUser) ? $_BogoUser->_prefs : false);
202 if ($_PassUser->userExists())
206 // No Bogo- or PassUser exists, or
207 // passwords are not allowed, and bogo is disallowed too.
208 // (Only the admin can sign in).
209 return $ForbiddenUser;
213 * Primary WikiUser function, called by lib/main.php.
215 * This determines the user's type and returns an appropriate user
216 * object. lib/main.php then querys the resultant object for password
217 * validity as necessary.
219 * If an _AnonUser object is returned, the user may only browse pages
220 * (and save prefs in a cookie).
222 * To disable access but provide prefs the global $ForbiddenUser class
223 * is returned. (was previously false)
226 function WikiUser ($UserName = '') {
227 global $ForbiddenUser;
229 //Maybe: Check sessionvar for username & save username into
230 //sessionvar (may be more appropriate to do this in lib/main.php).
232 $ForbiddenUser = new _ForbiddenUser($UserName);
233 // Found a user name.
234 return _determineAdminUserOrOtherUser($UserName);
236 elseif (!empty($_SESSION['userid'])) {
237 // Found a user name.
238 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
239 return _determineAdminUserOrOtherUser($_SESSION['userid']);
242 // Check for autologin pref in cookie and possibly upgrade
243 // user object to another type.
244 $_AnonUser = new _AnonUser();
245 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
246 // Found a user name.
247 $ForbiddenUser = new _ForbiddenUser($UserName);
248 return _determineAdminUserOrOtherUser($UserName);
251 $ForbiddenUser = new _ForbiddenUser();
252 if (_isAnonUserAllowed())
254 return $ForbiddenUser; // User must sign in to browse pages.
256 return $ForbiddenUser; // User must sign in with a password.
259 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
260 . "Unexpectedly, an appropriate user class could not be determined.");
261 return $ForbiddenUser; // Failsafe.
266 * WikiUser.php use the name 'WikiUser'
268 function WikiUserClassname() {
274 * Upgrade olduser by copying properties from user to olduser.
275 * We are not sure yet, for which php's a simple $this = $user works reliably,
276 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
277 * that's why try it the hard way.
279 function UpgradeUser ($olduser, $user) {
280 if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
281 // populate the upgraded class $olduser with the values from the new user object
282 //only _auth_level, _current_method, _current_index,
283 if (!empty($user->_level) and
284 $user->_level > $olduser->_level)
285 $olduser->_level = $user->_level;
286 if (!empty($user->_current_index) and
287 $user->_current_index > $olduser->_current_index) {
288 $olduser->_current_index = $user->_current_index;
289 $olduser->_current_method = $user->_current_method;
291 if (!empty($user->_authmethod))
292 $olduser->_authmethod = $user->_authmethod;
294 foreach (get_object_vars($user) as $k => $v) {
295 if (!empty($v)) $olduser->$k = $v;
298 $olduser->hasHomePage(); // revive db handle, because these don't survive sessions
299 //$GLOBALS['request']->_user = $olduser;
307 * Probably not needed, since we use the various user objects methods so far.
308 * Anyway, here it is, looping through all available objects.
310 function UserExists ($UserName) {
312 if (!($user = $request->getUser()))
313 $user = WikiUser($UserName);
316 if ($user->userExists($UserName)) {
317 $request->_user = $user;
320 if (isa($user,'_BogoUser'))
321 $user = new _PassUser($UserName,$user->_prefs);
322 $class = $user->nextClass();
323 if ($user = new $class($UserName,$user->_prefs)) {
324 return $user->userExists($UserName);
326 $request->_user = $GLOBALS['ForbiddenUser'];
330 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
333 * Base WikiUser class.
338 var $_level = WIKIAUTH_ANON;
340 var $_HomePagehandle = false;
343 function _WikiUser($UserName='', $prefs=false) {
345 $this->_userid = $UserName;
346 $this->_HomePagehandle = false;
348 $this->hasHomePage();
350 if (empty($this->_prefs)) {
351 if ($prefs) $this->_prefs = $prefs;
352 else $this->getPreferences();
356 function UserName() {
357 if (!empty($this->_userid))
358 return $this->_userid;
361 function getPreferences() {
362 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
363 . "New subclasses of _WikiUser must override this function.");
367 function setPreferences($prefs, $id_only) {
368 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
369 . "New subclasses of _WikiUser must override this function.");
373 function userExists() {
374 return $this->hasHomePage();
377 function checkPass($submitted_password) {
378 // By definition, an undefined user class cannot sign in.
379 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
380 . "New subclasses of _WikiUser must override this function.");
384 // returns page_handle to user's home page or false if none
385 function hasHomePage() {
386 if ($this->_userid) {
387 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
388 return $this->_HomePagehandle->exists();
391 // check db again (maybe someone else created it since
394 $this->_HomePagehandle = $request->getPage($this->_userid);
395 return $this->_HomePagehandle->exists();
402 // innocent helper: case-insensitive position in _auth_methods
403 function array_position ($string, $array) {
404 $string = strtolower($string);
405 for ($found = 0; $found < count($array); $found++) {
406 if (strtolower($array[$found]) == $string)
412 function nextAuthMethodIndex() {
413 if (empty($this->_auth_methods))
414 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
415 if (empty($this->_current_index)) {
416 if (get_class($this) != '_passuser') {
417 $this->_current_method = substr(get_class($this),1,-8);
418 $this->_current_index = $this->array_position($this->_current_method,
419 $this->_auth_methods);
421 $this->_current_index = -1;
424 $this->_current_index++;
425 if ($this->_current_index >= count($this->_auth_methods))
427 $this->_current_method = $this->_auth_methods[$this->_current_index];
428 return $this->_current_index;
431 function AuthMethod($index = false) {
432 return $this->_auth_methods[ $index === false ? 0 : $index];
435 // upgrade the user object
436 function nextClass() {
437 if (($next = $this->nextAuthMethodIndex()) !== false) {
438 $method = $this->AuthMethod($next);
439 return "_".$method."PassUser";
441 if ($user = new $class($this->_userid)) {
442 // prevent from endless recursion.
443 //$user->_current_method = $this->_current_method;
444 //$user->_current_index = $this->_current_index;
445 $user = UpgradeUser($user, $this);
450 return "_ForbiddenPassUser";
453 //Fixme: for _HttpAuthPassUser
454 function PrintLoginForm (&$request, $args, $fail_message = false,
455 $seperate_page = false) {
456 include_once('lib/Template.php');
457 // Call update_locale in case the system's default language is not 'en'.
458 // (We have no user pref for lang at this point yet, no one is logged in.)
459 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
460 update_locale(DEFAULT_LANGUAGE);
461 $userid = $this->_userid;
463 extract($args); // fixme
465 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
467 $pagename = $request->getArg('pagename');
469 $login = Template('login',
470 compact('pagename', 'userid', 'require_level',
471 'fail_message', 'pass_required', 'nocache'));
472 // check if the html template was already processed
473 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
474 if ($seperate_page) {
475 $page = $request->getPage($pagename);
476 $revision = $page->getCurrentRevision();
477 return GeneratePage($login,_("Sign In"),$revision);
479 return $login->printExpansion();
483 /** Signed in but probably not password checked.
485 function isSignedIn() {
486 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
489 /** This is password checked for sure.
491 function isAuthenticated () {
492 //return isa($this,'_PassUser');
493 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
494 return $this->_level >= WIKIAUTH_BOGO;
497 function isAdmin () {
499 if ($this->_level == WIKIAUTH_ADMIN) return true;
501 if (!$group) $group = &WikiGroup::getGroup($GLOBALS['request']);
502 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
505 /** Name or IP for a signed user. UserName could come from a cookie e.g.
508 return ( $this->UserName()
510 : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
513 /** Name for an authenticated user. No IP here.
515 function getAuthenticatedId() {
516 return ( $this->isAuthenticated()
518 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
521 function hasAuthority ($require_level) {
522 return $this->_level >= $require_level;
525 function isValidName ($userid = false) {
527 $userid = $this->_userid;
528 return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32;
532 * Called on an auth_args POST request, such as login, logout or signin.
533 * TODO: Check BogoLogin users with empty password. (self-signed users)
535 function AuthCheck ($postargs) {
536 // Normalize args, and extract.
537 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
539 foreach ($keys as $key)
540 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
542 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
544 if ($logout) { // Log out
545 $GLOBALS['request']->_user = new _AnonUser();
546 $GLOBALS['request']->_user->_userid = '';
547 $GLOBALS['request']->_user->_level = WIKIAUTH_ANON;
548 return $GLOBALS['request']->_user;
550 return false; // User hit cancel button.
551 elseif (!$login && !$userid)
552 return false; // Nothing to do?
554 if (!$this->isValidName($userid))
555 return _("Invalid username.");;
557 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
558 if ($authlevel <= 0) { // anon or forbidden
560 return _("Invalid password.");
562 return _("Invalid password or userid.");
563 } elseif ($authlevel < $require_level) { // auth ok, but not enough
564 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
567 $class = "_" . $this->_current_method . "PassUser";
568 $user = new $class($userid,$this->_prefs);
569 /*PHP5 patch*/$this = $user;
570 $this->_level = $authlevel;
573 $this->_userid = $userid;
574 $this->_level = $authlevel;
575 return _("Insufficient permissions.");
579 //$user = $GLOBALS['request']->_user;
580 if (!empty($this->_current_method) and
581 strtolower(get_class($this)) == '_passuser')
584 $class = "_" . $this->_current_method . "PassUser";
585 $user = new $class($userid,$this->_prefs);
586 /*PHP5 patch*/$this = $user;
587 $this->_level = $authlevel;
590 $this->_userid = $userid;
591 $this->_level = $authlevel;
598 * Not authenticated in user, but he may be signed in. Basicly with view access only.
599 * prefs are stored in cookies, but only the userid.
604 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
606 /** Anon only gets to load and save prefs in a cookie, that's it.
608 function getPreferences() {
611 if (empty($this->_prefs))
612 $this->_prefs = new UserPreferences;
613 $UserName = $this->UserName();
615 // Try to read deprecated 1.3.x style cookies
616 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
617 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
618 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
620 . sprintf("%s='%s'", WIKI_NAME, $cookie)
622 . _("Default preferences will be used."),
626 * Only set if it matches the UserName who is
627 * signing in or if this really is an Anon login (no
628 * username). (Remember, _BogoUser and higher inherit this
631 if (! $UserName || $UserName == @$unboxedcookie['userid']) {
632 $updated = $this->_prefs->updatePrefs($unboxedcookie);
633 //$this->_prefs = new UserPreferences($unboxedcookie);
634 $UserName = @$unboxedcookie['userid'];
635 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
636 $this->_userid = $UserName;
640 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
641 $request->deleteCookieVar(WIKI_NAME);
643 // Try to read deprecated 1.3.4 style cookies
644 if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
645 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
646 if (! $UserName || $UserName == $unboxedcookie['userid']) {
647 $updated = $this->_prefs->updatePrefs($unboxedcookie);
648 //$this->_prefs = new UserPreferences($unboxedcookie);
649 $UserName = $unboxedcookie['userid'];
650 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
651 $this->_userid = $UserName;
655 $request->deleteCookieVar("WIKI_PREF2");
659 // Try reading userid from old PhpWiki cookie formats:
660 if ($cookie = $request->cookies->get_old('WIKI_ID')) {
661 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
663 elseif (is_array($cookie) and !empty($cookie['userid']))
664 $UserName = $cookie['userid'];
667 $request->deleteCookieVar("WIKI_ID");
669 $this->_userid = $UserName;
672 // initializeTheme() needs at least an empty object
674 if (empty($this->_prefs))
675 $this->_prefs = new UserPreferences;
677 return $this->_prefs;
680 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
682 * Allow for multiple wikis in same domain. Encode only the
683 * _prefs array of the UserPreference object. Ideally the
684 * prefs array should just be imploded into a single string or
685 * something so it is completely human readable by the end
686 * user. In that case stricter error checking will be needed
687 * when loading the cookie.
689 function setPreferences($prefs, $id_only=false) {
690 if (!is_object($prefs)) {
691 if (is_object($this->_prefs)) {
692 $updated = $this->_prefs->updatePrefs($prefs);
693 $prefs =& $this->_prefs;
695 // update the prefs values from scratch. This could leed to unnecessary
696 // side-effects: duplicate emailVerified, ...
697 $this->_prefs = new UserPreferences($prefs);
701 if (!isset($this->_prefs))
702 $this->_prefs =& $prefs;
704 $updated = $this->_prefs->isChanged($prefs);
709 // new 1.3.8 policy: no array cookies, only plain userid string as in
710 // the pre 1.3.x versions.
711 // prefs should be stored besides the session in the homepagehandle or in a db.
712 $request->setCookieVar('WIKI_ID', $this->_userid,
713 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
714 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
715 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
718 $packed = $prefs->store();
719 $unpacked = $prefs->unpack($packed);
720 if (count($unpacked)) {
721 foreach (array('_method','_select','_update') as $param) {
722 if (!empty($this->_prefs->{$param}))
723 $prefs->{$param} = $this->_prefs->{$param};
725 $this->_prefs = $prefs;
726 //FIXME! The following must be done in $request->_setUser(), not here,
727 // to be able to iterate over multiple users, without tampering the current user.
730 $request->_prefs =& $this->_prefs;
731 $request->_user->_prefs =& $this->_prefs;
732 if (isset($request->_user->_auth_dbi)) {
733 $user = $request->_user;
734 unset($user->_auth_dbi);
735 $request->setSessionVar('wiki_user', $user);
737 //$request->setSessionVar('wiki_prefs', $this->_prefs);
738 $request->setSessionVar('wiki_user', $request->_user);
745 function userExists() {
749 function checkPass($submitted_password) {
751 // this might happen on a old-style signin button.
753 // By definition, the _AnonUser does not HAVE a password
754 // (compared to _BogoUser, who has an EMPTY password).
755 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
756 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
757 . "New subclasses of _WikiUser must override this function.");
764 * Helper class to finish the PassUser auth loop.
765 * This is added automatically to USER_AUTH_ORDER.
770 var $_level = WIKIAUTH_FORBIDDEN;
772 function checkPass($submitted_password) {
773 return WIKIAUTH_FORBIDDEN;
776 function userExists() {
777 if ($this->_HomePagehandle) return true;
782 * The PassUser name gets created automatically.
783 * That's why this class is empty, but must exist.
785 class _ForbiddenPassUser
786 extends _ForbiddenUser
794 * Do NOT extend _BogoUser to other classes, for checkPass()
795 * security. (In case of defects in code logic of the new class!)
796 * The intermediate step between anon and passuser.
797 * We also have the _BogoLoginPassUser class with stricter
798 * password checking, which fits into the auth loop.
799 * Note: This class is not called anymore by WikiUser()
804 function userExists() {
805 if (isWikiWord($this->_userid)) {
806 $this->_level = WIKIAUTH_BOGO;
809 $this->_level = WIKIAUTH_ANON;
814 function checkPass($submitted_password) {
815 // By definition, BogoUser has an empty password.
817 return $this->_level;
824 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
826 * The classes for all subsequent auth methods extend from this class.
827 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
828 * the three auth method policies first-only, strict and stacked
829 * and the two methods for prefs: homepage or database,
830 * if $DBAuthParams['pref_select'] is defined.
832 * Default is PersonalPage auth and prefs.
834 * @author: Reini Urban
838 var $_auth_dbi, $_prefs;
839 var $_current_method, $_current_index;
841 // check and prepare the auth and pref methods only once
842 function _PassUser($UserName='', $prefs=false) {
843 //global $DBAuthParams, $DBParams;
845 if (!$this->isValidName($UserName))
847 $this->_userid = $UserName;
848 if ($this->hasHomePage())
849 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
851 $this->_authmethod = substr(get_class($this),1,-8);
852 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
853 if (! $this->_prefs) {
854 if ($prefs) $this->_prefs = $prefs;
855 else $this->getPreferences();
858 // Check the configured Prefs methods
859 $dbi = $this->getAuthDbh();
860 $dbh = $GLOBALS['request']->getDbh();
861 if ( $dbi and !isset($this->_prefs->_select) and $dbh->getAuthParam('pref_select')) {
862 $this->_prefs->_method = $dbh->getParam('dbtype');
863 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
865 if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
866 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
867 array("userid", "pref_blob"));
870 $this->_prefs->_method = 'HomePage';
873 // Upgrade to the next parent _PassUser class. Avoid recursion.
874 if ( strtolower(get_class($this)) === '_passuser' ) {
875 //auth policy: Check the order of the configured auth methods
876 // 1. first-only: Upgrade the class here in the constructor
877 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
878 /// in the previous PhpWiki releases (slow)
879 // 3. strict: upgrade the class after checking the user existance in userExists()
880 // 4. stacked: upgrade the class after the password verification in checkPass()
881 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
882 if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
883 if (defined('USER_AUTH_POLICY')) {
884 // policy 1: only pre-define one method for all users
885 if (USER_AUTH_POLICY === 'first-only') {
886 $class = $this->nextClass();
887 return new $class($UserName,$this->_prefs);
889 // Use the default behaviour from the previous versions:
890 elseif (USER_AUTH_POLICY === 'old') {
891 // Default: try to be smart
892 // On php5 we can directly return and upgrade the Object,
893 // before we have to upgrade it manually.
894 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
895 if (check_php_version(5))
896 return new _HttpAuthPassUser($UserName,$this->_prefs);
898 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
899 //todo: with php5 comment the following line.
900 /*PHP5 patch*/$this = $user;
903 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
904 $dbh->getAuthParam('auth_check') and
905 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
906 if (check_php_version(5))
907 return new _DbPassUser($UserName,$this->_prefs);
909 $user = new _DbPassUser($UserName,$this->_prefs);
910 //todo: with php5 comment the following line.
911 /*PHP5 patch*/$this = $user;
914 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
915 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
916 function_exists('ldap_open')) {
917 if (check_php_version(5))
918 return new _LDAPPassUser($UserName,$this->_prefs);
920 $user = new _LDAPPassUser($UserName,$this->_prefs);
921 //todo: with php5 comment the following line.
922 /*PHP5 patch*/$this = $user;
925 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
926 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
927 if (check_php_version(5))
928 return new _IMAPPassUser($UserName,$this->_prefs);
930 $user = new _IMAPPassUser($UserName,$this->_prefs);
931 //todo: with php5 comment the following line.
932 /*PHP5 patch*/$this = $user;
935 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
936 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
937 if (check_php_version(5))
938 return new _FilePassUser($UserName, $this->_prefs);
940 $user = new _FilePassUser($UserName, $this->_prefs);
941 //todo: with php5 comment the following line.
942 /*PHP5 patch*/$this = $user;
946 if (check_php_version(5))
947 return new _PersonalPagePassUser($UserName,$this->_prefs);
949 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
950 //todo: with php5 comment the following line.
951 /*PHP5 patch*/$this = $user;
957 // else use the page methods defined in _PassUser.
963 function getAuthDbh () {
964 global $request; //, $DBParams, $DBAuthParams;
966 $dbh = $request->getDbh();
967 // session restauration doesn't re-connect to the database automatically,
968 // so dirty it here, to force a reconnect.
969 if (isset($this->_auth_dbi)) {
970 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
971 unset($this->_auth_dbi);
972 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
973 unset($this->_auth_dbi);
975 if (empty($this->_auth_dbi)) {
976 if ($dbh->getParam('dbtype') != 'SQL' and $dbh->getParam('dbtype') != 'ADODB')
978 if (empty($GLOBALS['DBAuthParams']))
980 if (!$dbh->getAuthParam('auth_dsn')) {
981 $dbh = $request->getDbh(); // use phpwiki database
982 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
983 $dbh = $request->getDbh(); // same phpwiki database
984 } else { // use another external database handle. needs PHP >= 4.1
985 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
986 $local_params['dsn'] = $local_params['auth_dsn'];
987 $dbh = WikiDB::open($local_params);
989 $this->_auth_dbi =& $dbh->_backend->_dbh;
991 return $this->_auth_dbi;
994 function _normalize_stmt_var($var, $oldstyle = false) {
995 static $valid_variables = array('userid','password','pref_blob','groupname');
996 // old-style: "'$userid'"
997 // new-style: '"\$userid"' or just "userid"
998 $new = str_replace(array("'",'"','\$','$'),'',$var);
999 if (!in_array($new,$valid_variables)) {
1000 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1003 return !$oldstyle ? "'$".$new."'" : '"\$'.$new.'"';
1006 // TODO: use it again for the auth and member tables
1007 function prepare ($stmt, $variables, $oldstyle = false) {
1009 $dbi = $request->getDbh();
1010 $this->getAuthDbh();
1011 // "'\$userid"' => '%s'
1012 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1013 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1015 if (is_array($variables)) {
1016 for ($i=0; $i < count($variables); $i++) {
1017 $var = $this->_normalize_stmt_var($variables[$i],$oldstyle);
1019 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1020 $variables[$i], $stmt), E_USER_WARNING);
1021 $variables[$i] = $var;
1022 if (!$var) $new[] = '';
1026 $var = $this->_normalize_stmt_var($variables,$oldstyle);
1028 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1029 $variables,$stmt), E_USER_WARNING);
1031 if (!$var) $new = '';
1034 $prefix = $dbi->getParam('prefix');
1035 // probably prefix table names if in same database
1036 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1037 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1039 if (!stristr($stmt, $prefix)) {
1040 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1041 trigger_error("TODO: Need to prefix the DBAuthParam tablename in config/config.ini:\n $stmt",
1043 $stmt = str_replace(array(" user "," pref "," member "),
1044 array(" ".$prefix."user ",
1045 " ".$prefix."prefs ",
1046 " ".$prefix."member "),$stmt);
1049 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1050 // Simple sprintf-style.
1051 $new_stmt = str_replace($variables,$new,$stmt);
1052 if ($new_stmt == $stmt) {
1054 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1055 $stmt), E_USER_WARNING);
1057 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1058 $stmt), E_USER_WARNING);
1059 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1065 function getPreferences() {
1066 if (!empty($this->_prefs->_method)) {
1067 if ($this->_prefs->_method == 'ADODB') {
1068 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
1069 return _AdoDbPassUser::getPreferences();
1070 } elseif ($this->_prefs->_method == 'SQL') {
1071 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
1072 return _PearDbPassUser::getPreferences();
1076 // We don't necessarily have to read the cookie first. Since
1077 // the user has a password, the prefs stored in the homepage
1078 // cannot be arbitrarily altered by other Bogo users.
1079 _AnonUser::getPreferences();
1080 // User may have deleted cookie, retrieve from his
1081 // PersonalPage if there is one.
1082 if ($this->_HomePagehandle) {
1083 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1084 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1085 //$this->_prefs = new UserPreferences($restored_from_page);
1086 return $this->_prefs;
1089 return $this->_prefs;
1092 function setPreferences($prefs, $id_only=false) {
1093 if (!empty($this->_prefs->_method)) {
1094 if ($this->_prefs->_method == 'ADODB') {
1095 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
1096 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1098 elseif ($this->_prefs->_method == 'SQL') {
1099 _PearDbPassUser::_PearDbPassUser($this->_userid,$prefs);
1100 return _PearDbPassUser::setPreferences($prefs, $id_only);
1103 if (_AnonUser::setPreferences($prefs, $id_only)) {
1104 // Encode only the _prefs array of the UserPreference object
1105 if ($this->_HomePagehandle and !$id_only) {
1106 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1112 function mayChangePass() {
1116 //The default method is getting the password from prefs.
1117 // child methods obtain $stored_password from external auth.
1118 function userExists() {
1119 //if ($this->_HomePagehandle) return true;
1120 $class = $this->nextClass();
1121 while ($user = new $class($this->_userid,$this->_prefs)) {
1122 //todo: with php5 comment the following line:
1123 /*PHP5 patch*/$this = $user;
1124 //UpgradeUser($this,$user);
1125 if ($user->userExists()) {
1128 // prevent endless loop. does this work on all PHP's?
1129 // it just has to set the classname, what it correctly does.
1130 $class = $user->nextClass();
1131 if ($class == "_ForbiddenPassUser")
1137 //The default method is getting the password from prefs.
1138 // child methods obtain $stored_password from external auth.
1139 function checkPass($submitted_password) {
1140 $stored_password = $this->_prefs->get('passwd');
1141 if ($this->_checkPass($submitted_password, $stored_password)) {
1142 $this->_level = WIKIAUTH_USER;
1143 return $this->_level;
1145 return $this->_tryNextPass($submitted_password);
1150 * The basic password checker for all PassUser objects.
1151 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1152 * Empty passwords are always false!
1153 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1154 * @see UserPreferences::set
1156 * DBPassUser password's have their own crypt definition.
1157 * That's why DBPassUser::checkPass() doesn't call this method, if
1158 * the db password method is 'plain', which means that the DB SQL
1159 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1160 * don't store plain passwords in the DB.
1162 * TODO: remove crypt() function check from config.php:396 ??
1164 function _checkPass($submitted_password, $stored_password) {
1165 if(!empty($submitted_password)) {
1166 if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1167 // With the EditMetaData plugin
1168 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."));
1171 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
1173 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
1174 // Verify against encrypted password.
1175 if (function_exists('crypt')) {
1176 if (crypt($submitted_password, $stored_password) == $stored_password )
1177 return true; // matches encrypted password
1182 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1183 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1189 // Verify against cleartext password.
1190 if ($submitted_password == $stored_password)
1193 // Check whether we forgot to enable ENCRYPTED_PASSWD
1194 if (function_exists('crypt')) {
1195 if (crypt($submitted_password, $stored_password) == $stored_password) {
1196 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1207 /** The default method is storing the password in prefs.
1208 * Child methods (DB,File) may store in external auth also, but this
1209 * must be explicitly enabled.
1210 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1212 function changePass($submitted_password) {
1213 $stored_password = $this->_prefs->get('passwd');
1214 // check if authenticated
1215 if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1216 $this->_prefs->set('passwd',$submitted_password);
1217 //update the storage (session, homepage, ...)
1218 $this->SetPreferences($this->_prefs);
1221 //Todo: return an error msg to the caller what failed?
1222 // same password or no privilege
1226 function _tryNextPass($submitted_password) {
1227 if (USER_AUTH_POLICY === 'strict') {
1228 $class = $this->nextClass();
1229 if ($user = new $class($this->_userid,$this->_prefs)) {
1230 if ($user->userExists()) {
1231 return $user->checkPass($submitted_password);
1235 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1236 $class = $this->nextClass();
1237 if ($user = new $class($this->_userid,$this->_prefs))
1238 return $user->checkPass($submitted_password);
1240 return $this->_level;
1243 function _tryNextUser() {
1244 if (USER_AUTH_POLICY === 'strict') {
1245 $class = $this->nextClass();
1246 while ($user = new $class($this->_userid,$this->_prefs)) {
1247 //todo: with php5 comment the following line:
1248 /*PHP5 patch*/$this = $user;
1249 //$user = UpgradeUser($this, $user);
1250 if ($user->userExists()) {
1253 $class = $this->nextClass();
1261 /** Without stored password. A _BogoLoginPassUser with password
1262 * is automatically upgraded to a PersonalPagePassUser.
1264 class _BogoLoginPassUser
1267 var $_authmethod = 'BogoLogin';
1268 function userExists() {
1269 if (isWikiWord($this->_userid)) {
1270 $this->_level = WIKIAUTH_BOGO;
1273 $this->_level = WIKIAUTH_ANON;
1278 /** A BogoLoginUser requires no password at all
1279 * But if there's one stored, we should prefer PersonalPage instead
1281 function checkPass($submitted_password) {
1282 if ($this->_prefs->get('passwd')) {
1283 $user = new _PersonalPagePassUser($this->_userid);
1284 if ($user->checkPass($submitted_password)) {
1285 //todo: with php5 comment the following line:
1286 /*PHP5 patch*/$this = $user;
1287 $user = UpgradeUser($this, $user);
1288 $this->_level = WIKIAUTH_USER;
1289 return $this->_level;
1291 $this->_level = WIKIAUTH_ANON;
1292 return $this->_level;
1295 if (isWikiWord($this->_userid)) {
1296 $this->_level = WIKIAUTH_BOGO;
1298 $this->_level = WIKIAUTH_ANON;
1300 return $this->_level;
1306 * This class is only to simplify the auth method dispatcher.
1307 * It inherits almost all all methods from _PassUser.
1309 class _PersonalPagePassUser
1312 var $_authmethod = 'PersonalPage';
1314 function userExists() {
1315 return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1318 /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1319 * BUT if the user already has a homepage with an empty password
1320 * stored, allow login but warn him to change it.
1322 function checkPass($submitted_password) {
1323 if ($this->userExists()) {
1324 $stored_password = $this->_prefs->get('passwd');
1325 if (empty($stored_password)) {
1326 trigger_error(sprintf(
1327 _("\nYou stored an empty password in your '%s' page.\n").
1328 _("Your access permissions are only for a BogoUser.\n").
1329 _("Please set your password in UserPreferences."),
1330 $this->_userid), E_USER_WARNING);
1331 $this->_level = WIKIAUTH_BOGO;
1332 return $this->_level;
1334 if ($this->_checkPass($submitted_password, $stored_password))
1335 return ($this->_level = WIKIAUTH_USER);
1336 return _PassUser::checkPass($submitted_password);
1338 return WIKIAUTH_ANON;
1343 * We have two possibilities here.
1344 * 1) The webserver location is already HTTP protected (usually Basic). Then just
1345 * use the username and do nothing
1346 * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1347 * by sending a 401 error and let the client display the login dialog.
1348 * This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1349 * since the other methods cannot be transparently called after this enforced
1351 * Try the available auth methods (most likely Bogo) and sent this header back.
1352 * header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1354 class _HttpAuthPassUser
1357 function _HttpAuthPassUser($UserName='',$prefs=false) {
1358 if ($prefs) $this->_prefs = $prefs;
1359 if (!isset($this->_prefs->_method))
1360 _PassUser::_PassUser($UserName);
1361 if ($UserName) $this->_userid = $UserName;
1362 $this->_authmethod = 'HttpAuth';
1363 if ($this->userExists())
1366 return $GLOBALS['ForbiddenUser'];
1369 function _http_username() {
1370 if (!isset($_SERVER))
1371 $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
1372 if (!empty($_SERVER['PHP_AUTH_USER']))
1373 return $_SERVER['PHP_AUTH_USER'];
1374 if (!empty($_SERVER['REMOTE_USER']))
1375 return $_SERVER['REMOTE_USER'];
1376 if (!empty($GLOBALS['HTTP_ENV_VARS']['REMOTE_USER']))
1377 return $GLOBALS['HTTP_ENV_VARS']['REMOTE_USER'];
1378 if (!empty($GLOBALS['REMOTE_USER']))
1379 return $GLOBALS['REMOTE_USER'];
1383 //force http auth authorization
1384 function userExists() {
1385 // todo: older php's
1386 $username = $this->_http_username();
1387 if (empty($username) or strtolower($username) != strtolower($this->_userid)) {
1388 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1389 header('HTTP/1.0 401 Unauthorized');
1392 $this->_userid = $username;
1393 $this->_level = WIKIAUTH_USER;
1397 function checkPass($submitted_password) {
1398 return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1401 function mayChangePass() {
1405 // hmm... either the server dialog or our own.
1406 function PrintLoginForm (&$request, $args, $fail_message = false,
1407 $seperate_page = true) {
1408 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1409 header('HTTP/1.0 401 Unauthorized');
1416 * Support reuse of existing user session from another application.
1417 * You have to define which session variable holds the userid, and
1418 * at what level is that user then. 1: BogoUser, 2: PassUser
1419 * define('AUTH_SESS_USER','userid');
1420 * define('AUTH_SESS_LEVEL',2);
1422 class _SessionPassUser
1425 function _SessionPassUser($UserName='',$prefs=false) {
1426 if ($prefs) $this->_prefs = $prefs;
1427 if (!defined("AUTH_SESS_USER") or !defined("AUTH_SESS_LEVEL")) {
1429 "AUTH_SESS_USER or AUTH_SESS_LEVEL is not defined for the SessionPassUser method",
1433 $sess =& $GLOBALS['HTTP_SESSION_VARS'];
1434 // user hash: "[user][userid]" or object "user->id"
1435 if (strstr(AUTH_SESS_USER,"][")) {
1436 $sess = $GLOBALS['HTTP_SESSION_VARS'];
1437 // recurse into hashes: "[user][userid]", sess = sess[user] => sess = sess[userid]
1438 foreach (split("][",AUTH_SESS_USER) as $v) {
1439 $v = str_replace(array("[","]"),'',$v);
1442 $this->_userid = $sess;
1443 } elseif (strstr(AUTH_SESS_USER,"->")) {
1444 // object "user->id" (no objects inside hashes supported!)
1445 list($obj,$key) = split("->",AUTH_SESS_USER);
1446 $this->_userid = $sess[$obj]->$key;
1448 $this->_userid = $sess[AUTH_SESS_USER];
1450 if (!isset($this->_prefs->_method))
1451 _PassUser::_PassUser($this->_userid);
1452 $this->_level = AUTH_SESS_LEVEL;
1453 $this->_authmethod = 'Session';
1455 function userExists() {
1456 return !empty($this->_userid);
1458 function checkPass($submitted_password) {
1459 return $this->userExists() and $this->_level;
1461 function mayChangePass() {
1467 * Baseclass for PearDB and ADODB PassUser's
1468 * Authenticate against a database, to be able to use shared users.
1469 * internal: no different $DbAuthParams['dsn'] defined, or
1470 * external: different $DbAuthParams['dsn']
1471 * The magic is done in the symbolic SQL statements in config/config.ini, similar to
1474 * We support only the SQL and ADODB backends.
1475 * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages,
1476 * not for auth stuff. If one would like to use e.g. dba for auth, he should
1477 * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
1478 * (Not supported yet, since we require SQL. SQLite would make since when
1479 * it will come to PHP)
1481 * @tables: user, pref
1483 * Preferences are handled in the parent class _PassUser, because the
1484 * previous classes may also use DB pref_select and pref_update.
1486 * Flat files auth is handled by the auth method "File".
1491 var $_authselect, $_authupdate, $_authcreate;
1493 // This can only be called from _PassUser, because the parent class
1494 // sets the auth_dbi and pref methods, before this class is initialized.
1495 function _DbPassUser($UserName='',$prefs=false) {
1496 if (!$this->_prefs) {
1497 if ($prefs) $this->_prefs = $prefs;
1499 if (!isset($this->_prefs->_method))
1500 _PassUser::_PassUser($UserName);
1501 elseif (!$this->isValidName($UserName)) {
1502 trigger_error(_("Invalid username."),E_USER_WARNING);
1505 $this->_authmethod = 'Db';
1506 //$this->getAuthDbh();
1507 //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1508 $dbi =& $GLOBALS['request']->_dbi;
1509 $dbtype = $dbi->getParam('dbtype');
1510 if ($dbtype == 'ADODB') {
1511 if (check_php_version(5))
1512 return new _AdoDbPassUser($UserName,$this->_prefs);
1514 $user = new _AdoDbPassUser($UserName,$this->_prefs);
1515 //todo: with php5 comment the following line:
1516 /*PHP5 patch*/$this = $user;
1520 elseif ($dbtype == 'SQL') {
1521 if (check_php_version(5))
1522 return new _PearDbPassUser($UserName,$this->_prefs);
1524 $user = new _PearDbPassUser($UserName,$this->_prefs);
1525 //todo: with php5 comment the following line:
1526 /*PHP5 patch*/$this = $user;
1533 function mayChangePass() {
1534 return !isset($this->_authupdate);
1539 class _PearDbPassUser
1543 * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1544 * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1550 var $_authmethod = 'PearDb';
1551 function _PearDbPassUser($UserName='',$prefs=false) {
1552 //global $DBAuthParams;
1553 if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1554 if ($prefs) $this->_prefs = $prefs;
1556 if (!isset($this->_prefs->_method))
1557 _PassUser::_PassUser($UserName);
1558 elseif (!$this->isValidName($UserName)) {
1559 trigger_error(_("Invalid username."), E_USER_WARNING);
1562 $this->_userid = $UserName;
1563 // make use of session data. generally we only initialize this every time,
1564 // but do auth checks only once
1565 $this->_auth_crypt_method = $GLOBALS['request']->_dbi->getAuthParam('auth_crypt_method');
1569 function getPreferences() {
1570 // override the generic slow method here for efficiency and not to
1571 // clutter the homepage metadata with prefs.
1572 _AnonUser::getPreferences();
1573 $this->getAuthDbh();
1574 if (isset($this->_prefs->_select)) {
1575 $dbh = &$this->_auth_dbi;
1576 $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1577 // patched by frederik@pandora.be
1578 $prefs = $db_result->fetchRow();
1579 $prefs_blob = @$prefs["prefs"];
1580 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1581 $updated = $this->_prefs->updatePrefs($restored_from_db);
1582 //$this->_prefs = new UserPreferences($restored_from_db);
1583 return $this->_prefs;
1586 if ($this->_HomePagehandle) {
1587 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1588 $updated = $this->_prefs->updatePrefs($restored_from_page);
1589 //$this->_prefs = new UserPreferences($restored_from_page);
1590 return $this->_prefs;
1593 return $this->_prefs;
1596 function setPreferences($prefs, $id_only=false) {
1597 // if the prefs are changed
1598 if ($count = _AnonUser::setPreferences($prefs, 1)) {
1600 //$user = $request->_user;
1601 //unset($user->_auth_dbi);
1602 // this must be done in $request->_setUser, not here!
1603 //$request->setSessionVar('wiki_user', $user);
1604 $this->getAuthDbh();
1605 $packed = $this->_prefs->store();
1606 if (!$id_only and isset($this->_prefs->_update)) {
1607 $dbh = &$this->_auth_dbi;
1608 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1609 $dbh->quote($packed),
1610 $dbh->quote($this->_userid)));
1612 if ($this->_HomePagehandle and $this->_HomePagehandle->get('pref'))
1613 $this->_HomePagehandle->set('pref', '');
1615 //store prefs in homepage, not in cookie
1616 if ($this->_HomePagehandle and !$id_only)
1617 $this->_HomePagehandle->set('pref', $packed);
1619 return $count; //count($this->_prefs->unpack($packed));
1624 function userExists() {
1625 //global $DBAuthParams;
1626 $this->getAuthDbh();
1627 $dbh = &$this->_auth_dbi;
1628 if (!$dbh) { // needed?
1629 return $this->_tryNextUser();
1631 if (!$this->isValidName()) {
1632 return $this->_tryNextUser();
1634 $dbi =& $GLOBALS['request']->_dbi;
1635 // Prepare the configured auth statements
1636 if ($dbi->getAuthParam('auth_check') and empty($this->_authselect)) {
1637 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1638 array("userid", "password"));
1640 if (empty($this->_authselect))
1641 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1642 'DBAUTH_AUTH_CHECK', 'SQL'),
1644 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1645 if ($this->_auth_crypt_method == 'crypt') {
1646 $rs = $dbh->query(sprintf($this->_authselect, $dbh->quote($this->_userid)));
1651 if (! $dbi->getAuthParam('auth_user_exists'))
1652 trigger_error(fmt("%s is missing",'DBAUTH_AUTH_USER_EXISTS'),
1654 $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'),"userid");
1655 $rs = $dbh->query(sprintf($this->_authcheck, $dbh->quote($this->_userid)));
1659 // maybe the user is allowed to create himself. Generally not wanted in
1660 // external databases, but maybe wanted for the wiki database, for performance
1662 if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) {
1663 $this->_authcreate = $this->prepare($dbh->getAuthParam('auth_create'),
1664 array("userid", "password"));
1666 if (!empty($this->_authcreate)) {
1667 $dbh->simpleQuery(sprintf($this->_authcreate,
1668 $dbh->quote($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1669 $dbh->quote($this->_userid)
1673 return $this->_tryNextUser();
1676 function checkPass($submitted_password) {
1677 //global $DBAuthParams;
1678 $this->getAuthDbh();
1679 if (!$this->_auth_dbi) { // needed?
1680 return $this->_tryNextPass($submitted_password);
1682 if (!$this->isValidName()) {
1683 return $this->_tryNextPass($submitted_password);
1685 if (!isset($this->_authselect))
1686 $this->userExists();
1687 if (!isset($this->_authselect))
1688 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1689 'DBAUTH_AUTH_CHECK','SQL'),
1692 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1693 $dbh = &$this->_auth_dbi;
1694 if ($this->_auth_crypt_method == 'crypt') {
1695 $stored_password = $dbh->getOne(sprintf($this->_authselect, $dbh->quote($this->_userid)));
1696 $result = $this->_checkPass($submitted_password, $stored_password);
1698 $okay = $dbh->getOne(sprintf($this->_authselect,
1699 $dbh->quote($submitted_password),
1700 $dbh->quote($this->_userid)));
1701 $result = !empty($okay);
1705 $this->_level = WIKIAUTH_USER;
1706 return $this->_level;
1708 return $this->_tryNextPass($submitted_password);
1712 function mayChangePass() {
1713 return $GLOBALS['request']->_dbi->getAuthParam('auth_update');
1716 function storePass($submitted_password) {
1717 if (!$this->isValidName()) {
1720 $this->getAuthDbh();
1721 $dbh = &$this->_auth_dbi;
1722 $dbi =& $GLOBALS['request']->_dbi;
1723 if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) {
1724 $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'),
1725 array("userid", "password"));
1727 if (empty($this->_authupdate)) {
1728 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1729 'DBAUTH_AUTH_UPDATE','SQL'),
1734 if ($this->_auth_crypt_method == 'crypt') {
1735 if (function_exists('crypt'))
1736 $submitted_password = crypt($submitted_password);
1738 $dbh->simpleQuery(sprintf($this->_authupdate,
1739 $dbh->quote($submitted_password),
1740 $dbh->quote($this->_userid)
1745 class _AdoDbPassUser
1749 * Simple sprintf, no prepare.
1751 * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster
1752 * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1754 * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1759 var $_authmethod = 'AdoDb';
1760 function _AdoDbPassUser($UserName='',$prefs=false) {
1761 if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1762 if ($prefs) $this->_prefs = $prefs;
1763 if (!isset($this->_prefs->_method))
1764 _PassUser::_PassUser($UserName);
1766 if (!$this->isValidName($UserName)) {
1767 trigger_error(_("Invalid username."),E_USER_WARNING);
1770 $this->_userid = $UserName;
1771 $this->getAuthDbh();
1772 $this->_auth_crypt_method = $GLOBALS['request']->_dbi->getAuthParam('auth_crypt_method');
1773 // Don't prepare the configured auth statements anymore
1777 function getPreferences() {
1778 // override the generic slow method here for efficiency
1779 _AnonUser::getPreferences();
1780 $this->getAuthDbh();
1781 if (isset($this->_prefs->_select)) {
1782 $dbh = & $this->_auth_dbi;
1783 $rs = $dbh->Execute(sprintf($this->_prefs->_select, $dbh->qstr($this->_userid)));
1787 $prefs_blob = @$rs->fields['prefs'];
1789 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1790 $updated = $this->_prefs->updatePrefs($restored_from_db);
1791 //$this->_prefs = new UserPreferences($restored_from_db);
1792 return $this->_prefs;
1796 if ($this->_HomePagehandle) {
1797 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1798 $updated = $this->_prefs->updatePrefs($restored_from_page);
1799 //$this->_prefs = new UserPreferences($restored_from_page);
1800 return $this->_prefs;
1803 return $this->_prefs;
1806 function setPreferences($prefs, $id_only=false) {
1807 // if the prefs are changed
1808 if (_AnonUser::setPreferences($prefs, 1)) {
1810 $packed = $this->_prefs->store();
1811 //$user = $request->_user;
1812 //unset($user->_auth_dbi);
1813 if (!$id_only and isset($this->_prefs->_update)) {
1814 $this->getAuthDbh();
1815 $dbh = &$this->_auth_dbi;
1816 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1817 $dbh->qstr($packed),
1818 $dbh->qstr($this->_userid)));
1819 $db_result->Close();
1821 if ($this->_HomePagehandle and $this->_HomePagehandle->get('pref'))
1822 $this->_HomePagehandle->set('pref', '');
1824 //store prefs in homepage, not in cookie
1825 if ($this->_HomePagehandle and !$id_only)
1826 $this->_HomePagehandle->set('pref', $packed);
1828 return count($this->_prefs->unpack($packed));
1833 function userExists() {
1834 $this->getAuthDbh();
1835 $dbh = &$this->_auth_dbi;
1836 if (!$dbh) { // needed?
1837 return $this->_tryNextUser();
1839 if (!$this->isValidName()) {
1840 return $this->_tryNextUser();
1842 $dbi =& $GLOBALS['request']->_dbi;
1843 if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) {
1844 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1845 array("userid","password"));
1847 if (empty($this->_authselect))
1848 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1849 'DBAUTH_AUTH_CHECK', 'ADODB'),
1851 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1852 if ($this->_auth_crypt_method == 'crypt') {
1853 $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid)));
1862 if (! $dbi->getAuthParam('auth_user_exists'))
1863 trigger_error(fmt("%s is missing", 'DBAUTH_AUTH_USER_EXISTS'),
1865 $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'), 'userid');
1866 $rs = $dbh->Execute(sprintf($this->_authcheck, $dbh->qstr($this->_userid)));
1874 // maybe the user is allowed to create himself. Generally not wanted in
1875 // external databases, but maybe wanted for the wiki database, for performance
1877 if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) {
1878 $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'),
1879 array("userid", "password"));
1881 if (!empty($this->_authcreate) and
1882 isset($GLOBALS['HTTP_POST_VARS']['auth']) and
1883 isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd']))
1885 $dbh->Execute(sprintf($this->_authcreate,
1886 $dbh->qstr($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1887 $dbh->qstr($this->_userid)));
1891 return $this->_tryNextUser();
1894 function checkPass($submitted_password) {
1895 //global $DBAuthParams;
1896 $this->getAuthDbh();
1897 if (!$this->_auth_dbi) { // needed?
1898 return $this->_tryNextPass($submitted_password);
1900 if (!$this->isValidName()) {
1901 return $this->_tryNextPass($submitted_password);
1903 $dbh =& $this->_auth_dbi;
1904 $dbi =& $GLOBALS['request']->_dbi;
1905 if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) {
1906 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1907 array("userid", "password"));
1909 if (!isset($this->_authselect))
1910 $this->userExists();
1911 if (!isset($this->_authselect))
1912 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1913 'DBAUTH_AUTH_CHECK', 'ADODB'),
1915 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1916 if ($this->_auth_crypt_method == 'crypt') {
1917 $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid)));
1919 $stored_password = $rs->fields['password'];
1921 $result = $this->_checkPass($submitted_password, $stored_password);
1927 $rs = $dbh->Execute(sprintf($this->_authselect,
1928 $dbh->qstr($submitted_password),
1929 $dbh->qstr($this->_userid)));
1930 if (isset($rs->fields['ok']))
1931 $okay = $rs->fields['ok'];
1932 elseif (isset($rs->fields[1]))
1933 $okay = $rs->fields[1];
1935 $okay = reset($rs->fields);
1938 $result = !empty($okay);
1942 $this->_level = WIKIAUTH_USER;
1943 return $this->_level;
1945 return $this->_tryNextPass($submitted_password);
1949 function mayChangePass() {
1950 return $GLOBALS['request']->_dbi->getAuthParam('auth_update');
1953 function storePass($submitted_password) {
1954 $this->getAuthDbh();
1955 $dbh = &$this->_auth_dbi;
1956 $dbi =& $GLOBALS['request']->_dbi;
1957 if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) {
1958 $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'),
1959 array("userid", "password"));
1961 if (!isset($this->_authupdate)) {
1962 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1963 'DBAUTH_AUTH_UPDATE', 'ADODB'),
1968 if ($this->_auth_crypt_method == 'crypt') {
1969 if (function_exists('crypt'))
1970 $submitted_password = crypt($submitted_password);
1972 $rs = $dbh->Execute(sprintf($this->_authupdate,
1973 $dbh->qstr($submitted_password),
1974 $dbh->qstr($this->_userid)
1984 * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in config/config.ini
1986 * Preferences are handled in _PassUser
1989 function checkPass($submitted_password) {
1990 global $LDAP_SET_OPTION;
1992 $this->_authmethod = 'LDAP';
1993 $userid = $this->_userid;
1994 if (!$this->isValidName()) {
1995 return $this->_tryNextPass($submitted_password);
1997 if (strstr($userid,'*')) {
1998 trigger_error(fmt("Invalid username '%s' for LDAP Auth",$userid),E_USER_WARNING);
1999 return WIKIAUTH_FORBIDDEN;
2002 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
2003 if (!empty($LDAP_SET_OPTION)) {
2004 foreach ($LDAP_SET_OPTION as $key => $value) {
2005 if (is_string($key) and defined($key))
2006 $key = constant($key);
2007 ldap_set_option($ldap,$key,$value);
2010 if (defined('LDAP_AUTH_USER'))
2011 if (defined('LDAP_AUTH_PASSWORD'))
2012 // Windows Active Directory Server is strict
2013 $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD);
2015 $r = @ldap_bind($ldap,LDAP_AUTH_USER);
2017 $r = @ldap_bind($ldap); // this is an anonymous bind
2019 // Need to set the right root search information. see ../index.php
2020 $st_search = defined('LDAP_SEARCH_FIELD')
2021 ? LDAP_SEARCH_FIELD."=$userid"
2023 $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
2024 $info = ldap_get_entries($ldap, $sr);
2025 // there may be more hits with this userid.
2026 // of course it would be better to narrow down the BASE_DN
2027 for ($i = 0; $i < $info["count"]; $i++) {
2028 $dn = $info[$i]["dn"];
2029 // The password is still plain text.
2030 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
2031 // ldap_bind will return TRUE if everything matches
2033 $this->_level = WIKIAUTH_USER;
2034 return $this->_level;
2038 trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST),
2043 return $this->_tryNextPass($submitted_password);
2046 function userExists() {
2047 global $LDAP_SET_OPTION;
2049 $userid = $this->_userid;
2050 if (strstr($userid,'*')) {
2051 trigger_error(fmt("Invalid username '%s' for LDAP Auth",$userid),E_USER_WARNING);
2052 return WIKIAUTH_FORBIDDEN;
2054 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
2055 if (!empty($LDAP_SET_OPTION)) {
2056 foreach ($LDAP_SET_OPTION as $key => $value) {
2057 if (is_string($key) and defined($key))
2058 $key = constant($key);
2059 ldap_set_option($ldap,$key,$value);
2062 if (defined('LDAP_AUTH_USER'))
2063 if (defined('LDAP_AUTH_PASSWORD'))
2064 // Windows Active Directory Server is strict
2065 $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD);
2067 $r = @ldap_bind($ldap,LDAP_AUTH_USER);
2069 $r = @ldap_bind($ldap); // this is an anonymous bind
2071 // Need to set the right root search information. see ../index.php
2072 $st_search = defined('LDAP_SEARCH_FIELD')
2073 ? LDAP_SEARCH_FIELD."=$userid"
2075 $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
2076 $info = ldap_get_entries($ldap, $sr);
2078 if ($info["count"] > 0) {
2083 trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
2086 return $this->_tryNextUser();
2089 function mayChangePass() {
2098 * Define the var IMAP_AUTH_HOST in config/config.ini (with port probably)
2100 * Preferences are handled in _PassUser
2103 function checkPass($submitted_password) {
2104 if (!$this->isValidName()) {
2105 return $this->_tryNextPass($submitted_password);
2107 $userid = $this->_userid;
2108 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
2109 $userid, $submitted_password, OP_HALFOPEN );
2112 $this->_authmethod = 'IMAP';
2113 $this->_level = WIKIAUTH_USER;
2114 return $this->_level;
2116 trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
2119 return $this->_tryNextPass($submitted_password);
2122 //CHECKME: this will not be okay for the auth policy strict
2123 function userExists() {
2125 if (checkPass($this->_prefs->get('passwd')))
2128 return $this->_tryNextUser();
2131 function mayChangePass() {
2138 extends _IMAPPassUser {
2140 * Define the var POP3_AUTH_HOST in config/config.ini
2141 * Preferences are handled in _PassUser
2143 function checkPass($submitted_password) {
2144 if (!$this->isValidName()) {
2145 return $this->_tryNextPass($submitted_password);
2147 $userid = $this->_userid;
2148 $pass = $submitted_password;
2149 $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost:110';
2150 if (defined('POP3_AUTH_PORT'))
2151 $port = POP3_AUTH_PORT;
2152 elseif (strstr($host,':')) {
2153 list(,$port) = split(':',$host);
2158 $fp = fsockopen($host, $port, $errno, $errstr, 10);
2160 // Get welcome string
2161 $line = fgets($fp, 1024);
2162 if (! strncmp("+OK ", $line, 4)) {
2164 fputs($fp, "user $userid\n");
2166 $line = fgets($fp, 1024);
2167 if (! strncmp("+OK ", $line, 4)) {
2169 fputs($fp, "pass $pass\n");
2171 $line = fgets($fp, 1024);
2172 if (! strncmp("+OK ", $line, 4)) {
2177 // quit the connection
2178 fputs($fp, "quit\n");
2179 // Get the sayonara message
2180 $line = fgets($fp, 1024);
2183 trigger_error(_("Couldn't connect to %s","POP3_AUTH_HOST ".$host.':'.$port),
2186 $this->_authmethod = 'POP3';
2188 $this->_level = WIKIAUTH_USER;
2190 $this->_level = WIKIAUTH_ANON;
2192 return $this->_level;
2199 * Check users defined in a .htaccess style file
2200 * username:crypt\n...
2202 * Preferences are handled in _PassUser
2205 var $_file, $_may_change;
2207 // This can only be called from _PassUser, because the parent class
2208 // sets the pref methods, before this class is initialized.
2209 function _FilePassUser($UserName='', $prefs=false, $file='') {
2210 if (!$this->_prefs and isa($this, "_FilePassUser")) {
2211 if ($prefs) $this->_prefs = $prefs;
2212 if (!isset($this->_prefs->_method))
2213 _PassUser::_PassUser($UserName);
2215 $this->_userid = $UserName;
2216 // read the .htaccess style file. We use our own copy of the standard pear class.
2217 //include_once 'lib/pear/File_Passwd.php';
2218 $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
2219 if (empty($file) and defined('AUTH_USER_FILE'))
2220 $file = AUTH_USER_FILE;
2221 include_once(dirname(__FILE__)."/pear/File_Passwd.php"); // same style as in main.php
2222 // "__PHP_Incomplete_Class"
2223 if (!empty($file) or empty($this->_file) or !isa($this->_file,"File_Passwd"))
2224 $this->_file = new File_Passwd($file, false, $file.'.lock');
2230 function mayChangePass() {
2231 return $this->_may_change;
2234 function userExists() {
2235 if (!$this->isValidName()) {
2236 return $this->_tryNextUser();
2238 $this->_authmethod = 'File';
2239 if (isset($this->_file->users[$this->_userid]))
2242 return $this->_tryNextUser();
2245 function checkPass($submitted_password) {
2246 if (!$this->isValidName()) {
2247 return $this->_tryNextPass($submitted_password);
2249 //include_once 'lib/pear/File_Passwd.php';
2250 if ($this->_file->verifyPassword($this->_userid, $submitted_password)) {
2251 $this->_authmethod = 'File';
2252 $this->_level = WIKIAUTH_USER;
2253 return $this->_level;
2256 return $this->_tryNextPass($submitted_password);
2259 function storePass($submitted_password) {
2260 if (!$this->isValidName()) {
2263 if ($this->_may_change) {
2264 $this->_file = new File_Passwd($this->_file->_filename, true, $this->_file->_filename.'.lock');
2265 $result = $this->_file->modUser($this->_userid,$submitted_password);
2266 $this->_file->close();
2267 $this->_file = new File_Passwd($this->_file->_filename, false);
2276 * Insert more auth classes here...
2277 * For example a customized db class for another db connection
2278 * or a socket-based auth server.
2284 * For security, this class should not be extended. Instead, extend
2285 * from _PassUser (think of this as unix "root").
2287 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
2288 * Other members of the Administrators group must raise their level otherwise somehow.
2289 * Currently every member is a AdminUser, which will not work for the various
2295 function mayChangePass() {
2298 function checkPass($submitted_password) {
2299 if ($this->_userid == ADMIN_USER)
2300 $stored_password = ADMIN_PASSWD;
2302 return $this->_tryNextPass($submitted_password);
2303 // TODO: safety check if really member of the ADMIN group?
2304 $stored_password = $this->_pref->get('passwd');
2306 if ($this->_checkPass($submitted_password, $stored_password)) {
2307 $this->_level = WIKIAUTH_ADMIN;
2308 return $this->_level;
2310 return $this->_tryNextPass($submitted_password);
2311 //$this->_level = WIKIAUTH_ANON;
2312 //return $this->_level;
2316 function storePass($submitted_password) {
2321 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2323 * Various data classes for the preference types,
2324 * to support get, set, sanify (range checking, ...)
2325 * update() will do the neccessary side-effects if a
2326 * setting gets changed (theme, language, ...)
2329 class _UserPreference
2333 function _UserPreference ($default_value) {
2334 $this->default_value = $default_value;
2337 function sanify ($value) {
2338 return (string)$value;
2341 function get ($name) {
2342 if (isset($this->{$name}))
2343 return $this->{$name};
2345 return $this->default_value;
2348 function getraw ($name) {
2349 if (!empty($this->{$name}))
2350 return $this->{$name};
2353 // stores the value as $this->$name, and not as $this->value (clever?)
2354 function set ($name, $value) {
2356 $value = $this->sanify($value);
2357 if ($this->get($name) != $value) {
2358 $this->update($value);
2361 if ($value != $this->default_value) {
2362 $this->{$name} = $value;
2364 unset($this->{$name});
2369 // default: no side-effects
2370 function update ($value) {
2375 class _UserPreference_numeric
2376 extends _UserPreference
2378 function _UserPreference_numeric ($default, $minval = false,
2380 $this->_UserPreference((double)$default);
2381 $this->_minval = (double)$minval;
2382 $this->_maxval = (double)$maxval;
2385 function sanify ($value) {
2386 $value = (double)$value;
2387 if ($this->_minval !== false && $value < $this->_minval)
2388 $value = $this->_minval;
2389 if ($this->_maxval !== false && $value > $this->_maxval)
2390 $value = $this->_maxval;
2395 class _UserPreference_int
2396 extends _UserPreference_numeric
2398 function _UserPreference_int ($default, $minval = false, $maxval = false) {
2399 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
2402 function sanify ($value) {
2403 return (int)parent::sanify((int)$value);
2407 class _UserPreference_bool
2408 extends _UserPreference
2410 function _UserPreference_bool ($default = false) {
2411 $this->_UserPreference((bool)$default);
2414 function sanify ($value) {
2415 if (is_array($value)) {
2416 /* This allows for constructs like:
2418 * <input type="hidden" name="pref[boolPref][]" value="0" />
2419 * <input type="checkbox" name="pref[boolPref][]" value="1" />
2421 * (If the checkbox is not checked, only the hidden input
2422 * gets sent. If the checkbox is sent, both inputs get
2425 foreach ($value as $val) {
2431 return (bool) $value;
2435 class _UserPreference_language
2436 extends _UserPreference
2438 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
2439 $this->_UserPreference($default);
2442 // FIXME: check for valid locale
2443 function sanify ($value) {
2444 // Revert to DEFAULT_LANGUAGE if user does not specify
2445 // language in UserPreferences or chooses <system language>.
2446 if ($value == '' or empty($value))
2447 $value = DEFAULT_LANGUAGE;
2449 return (string) $value;
2452 function update ($newvalue) {
2453 if (! $this->_init ) {
2454 // invalidate etag to force fresh output
2455 $GLOBALS['request']->setValidators(array('%mtime' => false));
2456 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
2461 class _UserPreference_theme
2462 extends _UserPreference
2464 function _UserPreference_theme ($default = THEME) {
2465 $this->_UserPreference($default);
2468 function sanify ($value) {
2469 if (!empty($value) and FindFile($this->_themefile($value)))
2471 return $this->default_value;
2474 function update ($newvalue) {
2476 // invalidate etag to force fresh output
2477 if (! $this->_init )
2478 $GLOBALS['request']->setValidators(array('%mtime' => false));
2480 include_once($this->_themefile($newvalue));
2482 include_once($this->_themefile(THEME));
2485 function _themefile ($theme) {
2486 return "themes/$theme/themeinfo.php";
2490 class _UserPreference_notify
2491 extends _UserPreference
2493 function sanify ($value) {
2497 return $this->default_value;
2500 /** update to global user prefs: side-effect on set notify changes
2501 * use a global_data notify hash:
2502 * notify = array('pagematch' => array(userid => ('email' => mail,
2503 * 'verified' => 0|1),
2507 function update ($value) {
2508 if (!empty($this->_init)) return;
2509 $dbh = $GLOBALS['request']->getDbh();
2510 $notify = $dbh->get('notify');
2515 // expand to existing pages only or store matches?
2516 // for now we store (glob-style) matches which is easier for the user
2517 $pages = $this->_page_split($value);
2518 // Limitation: only current user.
2519 $user = $GLOBALS['request']->getUser();
2520 if (!$user or !method_exists($user,'UserName')) return;
2521 // This fails with php5 and a WIKI_ID cookie:
2522 $userid = $user->UserName();
2523 $email = $user->_prefs->get('email');
2524 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
2525 // check existing notify hash and possibly delete pages for email
2526 if (!empty($data)) {
2527 foreach ($data as $page => $users) {
2528 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
2529 unset($data[$page][$userid]);
2531 if (count($data[$page]) == 0)
2532 unset($data[$page]);
2535 // add the new pages
2536 if (!empty($pages)) {
2537 foreach ($pages as $page) {
2538 if (!isset($data[$page]))
2539 $data[$page] = array();
2540 if (!isset($data[$page][$userid])) {
2541 // should we really store the verification notice here or
2542 // check it dynamically at every page->save?
2544 $data[$page][$userid] = array('email' => $email,
2545 'verified' => $verified);
2547 $data[$page][$userid] = array('email' => $email);
2552 // store users changes
2553 $dbh->set('notify',$data);
2556 /** split the user-given comma or whitespace delimited pagenames
2559 function _page_split($value) {
2560 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
2564 class _UserPreference_email
2565 extends _UserPreference
2567 function sanify($value) {
2568 // check for valid email address
2569 if ($this->get('email') == $value and $this->getraw('emailVerified'))
2572 if ($value == 1 or $value === true)
2574 list($ok,$msg) = ValidateMail($value,'noconnect');
2578 trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
2579 return $this->default_value;
2583 /** Side-effect on email changes:
2584 * Send a verification mail or for now just a notification email.
2585 * For true verification (value = 2), we'd need a mailserver hook.
2587 function update($value) {
2588 if (!empty($this->_init)) return;
2589 $verified = $this->getraw('emailVerified');
2591 if (($value == 1 or $value === true) and $verified)
2593 if (!empty($value) and !$verified) {
2594 list($ok,$msg) = ValidateMail($value);
2595 if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
2596 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
2597 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true))))
2598 $this->set('emailVerified',1);
2603 /** Check for valid email address
2604 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
2606 function ValidateMail($email, $noconnect=false) {
2607 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
2609 // well, technically ".a.a.@host.com" is also valid
2610 if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
2612 $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
2616 return array(true,sprintf(_("E-Mail address '%s' is properly formatted"), $email));
2618 list ( $Username, $Domain ) = split ("@",$email);
2619 //Todo: getmxrr workaround on windows or manual input field to verify it manually
2620 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
2621 $ConnectAddress = $MXHost[0];
2623 $ConnectAddress = $Domain;
2625 $Connect = fsockopen ( $ConnectAddress, 25 );
2627 if (ereg("^220", $Out = fgets($Connect, 1024))) {
2628 fputs ($Connect, "HELO $HTTP_HOST\r\n");
2629 $Out = fgets ( $Connect, 1024 );
2630 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
2631 $From = fgets ( $Connect, 1024 );
2632 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
2633 $To = fgets ($Connect, 1024);
2634 fputs ($Connect, "QUIT\r\n");
2636 if (!ereg ("^250", $From)) {
2638 $result[1]="Server rejected address: ". $From;
2641 if (!ereg ( "^250", $To )) {
2643 $result[1]="Server rejected address: ". $To;
2648 $result[1] = "No response from server";
2653 $result[1]="Can not connect E-Mail server.";
2657 $result[1]="E-Mail address '$email' appears to be valid.";
2659 } // end of function
2661 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2666 * This object holds the $request->_prefs subobjects.
2667 * A simple packed array of non-default values get's stored as cookie,
2668 * homepage, or database, which are converted to the array of
2670 * We don't store the objects, because otherwise we will
2671 * not be able to upgrade any subobject. And it's a waste of space also.
2674 class UserPreferences
2676 function UserPreferences($saved_prefs = false) {
2677 // userid stored too, to ensure the prefs are being loaded for
2678 // the correct (currently signing in) userid if stored in a
2680 // Update: for db prefs we disallow passwd.
2681 // userid is needed for pref reflexion. current pref must know its username,
2682 // if some app needs prefs from different users, different from current user.
2685 'userid' => new _UserPreference(''),
2686 'passwd' => new _UserPreference(''),
2687 'autologin' => new _UserPreference_bool(),
2688 //'emailVerified' => new _UserPreference_emailVerified(),
2689 //fixed: store emailVerified as email parameter, 1.3.8
2690 'email' => new _UserPreference_email(''),
2691 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
2692 'theme' => new _UserPreference_theme(THEME),
2693 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
2694 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2696 EDITWIDTH_MAX_COLS),
2697 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
2698 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2699 EDITHEIGHT_MIN_ROWS,
2700 EDITHEIGHT_DEFAULT_ROWS),
2701 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2702 TIMEOFFSET_MIN_HOURS,
2703 TIMEOFFSET_MAX_HOURS),
2704 'relativeDates' => new _UserPreference_bool(),
2705 'googleLink' => new _UserPreference_bool(), // 1.3.10
2707 // add custom theme-specific pref types:
2708 // FIXME: on theme changes the wiki_user session pref object will fail.
2709 // We will silently ignore this.
2710 if (!empty($customUserPreferenceColumns))
2711 $this->_prefs = array_merge($this->_prefs,$customUserPreferenceColumns);
2713 if (isset($this->_method) and $this->_method == 'SQL') {
2714 //unset($this->_prefs['userid']);
2715 unset($this->_prefs['passwd']);
2718 if (is_array($saved_prefs)) {
2719 foreach ($saved_prefs as $name => $value)
2720 $this->set($name, $value);
2724 function _getPref($name) {
2725 if ($name == 'emailVerified')
2727 if (!isset($this->_prefs[$name])) {
2728 if ($name == 'passwd2') return false;
2729 if ($name == 'passwd') return false;
2730 trigger_error("$name: unknown preference", E_USER_NOTICE);
2733 return $this->_prefs[$name];
2736 // get the value or default_value of the subobject
2737 function get($name) {
2738 if ($_pref = $this->_getPref($name))
2739 if ($name == 'emailVerified')
2740 return $_pref->getraw($name);
2742 return $_pref->get($name);
2747 // check and set the new value in the subobject
2748 function set($name, $value) {
2749 $pref = $this->_getPref($name);
2750 if ($pref === false)
2753 /* do it here or outside? */
2754 if ($name == 'passwd' and
2755 defined('PASSWORD_LENGTH_MINIMUM') and
2756 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2757 //TODO: How to notify the user?
2761 if ($name == 'theme' and $value == '')
2764 if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
2765 if ($name == 'emailVerified') $newvalue = $value;
2766 else $newvalue = $pref->sanify($value);
2767 $pref->set($name,$newvalue);
2769 $this->_prefs[$name] =& $pref;
2773 * use init to avoid update on set
2775 function updatePrefs($prefs, $init = false) {
2777 if ($init) $this->_init = $init;
2778 if (is_object($prefs)) {
2779 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2780 $obj->_init = $init;
2781 if ($obj->get($type) !== $prefs->get($type)) {
2782 if ($obj->set($type,$prefs->get($type)))
2785 foreach (array_keys($this->_prefs) as $type) {
2786 $obj =& $this->_prefs[$type];
2787 $obj->_init = $init;
2788 if ($prefs->get($type) !== $obj->get($type)) {
2789 // special systemdefault prefs: (probably not needed)
2790 if ($type == 'theme' and $prefs->get($type) == '' and $obj->get($type) == THEME) continue;
2791 if ($type == 'lang' and $prefs->get($type) == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue;
2792 if ($this->_prefs[$type]->set($type,$prefs->get($type)))
2796 } elseif (is_array($prefs)) {
2797 //unset($this->_prefs['userid']);
2798 if (isset($this->_method) and
2799 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2800 unset($this->_prefs['passwd']);
2802 // emailVerified at first, the rest later
2803 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2804 $obj->_init = $init;
2805 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2806 if ($obj->set($type,$prefs[$type]))
2809 foreach (array_keys($this->_prefs) as $type) {
2810 $obj =& $this->_prefs[$type];
2811 $obj->_init = $init;
2812 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2813 $prefs[$type] = false;
2814 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2815 $prefs[$type] = (int) $prefs[$type];
2816 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2817 // special systemdefault prefs:
2818 if ($type == 'theme' and $prefs[$type] == '' and $obj->get($type) == THEME) continue;
2819 if ($type == 'lang' and $prefs[$type] == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue;
2820 if ($obj->set($type,$prefs[$type]))
2828 // for now convert just array of objects => array of values
2829 // Todo: the specialized subobjects must override this.
2832 foreach ($this->_prefs as $name => $object) {
2833 if ($value = $object->getraw($name))
2834 $prefs[$name] = $value;
2835 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2836 $prefs['emailVerified'] = $value;
2838 return $this->pack($prefs);
2841 // packed string or array of values => array of values
2842 // Todo: the specialized subobjects must override this.
2843 function retrieve($packed) {
2844 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2845 $packed = unserialize($packed);
2846 if (!is_array($packed)) return false;
2848 foreach ($packed as $name => $packed_pref) {
2849 if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2850 //legacy: check if it's an old array of objects
2851 // Looks like a serialized object.
2852 // This might fail if the object definition does not exist anymore.
2853 // object with ->$name and ->default_value vars.
2854 $pref = @unserialize($packed_pref);
2856 $pref = @unserialize(base64_decode($packed_pref));
2857 $prefs[$name] = $pref->get($name);
2858 // fix old-style prefs
2859 } elseif (is_numeric($name) and is_array($packed_pref)) {
2860 if (count($packed_pref) == 1) {
2861 list($name,$value) = each($packed_pref);
2862 $prefs[$name] = $value;
2865 $prefs[$name] = @unserialize($packed_pref);
2866 if (empty($prefs[$name]))
2867 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2868 // patched by frederik@pandora.be
2869 if (empty($prefs[$name]))
2870 $prefs[$name] = $packed_pref;
2877 * Check if the given prefs object is different from the current prefs object
2879 function isChanged($other) {
2880 foreach ($this->_prefs as $type => $obj) {
2881 if ($obj->get($type) !== $other->get($type))
2887 function defaultPreferences() {
2889 foreach ($this->_prefs as $key => $obj) {
2890 $prefs[$key] = $obj->default_value;
2897 return $this->_prefs;
2900 function pack($nonpacked) {
2901 return serialize($nonpacked);
2904 function unpack($packed) {
2907 //$packed = base64_decode($packed);
2908 if (substr($packed, 0, 2) == "O:") {
2909 // Looks like a serialized object
2910 return unserialize($packed);
2912 if (substr($packed, 0, 2) == "a:") {
2913 return unserialize($packed);
2915 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2921 return hash($this->_prefs);
2925 /** TODO: new pref storage classes
2926 * These are currently user specific and should be rewritten to be pref specific.
2927 * i.e. $this == $user->_prefs
2929 class CookieUserPreferences
2930 extends UserPreferences
2932 function CookieUserPreferences ($saved_prefs = false) {
2933 //_AnonUser::_AnonUser('',$saved_prefs);
2934 UserPreferences::UserPreferences($saved_prefs);
2938 class PageUserPreferences
2939 extends UserPreferences
2941 function PageUserPreferences ($saved_prefs = false) {
2942 UserPreferences::UserPreferences($saved_prefs);
2946 class PearDbUserPreferences
2947 extends UserPreferences
2949 function PearDbUserPreferences ($saved_prefs = false) {
2950 UserPreferences::UserPreferences($saved_prefs);
2954 class AdoDbUserPreferences
2955 extends UserPreferences
2957 function AdoDbUserPreferences ($saved_prefs = false) {
2958 UserPreferences::UserPreferences($saved_prefs);
2960 function getPreferences() {
2961 // override the generic slow method here for efficiency
2962 _AnonUser::getPreferences();
2963 $this->getAuthDbh();
2964 if (isset($this->_select)) {
2965 $dbh = & $this->_auth_dbi;
2966 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2970 $prefs_blob = $rs->fields['pref_blob'];
2972 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2973 $updated = $this->_prefs->updatePrefs($restored_from_db);
2974 //$this->_prefs = new UserPreferences($restored_from_db);
2975 return $this->_prefs;
2979 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2980 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2981 $updated = $this->_prefs->updatePrefs($restored_from_page);
2982 //$this->_prefs = new UserPreferences($restored_from_page);
2983 return $this->_prefs;
2986 return $this->_prefs;
2991 // $Log: not supported by cvs2svn $
2992 // Revision 1.88 2004/06/04 20:32:53 rurban
2993 // Several locale related improvements suggested by Pierrick Meignen
2994 // LDAP fix by John Cole
2995 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2997 // Revision 1.87 2004/06/04 12:40:21 rurban
2998 // Restrict valid usernames to prevent from attacks against external auth or compromise
3000 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
3001 // Fxied more warnings
3003 // Revision 1.86 2004/06/03 18:06:29 rurban
3004 // fix file locking issues (only needed on write)
3005 // fixed immediate LANG and THEME in-session updates if not stored in prefs
3006 // advanced editpage toolbars (search & replace broken)
3008 // Revision 1.85 2004/06/03 12:46:03 rurban
3009 // fix signout, level must be 0 not -1
3011 // Revision 1.84 2004/06/03 12:36:03 rurban
3012 // fix eval warning on signin
3014 // Revision 1.83 2004/06/03 10:18:19 rurban
3015 // fix User locking issues, new config ENABLE_PAGEPERM
3017 // Revision 1.82 2004/06/03 09:39:51 rurban
3018 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
3020 // Revision 1.81 2004/06/02 18:01:45 rurban
3021 // init global FileFinder to add proper include paths at startup
3022 // adds PHPWIKI_DIR if started from another dir, lib/pear also
3023 // fix slashify for Windows
3024 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
3026 // Revision 1.80 2004/06/02 14:20:27 rurban
3027 // fix adodb DbPassUser login
3029 // Revision 1.79 2004/06/01 15:27:59 rurban
3030 // AdminUser only ADMIN_USER not member of Administrators
3031 // some RateIt improvements by dfrankow
3032 // edit_toolbar buttons
3034 // Revision 1.78 2004/05/27 17:49:06 rurban
3035 // renamed DB_Session to DbSession (in CVS also)
3036 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
3037 // remove leading slash in error message
3038 // added force_unlock parameter to File_Passwd (no return on stale locks)
3039 // fixed adodb session AffectedRows
3040 // added FileFinder helpers to unify local filenames and DATA_PATH names
3041 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
3043 // Revision 1.77 2004/05/18 14:49:51 rurban
3044 // Simplified strings for easier translation
3046 // Revision 1.76 2004/05/18 13:30:04 rurban
3047 // prevent from endless loop with oldstyle warnings
3049 // Revision 1.75 2004/05/16 22:07:35 rurban
3050 // check more config-default and predefined constants
3051 // various PagePerm fixes:
3052 // fix default PagePerms, esp. edit and view for Bogo and Password users
3053 // implemented Creator and Owner
3054 // BOGOUSERS renamed to BOGOUSER
3055 // fixed syntax errors in signin.tmpl
3057 // Revision 1.74 2004/05/15 19:48:33 rurban
3058 // fix some too loose PagePerms for signed, but not authenticated users
3059 // (admin, owner, creator)
3060 // no double login page header, better login msg.
3061 // moved action_pdf to lib/pdf.php
3063 // Revision 1.73 2004/05/15 18:31:01 rurban
3064 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
3066 // Revision 1.72 2004/05/12 10:49:55 rurban
3067 // require_once fix for those libs which are loaded before FileFinder and
3068 // its automatic include_path fix, and where require_once doesn't grok
3069 // dirname(__FILE__) != './lib'
3070 // upgrade fix with PearDB
3071 // navbar.tmpl: remove spaces for IE button alignment
3073 // Revision 1.71 2004/05/10 12:34:47 rurban
3074 // stabilize DbAuthParam statement pre-prozessor:
3075 // try old-style and new-style (double-)quoting
3076 // reject unknown $variables
3077 // use ->prepare() for all calls (again)
3079 // Revision 1.70 2004/05/06 19:26:16 rurban
3080 // improve stability, trying to find the InlineParser endless loop on sf.net
3082 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
3084 // Revision 1.69 2004/05/06 13:56:40 rurban
3085 // Enable the Administrators group, and add the WIKIPAGE group default root page.
3087 // Revision 1.68 2004/05/05 13:37:54 rurban
3088 // Support to remove all UserPreferences
3090 // Revision 1.66 2004/05/03 21:44:24 rurban
3091 // fixed sf,net bug #947264: LDAP options are constants, not strings!
3093 // Revision 1.65 2004/05/03 13:16:47 rurban
3094 // fixed UserPreferences update, esp for boolean and int
3096 // Revision 1.64 2004/05/02 15:10:06 rurban
3097 // new finally reliable way to detect if /index.php is called directly
3098 // and if to include lib/main.php
3099 // new global AllActionPages
3100 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
3101 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
3102 // PageGroupTestOne => subpages
3103 // renamed PhpWikiRss to PhpWikiRecentChanges
3104 // more docs, default configs, ...
3106 // Revision 1.63 2004/05/01 15:59:29 rurban
3107 // more php-4.0.6 compatibility: superglobals
3109 // Revision 1.62 2004/04/29 18:31:24 rurban
3110 // Prevent from warning where no db pref was previously stored.
3112 // Revision 1.61 2004/04/29 17:18:19 zorloc
3113 // 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.
3115 // Revision 1.60 2004/04/27 18:20:54 rurban
3116 // sf.net patch #940359 by rassie
3118 // Revision 1.59 2004/04/26 12:35:21 rurban
3119 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
3120 // File_Passwd is already loaded
3122 // Revision 1.58 2004/04/20 17:08:28 rurban
3123 // Some IniConfig fixes: prepend our private lib/pear dir
3124 // switch from " to ' in the auth statements
3125 // use error handling.
3126 // WikiUserNew changes for the new "'$variable'" syntax
3127 // in the statements
3128 // TODO: optimization to put config vars into the session.
3130 // Revision 1.57 2004/04/19 18:27:45 rurban
3131 // Prevent from some PHP5 warnings (ref args, no :: object init)
3132 // php5 runs now through, just one wrong XmlElement object init missing
3133 // Removed unneccesary UpgradeUser lines
3134 // Changed WikiLink to omit version if current (RecentChanges)
3136 // Revision 1.56 2004/04/19 09:13:24 rurban
3137 // new pref: googleLink
3139 // Revision 1.54 2004/04/18 00:24:45 rurban
3140 // re-use our simple prepare: just for table prefix warnings
3142 // Revision 1.53 2004/04/12 18:29:15 rurban
3143 // exp. Session auth for already authenticated users from another app
3145 // Revision 1.52 2004/04/12 13:04:50 rurban
3146 // added auth_create: self-registering Db users
3148 // removed rating recommendations
3149 // ziplib reformatting
3151 // Revision 1.51 2004/04/11 10:42:02 rurban
3152 // pgsrc/CreatePagePlugin
3154 // Revision 1.50 2004/04/10 05:34:35 rurban
3157 // Revision 1.49 2004/04/07 23:13:18 rurban
3158 // fixed pear/File_Passwd for Windows
3159 // fixed FilePassUser sessions (filehandle revive) and password update
3161 // Revision 1.48 2004/04/06 20:00:10 rurban
3162 // Cleanup of special PageList column types
3163 // Added support of plugin and theme specific Pagelist Types
3164 // Added support for theme specific UserPreferences
3165 // Added session support for ip-based throttling
3166 // sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
3167 // Enhanced postgres schema
3168 // Added DB_Session_dba support
3170 // Revision 1.47 2004/04/02 15:06:55 rurban
3171 // fixed a nasty ADODB_mysql session update bug
3172 // improved UserPreferences layout (tabled hints)
3173 // fixed UserPreferences auth handling
3174 // improved auth stability
3175 // improved old cookie handling: fixed deletion of old cookies with paths
3177 // Revision 1.46 2004/04/01 06:29:51 rurban
3179 // RateIt also for ADODB
3181 // Revision 1.45 2004/03/30 02:14:03 rurban
3182 // fixed yet another Prefs bug
3183 // added generic PearDb_iter
3184 // $request->appendValidators no so strict as before
3185 // added some box plugin methods
3186 // PageList commalist for condensed output
3188 // Revision 1.44 2004/03/27 22:01:03 rurban
3189 // two catches by Konstantin Zadorozhny
3191 // Revision 1.43 2004/03/27 19:40:09 rurban
3192 // init fix and validator reset
3194 // Revision 1.40 2004/03/25 22:54:31 rurban
3197 // Revision 1.38 2004/03/25 17:37:36 rurban
3198 // helper to patch to and from php5 (workaround for stricter parser, no macros in php)
3200 // Revision 1.37 2004/03/25 17:00:31 rurban
3201 // more code to convert old-style pref array to new hash
3203 // Revision 1.36 2004/03/24 19:39:02 rurban
3204 // php5 workaround code (plus some interim debugging code in XmlElement)
3205 // php5 doesn't work yet with the current XmlElement class constructors,
3206 // WikiUserNew does work better than php4.
3207 // rewrote WikiUserNew user upgrading to ease php5 update
3208 // fixed pref handling in WikiUserNew
3209 // added Email Notification
3210 // added simple Email verification
3211 // removed emailVerify userpref subclass: just a email property
3212 // changed pref binary storage layout: numarray => hash of non default values
3213 // print optimize message only if really done.
3214 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
3215 // prefs should be stored in db or homepage, besides the current session.
3217 // Revision 1.35 2004/03/18 22:18:31 rurban
3218 // workaround for php5 object upgrading problem
3220 // Revision 1.34 2004/03/18 21:41:09 rurban
3221 // fixed sqlite support
3222 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
3224 // Revision 1.33 2004/03/16 15:42:04 rurban
3225 // more fixes for undefined property warnings
3227 // Revision 1.32 2004/03/14 16:30:52 rurban
3228 // db-handle session revivification, dba fixes
3230 // Revision 1.31 2004/03/12 23:20:58 rurban
3231 // pref fixes (base64)
3233 // Revision 1.30 2004/03/12 20:59:17 rurban
3234 // important cookie fix by Konstantin Zadorozhny
3235 // new editpage feature: JS_SEARCHREPLACE
3237 // Revision 1.29 2004/03/11 13:30:47 rurban
3238 // fixed File Auth for user and group
3239 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
3241 // Revision 1.28 2004/03/08 18:17:09 rurban
3242 // added more WikiGroup::getMembersOf methods, esp. for special groups
3243 // fixed $LDAP_SET_OPTIONS
3244 // fixed _AuthInfo group methods
3246 // Revision 1.27 2004/03/01 09:35:13 rurban
3247 // fixed DbPassuser pref init; lost userid
3249 // Revision 1.26 2004/02/29 04:10:56 rurban
3250 // new POP3 auth (thanks to BiloBilo: pentothal at despammed dot com)
3251 // fixed syntax error in index.php
3253 // Revision 1.25 2004/02/28 22:25:07 rurban
3254 // First PagePerm implementation:
3256 // $Theme->setAnonEditUnknownLinks(false);
3258 // Layout improvement with dangling links for mostly closed wiki's:
3259 // If false, only users with edit permissions will be presented the
3260 // special wikiunknown class with "?" and Tooltip.
3261 // If true (default), any user will see the ?, but will be presented
3262 // the PrintLoginForm on a click.
3264 // Revision 1.24 2004/02/28 21:14:08 rurban
3265 // generally more PHPDOC docs
3266 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
3267 // fxied WikiUserNew pref handling: empty theme not stored, save only
3268 // changed prefs, sql prefs improved, fixed password update,
3269 // removed REPLACE sql (dangerous)
3270 // moved gettext init after the locale was guessed
3271 // + some minor changes
3273 // Revision 1.23 2004/02/27 13:21:17 rurban
3274 // several performance improvements, esp. with peardb
3276 // storepass seperated from prefs if defined so
3277 // stacked and strict still not working
3279 // Revision 1.22 2004/02/27 05:15:40 rurban
3280 // more stability. detected by Micki
3282 // Revision 1.21 2004/02/26 20:43:49 rurban
3283 // new HttpAuthPassUser class (forces http auth if in the auth loop)
3284 // fixed user upgrade: don't return _PassUser in the first hand.
3286 // Revision 1.20 2004/02/26 01:29:11 rurban
3287 // important fixes: endless loops in certain cases. minor rewrite
3289 // Revision 1.19 2004/02/25 17:15:17 rurban
3290 // improve stability
3292 // Revision 1.18 2004/02/24 15:20:05 rurban
3293 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
3295 // Revision 1.17 2004/02/17 12:16:42 rurban
3296 // started with changePass support. not yet used.
3298 // Revision 1.16 2004/02/15 22:23:45 rurban
3299 // oops, fixed showstopper (endless recursion)
3301 // Revision 1.15 2004/02/15 21:34:37 rurban
3302 // PageList enhanced and improved.
3303 // fixed new WikiAdmin... plugins
3304 // editpage, Theme with exp. htmlarea framework
3305 // (htmlarea yet committed, this is really questionable)
3306 // WikiUser... code with better session handling for prefs
3307 // enhanced UserPreferences (again)
3308 // RecentChanges for show_deleted: how should pages be deleted then?
3310 // Revision 1.14 2004/02/15 17:30:13 rurban
3311 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
3312 // fixed getPreferences() (esp. from sessions)
3313 // fixed setPreferences() (update and set),
3314 // fixed AdoDb DB statements,
3315 // update prefs only at UserPreferences POST (for testing)
3316 // unified db prefs methods (but in external pref classes yet)
3318 // Revision 1.13 2004/02/09 03:58:12 rurban
3319 // for now default DB_SESSION to false
3321 // * not existing perms will now query the parent, and not
3322 // return the default perm
3323 // * added pagePermissions func which returns the object per page
3324 // * added getAccessDescription
3326 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
3327 // * force init of authdbh in the 2 db classes
3329 // * fixed session handling (not triple auth request anymore)
3330 // * don't store cookie prefs with sessions
3331 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
3333 // Revision 1.12 2004/02/07 10:41:25 rurban
3334 // fixed auth from session (still double code but works)
3336 // fixed DbPassUser upgrade and policy=old
3339 // Revision 1.11 2004/02/03 09:45:39 rurban
3340 // LDAP cleanup, start of new Pref classes
3342 // Revision 1.10 2004/02/01 09:14:11 rurban
3343 // Started with Group_Ldap (not yet ready)
3344 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
3345 // fixed some configurator vars
3346 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
3347 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
3348 // USE_DB_SESSION defaults to true on SQL
3349 // changed GROUP_METHOD definition to string, not constants
3350 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
3351 // create users. (Not to be used with external databases generally, but
3352 // with the default internal user table)
3354 // fixed the IndexAsConfigProblem logic. this was flawed:
3355 // scripts which are the same virtual path defined their own lib/main call
3356 // (hmm, have to test this better, phpwiki.sf.net/demo works again)
3358 // Revision 1.9 2004/01/30 19:57:58 rurban
3359 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
3361 // Revision 1.8 2004/01/30 18:46:15 rurban
3362 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
3364 // Revision 1.7 2004/01/27 23:23:39 rurban
3365 // renamed ->Username => _userid for consistency
3366 // renamed mayCheckPassword => mayCheckPass
3367 // fixed recursion problem in WikiUserNew
3368 // fixed bogo login (but not quite 100% ready yet, password storage)
3370 // Revision 1.6 2004/01/26 09:17:49 rurban
3371 // * changed stored pref representation as before.
3372 // the array of objects is 1) bigger and 2)
3373 // less portable. If we would import packed pref
3374 // objects and the object definition was changed, PHP would fail.
3375 // This doesn't happen with an simple array of non-default values.
3376 // * use $prefs->retrieve and $prefs->store methods, where retrieve
3377 // understands the interim format of array of objects also.
3378 // * simplified $prefs->get() and fixed $prefs->set()
3379 // * added $user->_userid and class '_WikiUser' portability functions
3380 // * fixed $user object ->_level upgrading, mostly using sessions.
3381 // this fixes yesterdays problems with loosing authorization level.
3382 // * fixed WikiUserNew::checkPass to return the _level
3383 // * fixed WikiUserNew::isSignedIn
3384 // * added explodePageList to class PageList, support sortby arg
3385 // * fixed UserPreferences for WikiUserNew
3386 // * fixed WikiPlugin for empty defaults array
3387 // * UnfoldSubpages: added pagename arg, renamed pages arg,
3388 // removed sort arg, support sortby arg
3390 // Revision 1.5 2004/01/25 03:05:00 rurban
3391 // First working version, but has some problems with the current main loop.
3392 // Implemented new auth method dispatcher and policies, all the external
3393 // _PassUser classes (also for ADODB and Pear DB).
3394 // The two global funcs UserExists() and CheckPass() are probably not needed,
3395 // since the auth loop is done recursively inside the class code, upgrading
3396 // the user class within itself.
3397 // Note: When a higher user class is returned, this doesn't mean that the user
3398 // is authorized, $user->_level is still low, and only upgraded on successful
3401 // Revision 1.4 2003/12/07 19:29:48 carstenklapp
3402 // Code Housecleaning: fixed syntax errors. (php -l *.php)
3404 // Revision 1.3 2003/12/06 19:10:46 carstenklapp
3405 // Finished off logic for determining user class, including
3406 // PassUser. Removed ability of BogoUser to save prefs into a page.
3408 // Revision 1.2 2003/12/03 21:45:48 carstenklapp
3409 // Added admin user, password user, and preference classes. Added
3410 // password checking functions for users and the admin. (Now the easy
3411 // parts are nearly done).
3413 // Revision 1.1 2003/12/02 05:46:36 carstenklapp
3414 // Complete rewrite of WikiUser.php.
3416 // This should make it easier to hook in user permission groups etc. some
3417 // time in the future. Most importantly, to finally get UserPreferences
3418 // fully working properly for all classes of users: AnonUser, BogoUser,
3419 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
3420 // want a cookie or not, and to bring back optional AutoLogin with the
3421 // UserName stored in a cookie--something that was lost after PhpWiki had
3422 // dropped the default http auth login method.
3424 // Added WikiUser classes which will (almost) work together with existing
3425 // UserPreferences class. Other parts of PhpWiki need to be updated yet
3426 // before this code can be hooked up.
3432 // c-basic-offset: 4
3433 // c-hanging-comment-ender-p: nil
3434 // indent-tabs-mode: nil