2 rcs_id('$Id: WikiUserNew.php,v 1.93 2004-06-15 09:15:52 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 not password checked or empty password.
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';
854 // Check the configured Prefs methods
855 $dbi = $this->getAuthDbh();
856 $dbh = $GLOBALS['request']->getDbh();
857 if ( $dbi and !isset($this->_prefs->_select) and $dbh->getAuthParam('pref_select')) {
858 if (!$this->_prefs) {
859 $this->_prefs = new UserPreferences();
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 if (! $this->_prefs or isset($need_pref) ) {
874 if ($prefs) $this->_prefs = $prefs;
875 else $this->getPreferences();
878 // Upgrade to the next parent _PassUser class. Avoid recursion.
879 if ( strtolower(get_class($this)) === '_passuser' ) {
880 //auth policy: Check the order of the configured auth methods
881 // 1. first-only: Upgrade the class here in the constructor
882 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
883 /// in the previous PhpWiki releases (slow)
884 // 3. strict: upgrade the class after checking the user existance in userExists()
885 // 4. stacked: upgrade the class after the password verification in checkPass()
886 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
887 if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
888 if (defined('USER_AUTH_POLICY')) {
889 // policy 1: only pre-define one method for all users
890 if (USER_AUTH_POLICY === 'first-only') {
891 $class = $this->nextClass();
892 return new $class($UserName,$this->_prefs);
894 // Use the default behaviour from the previous versions:
895 elseif (USER_AUTH_POLICY === 'old') {
896 // Default: try to be smart
897 // On php5 we can directly return and upgrade the Object,
898 // before we have to upgrade it manually.
899 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
900 if (check_php_version(5))
901 return new _HttpAuthPassUser($UserName,$this->_prefs);
903 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
904 //todo: with php5 comment the following line.
905 /*PHP5 patch*/$this = $user;
908 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
909 $dbh->getAuthParam('auth_check') and
910 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
911 if (check_php_version(5))
912 return new _DbPassUser($UserName,$this->_prefs);
914 $user = new _DbPassUser($UserName,$this->_prefs);
915 //todo: with php5 comment the following line.
916 /*PHP5 patch*/$this = $user;
919 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
920 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
921 function_exists('ldap_connect')) {
922 if (check_php_version(5))
923 return new _LDAPPassUser($UserName,$this->_prefs);
925 $user = new _LDAPPassUser($UserName,$this->_prefs);
926 //todo: with php5 comment the following line.
927 /*PHP5 patch*/$this = $user;
930 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
931 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
932 if (check_php_version(5))
933 return new _IMAPPassUser($UserName,$this->_prefs);
935 $user = new _IMAPPassUser($UserName,$this->_prefs);
936 //todo: with php5 comment the following line.
937 /*PHP5 patch*/$this = $user;
940 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
941 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
942 if (check_php_version(5))
943 return new _FilePassUser($UserName, $this->_prefs);
945 $user = new _FilePassUser($UserName, $this->_prefs);
946 //todo: with php5 comment the following line.
947 /*PHP5 patch*/$this = $user;
951 if (check_php_version(5))
952 return new _PersonalPagePassUser($UserName,$this->_prefs);
954 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
955 //todo: with php5 comment the following line.
956 /*PHP5 patch*/$this = $user;
962 // else use the page methods defined in _PassUser.
968 function getAuthDbh () {
969 global $request; //, $DBParams, $DBAuthParams;
971 $dbh = $request->getDbh();
972 // session restauration doesn't re-connect to the database automatically,
973 // so dirty it here, to force a reconnect.
974 if (isset($this->_auth_dbi)) {
975 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
976 unset($this->_auth_dbi);
977 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
978 unset($this->_auth_dbi);
980 if (empty($this->_auth_dbi)) {
981 if ($dbh->getParam('dbtype') != 'SQL' and $dbh->getParam('dbtype') != 'ADODB')
983 if (empty($GLOBALS['DBAuthParams']))
985 if (!$dbh->getAuthParam('auth_dsn')) {
986 $dbh = $request->getDbh(); // use phpwiki database
987 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
988 $dbh = $request->getDbh(); // same phpwiki database
989 } else { // use another external database handle. needs PHP >= 4.1
990 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
991 $local_params['dsn'] = $local_params['auth_dsn'];
992 $dbh = WikiDB::open($local_params);
994 $this->_auth_dbi =& $dbh->_backend->_dbh;
996 return $this->_auth_dbi;
999 function _normalize_stmt_var($var, $oldstyle = false) {
1000 static $valid_variables = array('userid','password','pref_blob','groupname');
1001 // old-style: "'$userid'"
1002 // new-style: '"\$userid"' or just "userid"
1003 $new = str_replace(array("'",'"','\$','$'),'',$var);
1004 if (!in_array($new,$valid_variables)) {
1005 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1008 return !$oldstyle ? "'$".$new."'" : '"\$'.$new.'"';
1011 // TODO: use it again for the auth and member tables
1012 function prepare ($stmt, $variables, $oldstyle = false) {
1014 $dbi = $request->getDbh();
1015 $this->getAuthDbh();
1016 // "'\$userid"' => '%s'
1017 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1018 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1020 if (is_array($variables)) {
1021 for ($i=0; $i < count($variables); $i++) {
1022 $var = $this->_normalize_stmt_var($variables[$i],$oldstyle);
1024 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1025 $variables[$i], $stmt), E_USER_WARNING);
1026 $variables[$i] = $var;
1027 if (!$var) $new[] = '';
1031 $var = $this->_normalize_stmt_var($variables,$oldstyle);
1033 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1034 $variables,$stmt), E_USER_WARNING);
1036 if (!$var) $new = '';
1039 $prefix = $dbi->getParam('prefix');
1040 // probably prefix table names if in same database
1041 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1042 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1044 if (!stristr($stmt, $prefix)) {
1045 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1046 trigger_error("TODO: Need to prefix the DBAuthParam tablename in config/config.ini:\n $stmt",
1048 $stmt = str_replace(array(" user "," pref "," member "),
1049 array(" ".$prefix."user ",
1050 " ".$prefix."prefs ",
1051 " ".$prefix."member "),$stmt);
1054 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1055 // Simple sprintf-style.
1056 $new_stmt = str_replace($variables,$new,$stmt);
1057 if ($new_stmt == $stmt) {
1059 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1060 $stmt), E_USER_WARNING);
1062 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1063 $stmt), E_USER_WARNING);
1064 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1070 function getPreferences() {
1071 if (!empty($this->_prefs->_method)) {
1072 if ($this->_prefs->_method == 'ADODB') {
1073 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
1074 return _AdoDbPassUser::getPreferences();
1075 } elseif ($this->_prefs->_method == 'SQL') {
1076 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
1077 return _PearDbPassUser::getPreferences();
1081 // We don't necessarily have to read the cookie first. Since
1082 // the user has a password, the prefs stored in the homepage
1083 // cannot be arbitrarily altered by other Bogo users.
1084 _AnonUser::getPreferences();
1085 // User may have deleted cookie, retrieve from his
1086 // PersonalPage if there is one.
1087 if ($this->_HomePagehandle) {
1088 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1089 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1090 //$this->_prefs = new UserPreferences($restored_from_page);
1091 return $this->_prefs;
1094 return $this->_prefs;
1097 function setPreferences($prefs, $id_only=false) {
1098 if (!empty($this->_prefs->_method)) {
1099 if ($this->_prefs->_method == 'ADODB') {
1100 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
1101 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1103 elseif ($this->_prefs->_method == 'SQL') {
1104 _PearDbPassUser::_PearDbPassUser($this->_userid,$prefs);
1105 return _PearDbPassUser::setPreferences($prefs, $id_only);
1108 if (_AnonUser::setPreferences($prefs, $id_only)) {
1109 // Encode only the _prefs array of the UserPreference object
1110 if ($this->_HomePagehandle and !$id_only) {
1111 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1117 function mayChangePass() {
1121 //The default method is getting the password from prefs.
1122 // child methods obtain $stored_password from external auth.
1123 function userExists() {
1124 //if ($this->_HomePagehandle) return true;
1125 $class = $this->nextClass();
1126 while ($user = new $class($this->_userid,$this->_prefs)) {
1127 //todo: with php5 comment the following line:
1128 /*PHP5 patch*/$this = $user;
1129 //UpgradeUser($this,$user);
1130 if ($user->userExists()) {
1133 // prevent endless loop. does this work on all PHP's?
1134 // it just has to set the classname, what it correctly does.
1135 $class = $user->nextClass();
1136 if ($class == "_ForbiddenPassUser")
1142 //The default method is getting the password from prefs.
1143 // child methods obtain $stored_password from external auth.
1144 function checkPass($submitted_password) {
1145 $stored_password = $this->_prefs->get('passwd');
1146 if ($this->_checkPass($submitted_password, $stored_password)) {
1147 $this->_level = WIKIAUTH_USER;
1148 return $this->_level;
1150 return $this->_tryNextPass($submitted_password);
1155 * The basic password checker for all PassUser objects.
1156 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1157 * Empty passwords are always false!
1158 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1159 * @see UserPreferences::set
1161 * DBPassUser password's have their own crypt definition.
1162 * That's why DBPassUser::checkPass() doesn't call this method, if
1163 * the db password method is 'plain', which means that the DB SQL
1164 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1165 * don't store plain passwords in the DB.
1167 * TODO: remove crypt() function check from config.php:396 ??
1169 function _checkPass($submitted_password, $stored_password) {
1170 if(!empty($submitted_password)) {
1171 if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1172 // With the EditMetaData plugin
1173 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."));
1176 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
1178 if (ENCRYPTED_PASSWD) {
1179 // Verify against encrypted password.
1180 if (function_exists('crypt')) {
1181 if (crypt($submitted_password, $stored_password) == $stored_password )
1182 return true; // matches encrypted password
1187 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1188 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1194 // Verify against cleartext password.
1195 if ($submitted_password == $stored_password)
1198 // Check whether we forgot to enable ENCRYPTED_PASSWD
1199 if (function_exists('crypt')) {
1200 if (crypt($submitted_password, $stored_password) == $stored_password) {
1201 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1212 /** The default method is storing the password in prefs.
1213 * Child methods (DB,File) may store in external auth also, but this
1214 * must be explicitly enabled.
1215 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1217 function changePass($submitted_password) {
1218 $stored_password = $this->_prefs->get('passwd');
1219 // check if authenticated
1220 if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1221 $this->_prefs->set('passwd',$submitted_password);
1222 //update the storage (session, homepage, ...)
1223 $this->SetPreferences($this->_prefs);
1226 //Todo: return an error msg to the caller what failed?
1227 // same password or no privilege
1231 function _tryNextPass($submitted_password) {
1232 if (USER_AUTH_POLICY === 'strict') {
1233 $class = $this->nextClass();
1234 if ($user = new $class($this->_userid,$this->_prefs)) {
1235 if ($user->userExists()) {
1236 return $user->checkPass($submitted_password);
1240 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1241 $class = $this->nextClass();
1242 if ($user = new $class($this->_userid,$this->_prefs))
1243 return $user->checkPass($submitted_password);
1245 return $this->_level;
1248 function _tryNextUser() {
1249 if (USER_AUTH_POLICY === 'strict') {
1250 $class = $this->nextClass();
1251 while ($user = new $class($this->_userid,$this->_prefs)) {
1252 //todo: with php5 comment the following line:
1253 /*PHP5 patch*/$this = $user;
1254 //$user = UpgradeUser($this, $user);
1255 if ($user->userExists()) {
1258 $class = $this->nextClass();
1266 /** Without stored password. A _BogoLoginPassUser with password
1267 * is automatically upgraded to a PersonalPagePassUser.
1269 class _BogoLoginPassUser
1272 var $_authmethod = 'BogoLogin';
1273 function userExists() {
1274 if (isWikiWord($this->_userid)) {
1275 $this->_level = WIKIAUTH_BOGO;
1278 $this->_level = WIKIAUTH_ANON;
1283 /** A BogoLoginUser requires no password at all
1284 * But if there's one stored, we should prefer PersonalPage instead
1286 function checkPass($submitted_password) {
1287 if ($this->_prefs->get('passwd')) {
1288 if (isset($this->_prefs->_method) and $this->_prefs->_method == 'HomePage') {
1289 $user = new _PersonalPagePassUser($this->_userid, $this->_prefs);
1290 if ($user->checkPass($submitted_password)) {
1291 //todo: with php5 comment the following line:
1292 /*PHP5 patch*/$this = $user;
1293 $user = UpgradeUser($this, $user);
1294 $this->_level = WIKIAUTH_USER;
1295 return $this->_level;
1297 $this->_level = WIKIAUTH_ANON;
1298 return $this->_level;
1301 $stored_password = $this->_prefs->get('passwd');
1302 if ($this->_checkPass($submitted_password, $stored_password)) {
1303 $this->_level = WIKIAUTH_USER;
1304 return $this->_level;
1306 return $this->_tryNextPass($submitted_password);
1310 if (isWikiWord($this->_userid)) {
1311 $this->_level = WIKIAUTH_BOGO;
1313 $this->_level = WIKIAUTH_ANON;
1315 return $this->_level;
1321 * This class is only to simplify the auth method dispatcher.
1322 * It inherits almost all all methods from _PassUser.
1324 class _PersonalPagePassUser
1327 var $_authmethod = 'PersonalPage';
1329 function userExists() {
1330 return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1333 /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1334 * BUT if the user already has a homepage with an empty password
1335 * stored, allow login but warn him to change it.
1337 function checkPass($submitted_password) {
1338 if ($this->userExists()) {
1339 $stored_password = $this->_prefs->get('passwd');
1340 if (empty($stored_password)) {
1341 trigger_error(sprintf(
1342 _("\nYou stored an empty password in your '%s' page.\n").
1343 _("Your access permissions are only for a BogoUser.\n").
1344 _("Please set your password in UserPreferences."),
1345 $this->_userid), E_USER_WARNING);
1346 $this->_level = WIKIAUTH_BOGO;
1347 return $this->_level;
1349 if ($this->_checkPass($submitted_password, $stored_password))
1350 return ($this->_level = WIKIAUTH_USER);
1351 return _PassUser::checkPass($submitted_password);
1353 return WIKIAUTH_ANON;
1358 * We have two possibilities here.
1359 * 1) The webserver location is already HTTP protected (usually Basic). Then just
1360 * use the username and do nothing
1361 * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1362 * by sending a 401 error and let the client display the login dialog.
1363 * This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1364 * since the other methods cannot be transparently called after this enforced
1366 * Try the available auth methods (most likely Bogo) and sent this header back.
1367 * header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1369 class _HttpAuthPassUser
1372 function _HttpAuthPassUser($UserName='',$prefs=false) {
1373 if ($prefs) $this->_prefs = $prefs;
1374 if (!isset($this->_prefs->_method))
1375 _PassUser::_PassUser($UserName);
1376 if ($UserName) $this->_userid = $UserName;
1377 $this->_authmethod = 'HttpAuth';
1378 if ($this->userExists())
1381 return $GLOBALS['ForbiddenUser'];
1384 function _http_username() {
1385 if (!isset($_SERVER))
1386 $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
1387 if (!empty($_SERVER['PHP_AUTH_USER']))
1388 return $_SERVER['PHP_AUTH_USER'];
1389 if (!empty($_SERVER['REMOTE_USER']))
1390 return $_SERVER['REMOTE_USER'];
1391 if (!empty($GLOBALS['HTTP_ENV_VARS']['REMOTE_USER']))
1392 return $GLOBALS['HTTP_ENV_VARS']['REMOTE_USER'];
1393 if (!empty($GLOBALS['REMOTE_USER']))
1394 return $GLOBALS['REMOTE_USER'];
1398 //force http auth authorization
1399 function userExists() {
1400 // todo: older php's
1401 $username = $this->_http_username();
1402 if (empty($username) or strtolower($username) != strtolower($this->_userid)) {
1403 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1404 header('HTTP/1.0 401 Unauthorized');
1407 $this->_userid = $username;
1408 $this->_level = WIKIAUTH_USER;
1412 function checkPass($submitted_password) {
1413 return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1416 function mayChangePass() {
1420 // hmm... either the server dialog or our own.
1421 function PrintLoginForm (&$request, $args, $fail_message = false,
1422 $seperate_page = true) {
1423 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1424 header('HTTP/1.0 401 Unauthorized');
1431 * Support reuse of existing user session from another application.
1432 * You have to define which session variable holds the userid, and
1433 * at what level is that user then. 1: BogoUser, 2: PassUser
1434 * define('AUTH_SESS_USER','userid');
1435 * define('AUTH_SESS_LEVEL',2);
1437 class _SessionPassUser
1440 function _SessionPassUser($UserName='',$prefs=false) {
1441 if ($prefs) $this->_prefs = $prefs;
1442 if (!defined("AUTH_SESS_USER") or !defined("AUTH_SESS_LEVEL")) {
1444 "AUTH_SESS_USER or AUTH_SESS_LEVEL is not defined for the SessionPassUser method",
1448 $sess =& $GLOBALS['HTTP_SESSION_VARS'];
1449 // user hash: "[user][userid]" or object "user->id"
1450 if (strstr(AUTH_SESS_USER,"][")) {
1451 $sess = $GLOBALS['HTTP_SESSION_VARS'];
1452 // recurse into hashes: "[user][userid]", sess = sess[user] => sess = sess[userid]
1453 foreach (split("][",AUTH_SESS_USER) as $v) {
1454 $v = str_replace(array("[","]"),'',$v);
1457 $this->_userid = $sess;
1458 } elseif (strstr(AUTH_SESS_USER,"->")) {
1459 // object "user->id" (no objects inside hashes supported!)
1460 list($obj,$key) = split("->",AUTH_SESS_USER);
1461 $this->_userid = $sess[$obj]->$key;
1463 $this->_userid = $sess[AUTH_SESS_USER];
1465 if (!isset($this->_prefs->_method))
1466 _PassUser::_PassUser($this->_userid);
1467 $this->_level = AUTH_SESS_LEVEL;
1468 $this->_authmethod = 'Session';
1470 function userExists() {
1471 return !empty($this->_userid);
1473 function checkPass($submitted_password) {
1474 return $this->userExists() and $this->_level;
1476 function mayChangePass() {
1482 * Baseclass for PearDB and ADODB PassUser's
1483 * Authenticate against a database, to be able to use shared users.
1484 * internal: no different $DbAuthParams['dsn'] defined, or
1485 * external: different $DbAuthParams['dsn']
1486 * The magic is done in the symbolic SQL statements in config/config.ini, similar to
1489 * We support only the SQL and ADODB backends.
1490 * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages,
1491 * not for auth stuff. If one would like to use e.g. dba for auth, he should
1492 * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
1493 * (Not supported yet, since we require SQL. SQLite would make since when
1494 * it will come to PHP)
1496 * @tables: user, pref
1498 * Preferences are handled in the parent class _PassUser, because the
1499 * previous classes may also use DB pref_select and pref_update.
1501 * Flat files auth is handled by the auth method "File".
1506 var $_authselect, $_authupdate, $_authcreate;
1508 // This can only be called from _PassUser, because the parent class
1509 // sets the auth_dbi and pref methods, before this class is initialized.
1510 function _DbPassUser($UserName='',$prefs=false) {
1511 if (!$this->_prefs) {
1512 if ($prefs) $this->_prefs = $prefs;
1514 if (!isset($this->_prefs->_method))
1515 _PassUser::_PassUser($UserName);
1516 elseif (!$this->isValidName($UserName)) {
1517 trigger_error(_("Invalid username."),E_USER_WARNING);
1520 $this->_authmethod = 'Db';
1521 //$this->getAuthDbh();
1522 //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1523 $dbi =& $GLOBALS['request']->_dbi;
1524 $dbtype = $dbi->getParam('dbtype');
1525 if ($dbtype == 'ADODB') {
1526 if (check_php_version(5))
1527 return new _AdoDbPassUser($UserName,$this->_prefs);
1529 $user = new _AdoDbPassUser($UserName,$this->_prefs);
1530 //todo: with php5 comment the following line:
1531 /*PHP5 patch*/$this = $user;
1535 elseif ($dbtype == 'SQL') {
1536 if (check_php_version(5))
1537 return new _PearDbPassUser($UserName,$this->_prefs);
1539 $user = new _PearDbPassUser($UserName,$this->_prefs);
1540 //todo: with php5 comment the following line:
1541 /*PHP5 patch*/$this = $user;
1548 function mayChangePass() {
1549 return !isset($this->_authupdate);
1554 class _PearDbPassUser
1558 * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1559 * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1565 var $_authmethod = 'PearDb';
1566 function _PearDbPassUser($UserName='',$prefs=false) {
1567 //global $DBAuthParams;
1568 if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1569 if ($prefs) $this->_prefs = $prefs;
1571 if (!isset($this->_prefs->_method))
1572 _PassUser::_PassUser($UserName);
1573 elseif (!$this->isValidName($UserName)) {
1574 trigger_error(_("Invalid username."), E_USER_WARNING);
1577 $this->_userid = $UserName;
1578 // make use of session data. generally we only initialize this every time,
1579 // but do auth checks only once
1580 $this->_auth_crypt_method = $GLOBALS['request']->_dbi->getAuthParam('auth_crypt_method');
1584 function getPreferences() {
1585 // override the generic slow method here for efficiency and not to
1586 // clutter the homepage metadata with prefs.
1587 _AnonUser::getPreferences();
1588 $this->getAuthDbh();
1589 if (isset($this->_prefs->_select)) {
1590 $dbh = &$this->_auth_dbi;
1591 $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1592 // patched by frederik@pandora.be
1593 $prefs = $db_result->fetchRow();
1594 $prefs_blob = @$prefs["prefs"];
1595 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1596 $updated = $this->_prefs->updatePrefs($restored_from_db);
1597 //$this->_prefs = new UserPreferences($restored_from_db);
1598 return $this->_prefs;
1601 if ($this->_HomePagehandle) {
1602 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1603 $updated = $this->_prefs->updatePrefs($restored_from_page);
1604 //$this->_prefs = new UserPreferences($restored_from_page);
1605 return $this->_prefs;
1608 return $this->_prefs;
1611 function setPreferences($prefs, $id_only=false) {
1612 // if the prefs are changed
1613 if ($count = _AnonUser::setPreferences($prefs, 1)) {
1615 //$user = $request->_user;
1616 //unset($user->_auth_dbi);
1617 // this must be done in $request->_setUser, not here!
1618 //$request->setSessionVar('wiki_user', $user);
1619 $this->getAuthDbh();
1620 $packed = $this->_prefs->store();
1621 if (!$id_only and isset($this->_prefs->_update)) {
1622 $dbh = &$this->_auth_dbi;
1623 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1624 $dbh->quote($packed),
1625 $dbh->quote($this->_userid)));
1627 if ($this->_HomePagehandle and $this->_HomePagehandle->get('pref'))
1628 $this->_HomePagehandle->set('pref', '');
1630 //store prefs in homepage, not in cookie
1631 if ($this->_HomePagehandle and !$id_only)
1632 $this->_HomePagehandle->set('pref', $packed);
1634 return $count; //count($this->_prefs->unpack($packed));
1639 function userExists() {
1640 //global $DBAuthParams;
1641 $this->getAuthDbh();
1642 $dbh = &$this->_auth_dbi;
1643 if (!$dbh) { // needed?
1644 return $this->_tryNextUser();
1646 if (!$this->isValidName()) {
1647 return $this->_tryNextUser();
1649 $dbi =& $GLOBALS['request']->_dbi;
1650 // Prepare the configured auth statements
1651 if ($dbi->getAuthParam('auth_check') and empty($this->_authselect)) {
1652 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1653 array("userid", "password"));
1655 if (empty($this->_authselect))
1656 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1657 'DBAUTH_AUTH_CHECK', 'SQL'),
1659 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1660 if ($this->_auth_crypt_method == 'crypt') {
1661 $rs = $dbh->query(sprintf($this->_authselect, $dbh->quote($this->_userid)));
1666 if (! $dbi->getAuthParam('auth_user_exists'))
1667 trigger_error(fmt("%s is missing",'DBAUTH_AUTH_USER_EXISTS'),
1669 $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'),"userid");
1670 $rs = $dbh->query(sprintf($this->_authcheck, $dbh->quote($this->_userid)));
1674 // maybe the user is allowed to create himself. Generally not wanted in
1675 // external databases, but maybe wanted for the wiki database, for performance
1677 if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) {
1678 $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'),
1679 array("userid", "password"));
1681 if (!empty($this->_authcreate)) {
1682 $dbh->simpleQuery(sprintf($this->_authcreate,
1683 $dbh->quote($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1684 $dbh->quote($this->_userid)
1688 return $this->_tryNextUser();
1691 function checkPass($submitted_password) {
1692 //global $DBAuthParams;
1693 $this->getAuthDbh();
1694 if (!$this->_auth_dbi) { // needed?
1695 return $this->_tryNextPass($submitted_password);
1697 if (!$this->isValidName()) {
1698 return $this->_tryNextPass($submitted_password);
1700 if (!isset($this->_authselect))
1701 $this->userExists();
1702 if (!isset($this->_authselect))
1703 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1704 'DBAUTH_AUTH_CHECK','SQL'),
1707 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1708 $dbh = &$this->_auth_dbi;
1709 if ($this->_auth_crypt_method == 'crypt') {
1710 $stored_password = $dbh->getOne(sprintf($this->_authselect, $dbh->quote($this->_userid)));
1711 $result = $this->_checkPass($submitted_password, $stored_password);
1713 $okay = $dbh->getOne(sprintf($this->_authselect,
1714 $dbh->quote($submitted_password),
1715 $dbh->quote($this->_userid)));
1716 $result = !empty($okay);
1720 $this->_level = WIKIAUTH_USER;
1721 return $this->_level;
1723 return $this->_tryNextPass($submitted_password);
1727 function mayChangePass() {
1728 return $GLOBALS['request']->_dbi->getAuthParam('auth_update');
1731 function storePass($submitted_password) {
1732 if (!$this->isValidName()) {
1735 $this->getAuthDbh();
1736 $dbh = &$this->_auth_dbi;
1737 $dbi =& $GLOBALS['request']->_dbi;
1738 if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) {
1739 $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'),
1740 array("userid", "password"));
1742 if (empty($this->_authupdate)) {
1743 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1744 'DBAUTH_AUTH_UPDATE','SQL'),
1749 if ($this->_auth_crypt_method == 'crypt') {
1750 if (function_exists('crypt'))
1751 $submitted_password = crypt($submitted_password);
1753 $dbh->simpleQuery(sprintf($this->_authupdate,
1754 $dbh->quote($submitted_password),
1755 $dbh->quote($this->_userid)
1761 class _AdoDbPassUser
1765 * Simple sprintf, no prepare.
1767 * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster
1768 * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1770 * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1775 var $_authmethod = 'AdoDb';
1776 function _AdoDbPassUser($UserName='',$prefs=false) {
1777 if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1778 if ($prefs) $this->_prefs = $prefs;
1779 if (!isset($this->_prefs->_method))
1780 _PassUser::_PassUser($UserName);
1782 if (!$this->isValidName($UserName)) {
1783 trigger_error(_("Invalid username."),E_USER_WARNING);
1786 $this->_userid = $UserName;
1787 $this->getAuthDbh();
1788 $this->_auth_crypt_method = $GLOBALS['request']->_dbi->getAuthParam('auth_crypt_method');
1789 // Don't prepare the configured auth statements anymore
1793 function getPreferences() {
1794 // override the generic slow method here for efficiency
1795 _AnonUser::getPreferences();
1796 $this->getAuthDbh();
1797 if (isset($this->_prefs->_select)) {
1798 $dbh = & $this->_auth_dbi;
1799 $rs = $dbh->Execute(sprintf($this->_prefs->_select, $dbh->qstr($this->_userid)));
1803 $prefs_blob = @$rs->fields['prefs'];
1805 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1806 $updated = $this->_prefs->updatePrefs($restored_from_db);
1807 //$this->_prefs = new UserPreferences($restored_from_db);
1808 return $this->_prefs;
1812 if ($this->_HomePagehandle) {
1813 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1814 $updated = $this->_prefs->updatePrefs($restored_from_page);
1815 //$this->_prefs = new UserPreferences($restored_from_page);
1816 return $this->_prefs;
1819 return $this->_prefs;
1822 function setPreferences($prefs, $id_only=false) {
1823 // if the prefs are changed
1824 if (_AnonUser::setPreferences($prefs, 1)) {
1826 $packed = $this->_prefs->store();
1827 //$user = $request->_user;
1828 //unset($user->_auth_dbi);
1829 if (!$id_only and isset($this->_prefs->_update)) {
1830 $this->getAuthDbh();
1831 $dbh = &$this->_auth_dbi;
1832 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1833 $dbh->qstr($packed),
1834 $dbh->qstr($this->_userid)));
1835 $db_result->Close();
1837 if ($this->_HomePagehandle and $this->_HomePagehandle->get('pref'))
1838 $this->_HomePagehandle->set('pref', '');
1840 //store prefs in homepage, not in cookie
1841 if ($this->_HomePagehandle and !$id_only)
1842 $this->_HomePagehandle->set('pref', $packed);
1844 return count($this->_prefs->unpack($packed));
1849 function userExists() {
1850 $this->getAuthDbh();
1851 $dbh = &$this->_auth_dbi;
1852 if (!$dbh) { // needed?
1853 return $this->_tryNextUser();
1855 if (!$this->isValidName()) {
1856 return $this->_tryNextUser();
1858 $dbi =& $GLOBALS['request']->_dbi;
1859 if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) {
1860 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1861 array("userid","password"));
1863 if (empty($this->_authselect))
1864 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1865 'DBAUTH_AUTH_CHECK', 'ADODB'),
1867 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1868 if ($this->_auth_crypt_method == 'crypt') {
1869 $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid)));
1878 if (! $dbi->getAuthParam('auth_user_exists'))
1879 trigger_error(fmt("%s is missing", 'DBAUTH_AUTH_USER_EXISTS'),
1881 $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'), 'userid');
1882 $rs = $dbh->Execute(sprintf($this->_authcheck, $dbh->qstr($this->_userid)));
1890 // maybe the user is allowed to create himself. Generally not wanted in
1891 // external databases, but maybe wanted for the wiki database, for performance
1893 if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) {
1894 $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'),
1895 array("userid", "password"));
1897 if (!empty($this->_authcreate) and
1898 isset($GLOBALS['HTTP_POST_VARS']['auth']) and
1899 isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd']))
1901 $dbh->Execute(sprintf($this->_authcreate,
1902 $dbh->qstr($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1903 $dbh->qstr($this->_userid)));
1907 return $this->_tryNextUser();
1910 function checkPass($submitted_password) {
1911 //global $DBAuthParams;
1912 $this->getAuthDbh();
1913 if (!$this->_auth_dbi) { // needed?
1914 return $this->_tryNextPass($submitted_password);
1916 if (!$this->isValidName()) {
1917 return $this->_tryNextPass($submitted_password);
1919 $dbh =& $this->_auth_dbi;
1920 $dbi =& $GLOBALS['request']->_dbi;
1921 if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) {
1922 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1923 array("userid", "password"));
1925 if (!isset($this->_authselect))
1926 $this->userExists();
1927 if (!isset($this->_authselect))
1928 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1929 'DBAUTH_AUTH_CHECK', 'ADODB'),
1931 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1932 if ($this->_auth_crypt_method == 'crypt') {
1933 $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid)));
1935 $stored_password = $rs->fields['password'];
1937 $result = $this->_checkPass($submitted_password, $stored_password);
1943 $rs = $dbh->Execute(sprintf($this->_authselect,
1944 $dbh->qstr($submitted_password),
1945 $dbh->qstr($this->_userid)));
1946 if (isset($rs->fields['ok']))
1947 $okay = $rs->fields['ok'];
1948 elseif (isset($rs->fields[1]))
1949 $okay = $rs->fields[1];
1951 $okay = reset($rs->fields);
1954 $result = !empty($okay);
1958 $this->_level = WIKIAUTH_USER;
1959 return $this->_level;
1961 return $this->_tryNextPass($submitted_password);
1965 function mayChangePass() {
1966 return $GLOBALS['request']->_dbi->getAuthParam('auth_update');
1969 function storePass($submitted_password) {
1970 $this->getAuthDbh();
1971 $dbh = &$this->_auth_dbi;
1972 $dbi =& $GLOBALS['request']->_dbi;
1973 if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) {
1974 $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'),
1975 array("userid", "password"));
1977 if (!isset($this->_authupdate)) {
1978 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1979 'DBAUTH_AUTH_UPDATE', 'ADODB'),
1984 if ($this->_auth_crypt_method == 'crypt') {
1985 if (function_exists('crypt'))
1986 $submitted_password = crypt($submitted_password);
1988 $rs = $dbh->Execute(sprintf($this->_authupdate,
1989 $dbh->qstr($submitted_password),
1990 $dbh->qstr($this->_userid)
2000 * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in config/config.ini
2002 * Preferences are handled in _PassUser
2005 function checkPass($submitted_password) {
2006 global $LDAP_SET_OPTION;
2008 $this->_authmethod = 'LDAP';
2009 $userid = $this->_userid;
2010 if (!$this->isValidName()) {
2011 return $this->_tryNextPass($submitted_password);
2013 if (strstr($userid,'*')) {
2014 trigger_error(fmt("Invalid username '%s' for LDAP Auth",$userid),E_USER_WARNING);
2015 return WIKIAUTH_FORBIDDEN;
2018 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
2019 if (!empty($LDAP_SET_OPTION)) {
2020 foreach ($LDAP_SET_OPTION as $key => $value) {
2021 if (is_string($key) and defined($key))
2022 $key = constant($key);
2023 ldap_set_option($ldap,$key,$value);
2026 if (defined('LDAP_AUTH_USER'))
2027 if (defined('LDAP_AUTH_PASSWORD'))
2028 // Windows Active Directory Server is strict
2029 $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD);
2031 $r = @ldap_bind($ldap,LDAP_AUTH_USER);
2033 $r = @ldap_bind($ldap); // this is an anonymous bind
2035 // Need to set the right root search information. see ../index.php
2036 $st_search = defined('LDAP_SEARCH_FIELD')
2037 ? LDAP_SEARCH_FIELD."=$userid"
2039 $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
2040 $info = ldap_get_entries($ldap, $sr);
2041 // there may be more hits with this userid.
2042 // of course it would be better to narrow down the BASE_DN
2043 for ($i = 0; $i < $info["count"]; $i++) {
2044 $dn = $info[$i]["dn"];
2045 // The password is still plain text.
2046 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
2047 // ldap_bind will return TRUE if everything matches
2049 $this->_level = WIKIAUTH_USER;
2050 return $this->_level;
2054 trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST),
2059 return $this->_tryNextPass($submitted_password);
2062 function userExists() {
2063 global $LDAP_SET_OPTION;
2065 $userid = $this->_userid;
2066 if (strstr($userid,'*')) {
2067 trigger_error(fmt("Invalid username '%s' for LDAP Auth",$userid),E_USER_WARNING);
2068 return WIKIAUTH_FORBIDDEN;
2070 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
2071 if (!empty($LDAP_SET_OPTION)) {
2072 foreach ($LDAP_SET_OPTION as $key => $value) {
2073 if (is_string($key) and defined($key))
2074 $key = constant($key);
2075 ldap_set_option($ldap,$key,$value);
2078 if (defined('LDAP_AUTH_USER'))
2079 if (defined('LDAP_AUTH_PASSWORD'))
2080 // Windows Active Directory Server is strict
2081 $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD);
2083 $r = @ldap_bind($ldap,LDAP_AUTH_USER);
2085 $r = @ldap_bind($ldap); // this is an anonymous bind
2087 // Need to set the right root search information. see ../index.php
2088 $st_search = defined('LDAP_SEARCH_FIELD')
2089 ? LDAP_SEARCH_FIELD."=$userid"
2091 $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
2092 $info = ldap_get_entries($ldap, $sr);
2094 if ($info["count"] > 0) {
2099 trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
2102 return $this->_tryNextUser();
2105 function mayChangePass() {
2114 * Define the var IMAP_AUTH_HOST in config/config.ini (with port probably)
2116 * Preferences are handled in _PassUser
2119 function checkPass($submitted_password) {
2120 if (!$this->isValidName()) {
2121 return $this->_tryNextPass($submitted_password);
2123 $userid = $this->_userid;
2124 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
2125 $userid, $submitted_password, OP_HALFOPEN );
2128 $this->_authmethod = 'IMAP';
2129 $this->_level = WIKIAUTH_USER;
2130 return $this->_level;
2132 trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
2135 return $this->_tryNextPass($submitted_password);
2138 //CHECKME: this will not be okay for the auth policy strict
2139 function userExists() {
2141 if (checkPass($this->_prefs->get('passwd')))
2144 return $this->_tryNextUser();
2147 function mayChangePass() {
2154 extends _IMAPPassUser {
2156 * Define the var POP3_AUTH_HOST in config/config.ini
2157 * Preferences are handled in _PassUser
2159 function checkPass($submitted_password) {
2160 if (!$this->isValidName()) {
2161 return $this->_tryNextPass($submitted_password);
2163 $userid = $this->_userid;
2164 $pass = $submitted_password;
2165 $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost:110';
2166 if (defined('POP3_AUTH_PORT'))
2167 $port = POP3_AUTH_PORT;
2168 elseif (strstr($host,':')) {
2169 list(,$port) = split(':',$host);
2174 $fp = fsockopen($host, $port, $errno, $errstr, 10);
2176 // Get welcome string
2177 $line = fgets($fp, 1024);
2178 if (! strncmp("+OK ", $line, 4)) {
2180 fputs($fp, "user $userid\n");
2182 $line = fgets($fp, 1024);
2183 if (! strncmp("+OK ", $line, 4)) {
2185 fputs($fp, "pass $pass\n");
2187 $line = fgets($fp, 1024);
2188 if (! strncmp("+OK ", $line, 4)) {
2193 // quit the connection
2194 fputs($fp, "quit\n");
2195 // Get the sayonara message
2196 $line = fgets($fp, 1024);
2199 trigger_error(_("Couldn't connect to %s","POP3_AUTH_HOST ".$host.':'.$port),
2202 $this->_authmethod = 'POP3';
2204 $this->_level = WIKIAUTH_USER;
2206 $this->_level = WIKIAUTH_ANON;
2208 return $this->_level;
2215 * Check users defined in a .htaccess style file
2216 * username:crypt\n...
2218 * Preferences are handled in _PassUser
2221 var $_file, $_may_change;
2223 // This can only be called from _PassUser, because the parent class
2224 // sets the pref methods, before this class is initialized.
2225 function _FilePassUser($UserName='', $prefs=false, $file='') {
2226 if (!$this->_prefs and isa($this, "_FilePassUser")) {
2227 if ($prefs) $this->_prefs = $prefs;
2228 if (!isset($this->_prefs->_method))
2229 _PassUser::_PassUser($UserName);
2231 $this->_userid = $UserName;
2232 // read the .htaccess style file. We use our own copy of the standard pear class.
2233 //include_once 'lib/pear/File_Passwd.php';
2234 $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
2235 if (empty($file) and defined('AUTH_USER_FILE'))
2236 $file = AUTH_USER_FILE;
2237 include_once(dirname(__FILE__)."/pear/File_Passwd.php"); // same style as in main.php
2238 // "__PHP_Incomplete_Class"
2239 if (!empty($file) or empty($this->_file) or !isa($this->_file,"File_Passwd"))
2240 $this->_file = new File_Passwd($file, false, $file.'.lock');
2246 function mayChangePass() {
2247 return $this->_may_change;
2250 function userExists() {
2251 if (!$this->isValidName()) {
2252 return $this->_tryNextUser();
2254 $this->_authmethod = 'File';
2255 if (isset($this->_file->users[$this->_userid]))
2258 return $this->_tryNextUser();
2261 function checkPass($submitted_password) {
2262 if (!$this->isValidName()) {
2263 return $this->_tryNextPass($submitted_password);
2265 //include_once 'lib/pear/File_Passwd.php';
2266 if ($this->_file->verifyPassword($this->_userid, $submitted_password)) {
2267 $this->_authmethod = 'File';
2268 $this->_level = WIKIAUTH_USER;
2269 return $this->_level;
2272 return $this->_tryNextPass($submitted_password);
2275 function storePass($submitted_password) {
2276 if (!$this->isValidName()) {
2279 if ($this->_may_change) {
2280 $this->_file = new File_Passwd($this->_file->_filename, true, $this->_file->_filename.'.lock');
2281 $result = $this->_file->modUser($this->_userid,$submitted_password);
2282 $this->_file->close();
2283 $this->_file = new File_Passwd($this->_file->_filename, false);
2292 * Insert more auth classes here...
2293 * For example a customized db class for another db connection
2294 * or a socket-based auth server.
2300 * For security, this class should not be extended. Instead, extend
2301 * from _PassUser (think of this as unix "root").
2303 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
2304 * Other members of the Administrators group must raise their level otherwise somehow.
2305 * Currently every member is a AdminUser, which will not work for the various
2311 function mayChangePass() {
2314 function checkPass($submitted_password) {
2315 if ($this->_userid == ADMIN_USER)
2316 $stored_password = ADMIN_PASSWD;
2318 return $this->_tryNextPass($submitted_password);
2319 // TODO: safety check if really member of the ADMIN group?
2320 $stored_password = $this->_pref->get('passwd');
2322 if ($this->_checkPass($submitted_password, $stored_password)) {
2323 $this->_level = WIKIAUTH_ADMIN;
2324 return $this->_level;
2326 return $this->_tryNextPass($submitted_password);
2327 //$this->_level = WIKIAUTH_ANON;
2328 //return $this->_level;
2332 function storePass($submitted_password) {
2337 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2339 * Various data classes for the preference types,
2340 * to support get, set, sanify (range checking, ...)
2341 * update() will do the neccessary side-effects if a
2342 * setting gets changed (theme, language, ...)
2345 class _UserPreference
2349 function _UserPreference ($default_value) {
2350 $this->default_value = $default_value;
2353 function sanify ($value) {
2354 return (string)$value;
2357 function get ($name) {
2358 if (isset($this->{$name}))
2359 return $this->{$name};
2361 return $this->default_value;
2364 function getraw ($name) {
2365 if (!empty($this->{$name}))
2366 return $this->{$name};
2369 // stores the value as $this->$name, and not as $this->value (clever?)
2370 function set ($name, $value) {
2372 $value = $this->sanify($value);
2373 if ($this->get($name) != $value) {
2374 $this->update($value);
2377 if ($value != $this->default_value) {
2378 $this->{$name} = $value;
2380 unset($this->{$name});
2385 // default: no side-effects
2386 function update ($value) {
2391 class _UserPreference_numeric
2392 extends _UserPreference
2394 function _UserPreference_numeric ($default, $minval = false,
2396 $this->_UserPreference((double)$default);
2397 $this->_minval = (double)$minval;
2398 $this->_maxval = (double)$maxval;
2401 function sanify ($value) {
2402 $value = (double)$value;
2403 if ($this->_minval !== false && $value < $this->_minval)
2404 $value = $this->_minval;
2405 if ($this->_maxval !== false && $value > $this->_maxval)
2406 $value = $this->_maxval;
2411 class _UserPreference_int
2412 extends _UserPreference_numeric
2414 function _UserPreference_int ($default, $minval = false, $maxval = false) {
2415 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
2418 function sanify ($value) {
2419 return (int)parent::sanify((int)$value);
2423 class _UserPreference_bool
2424 extends _UserPreference
2426 function _UserPreference_bool ($default = false) {
2427 $this->_UserPreference((bool)$default);
2430 function sanify ($value) {
2431 if (is_array($value)) {
2432 /* This allows for constructs like:
2434 * <input type="hidden" name="pref[boolPref][]" value="0" />
2435 * <input type="checkbox" name="pref[boolPref][]" value="1" />
2437 * (If the checkbox is not checked, only the hidden input
2438 * gets sent. If the checkbox is sent, both inputs get
2441 foreach ($value as $val) {
2447 return (bool) $value;
2451 class _UserPreference_language
2452 extends _UserPreference
2454 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
2455 $this->_UserPreference($default);
2458 // FIXME: check for valid locale
2459 function sanify ($value) {
2460 // Revert to DEFAULT_LANGUAGE if user does not specify
2461 // language in UserPreferences or chooses <system language>.
2462 if ($value == '' or empty($value))
2463 $value = DEFAULT_LANGUAGE;
2465 return (string) $value;
2468 function update ($newvalue) {
2469 if (! $this->_init ) {
2470 // invalidate etag to force fresh output
2471 $GLOBALS['request']->setValidators(array('%mtime' => false));
2472 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
2477 class _UserPreference_theme
2478 extends _UserPreference
2480 function _UserPreference_theme ($default = THEME) {
2481 $this->_UserPreference($default);
2484 function sanify ($value) {
2485 if (!empty($value) and FindFile($this->_themefile($value)))
2487 return $this->default_value;
2490 function update ($newvalue) {
2492 // invalidate etag to force fresh output
2493 if (! $this->_init )
2494 $GLOBALS['request']->setValidators(array('%mtime' => false));
2496 include_once($this->_themefile($newvalue));
2497 if (empty($WikiTheme))
2498 include_once($this->_themefile(THEME));
2501 function _themefile ($theme) {
2502 return "themes/$theme/themeinfo.php";
2506 class _UserPreference_notify
2507 extends _UserPreference
2509 function sanify ($value) {
2513 return $this->default_value;
2516 /** update to global user prefs: side-effect on set notify changes
2517 * use a global_data notify hash:
2518 * notify = array('pagematch' => array(userid => ('email' => mail,
2519 * 'verified' => 0|1),
2523 function update ($value) {
2524 if (!empty($this->_init)) return;
2525 $dbh = $GLOBALS['request']->getDbh();
2526 $notify = $dbh->get('notify');
2531 // expand to existing pages only or store matches?
2532 // for now we store (glob-style) matches which is easier for the user
2533 $pages = $this->_page_split($value);
2534 // Limitation: only current user.
2535 $user = $GLOBALS['request']->getUser();
2536 if (!$user or !method_exists($user,'UserName')) return;
2537 // This fails with php5 and a WIKI_ID cookie:
2538 $userid = $user->UserName();
2539 $email = $user->_prefs->get('email');
2540 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
2541 // check existing notify hash and possibly delete pages for email
2542 if (!empty($data)) {
2543 foreach ($data as $page => $users) {
2544 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
2545 unset($data[$page][$userid]);
2547 if (count($data[$page]) == 0)
2548 unset($data[$page]);
2551 // add the new pages
2552 if (!empty($pages)) {
2553 foreach ($pages as $page) {
2554 if (!isset($data[$page]))
2555 $data[$page] = array();
2556 if (!isset($data[$page][$userid])) {
2557 // should we really store the verification notice here or
2558 // check it dynamically at every page->save?
2560 $data[$page][$userid] = array('email' => $email,
2561 'verified' => $verified);
2563 $data[$page][$userid] = array('email' => $email);
2568 // store users changes
2569 $dbh->set('notify',$data);
2572 /** split the user-given comma or whitespace delimited pagenames
2575 function _page_split($value) {
2576 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
2580 class _UserPreference_email
2581 extends _UserPreference
2583 function sanify($value) {
2584 // check for valid email address
2585 if ($this->get('email') == $value and $this->getraw('emailVerified'))
2588 if ($value == 1 or $value === true)
2590 list($ok,$msg) = ValidateMail($value,'noconnect');
2594 trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
2595 return $this->default_value;
2599 /** Side-effect on email changes:
2600 * Send a verification mail or for now just a notification email.
2601 * For true verification (value = 2), we'd need a mailserver hook.
2603 function update($value) {
2604 if (!empty($this->_init)) return;
2605 $verified = $this->getraw('emailVerified');
2607 if (($value == 1 or $value === true) and $verified)
2609 if (!empty($value) and !$verified) {
2610 list($ok,$msg) = ValidateMail($value);
2611 if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
2612 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
2613 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true))))
2614 $this->set('emailVerified',1);
2619 /** Check for valid email address
2620 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
2622 function ValidateMail($email, $noconnect=false) {
2623 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
2625 // well, technically ".a.a.@host.com" is also valid
2626 if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
2628 $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
2632 return array(true,sprintf(_("E-Mail address '%s' is properly formatted"), $email));
2634 list ( $Username, $Domain ) = split ("@",$email);
2635 //Todo: getmxrr workaround on windows or manual input field to verify it manually
2636 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
2637 $ConnectAddress = $MXHost[0];
2639 $ConnectAddress = $Domain;
2641 $Connect = fsockopen ( $ConnectAddress, 25 );
2643 if (ereg("^220", $Out = fgets($Connect, 1024))) {
2644 fputs ($Connect, "HELO $HTTP_HOST\r\n");
2645 $Out = fgets ( $Connect, 1024 );
2646 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
2647 $From = fgets ( $Connect, 1024 );
2648 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
2649 $To = fgets ($Connect, 1024);
2650 fputs ($Connect, "QUIT\r\n");
2652 if (!ereg ("^250", $From)) {
2654 $result[1]="Server rejected address: ". $From;
2657 if (!ereg ( "^250", $To )) {
2659 $result[1]="Server rejected address: ". $To;
2664 $result[1] = "No response from server";
2669 $result[1]="Can not connect E-Mail server.";
2673 $result[1]="E-Mail address '$email' appears to be valid.";
2675 } // end of function
2677 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2682 * This object holds the $request->_prefs subobjects.
2683 * A simple packed array of non-default values get's stored as cookie,
2684 * homepage, or database, which are converted to the array of
2686 * We don't store the objects, because otherwise we will
2687 * not be able to upgrade any subobject. And it's a waste of space also.
2690 class UserPreferences
2692 function UserPreferences($saved_prefs = false) {
2693 // userid stored too, to ensure the prefs are being loaded for
2694 // the correct (currently signing in) userid if stored in a
2696 // Update: for db prefs we disallow passwd.
2697 // userid is needed for pref reflexion. current pref must know its username,
2698 // if some app needs prefs from different users, different from current user.
2701 'userid' => new _UserPreference(''),
2702 'passwd' => new _UserPreference(''),
2703 'autologin' => new _UserPreference_bool(),
2704 //'emailVerified' => new _UserPreference_emailVerified(),
2705 //fixed: store emailVerified as email parameter, 1.3.8
2706 'email' => new _UserPreference_email(''),
2707 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
2708 'theme' => new _UserPreference_theme(THEME),
2709 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
2710 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2712 EDITWIDTH_MAX_COLS),
2713 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
2714 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2715 EDITHEIGHT_MIN_ROWS,
2716 EDITHEIGHT_DEFAULT_ROWS),
2717 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2718 TIMEOFFSET_MIN_HOURS,
2719 TIMEOFFSET_MAX_HOURS),
2720 'relativeDates' => new _UserPreference_bool(),
2721 'googleLink' => new _UserPreference_bool(), // 1.3.10
2723 // add custom theme-specific pref types:
2724 // FIXME: on theme changes the wiki_user session pref object will fail.
2725 // We will silently ignore this.
2726 if (!empty($customUserPreferenceColumns))
2727 $this->_prefs = array_merge($this->_prefs,$customUserPreferenceColumns);
2729 if (isset($this->_method) and $this->_method == 'SQL') {
2730 //unset($this->_prefs['userid']);
2731 unset($this->_prefs['passwd']);
2734 if (is_array($saved_prefs)) {
2735 foreach ($saved_prefs as $name => $value)
2736 $this->set($name, $value);
2740 function _getPref($name) {
2741 if ($name == 'emailVerified')
2743 if (!isset($this->_prefs[$name])) {
2744 if ($name == 'passwd2') return false;
2745 if ($name == 'passwd') return false;
2746 trigger_error("$name: unknown preference", E_USER_NOTICE);
2749 return $this->_prefs[$name];
2752 // get the value or default_value of the subobject
2753 function get($name) {
2754 if ($_pref = $this->_getPref($name))
2755 if ($name == 'emailVerified')
2756 return $_pref->getraw($name);
2758 return $_pref->get($name);
2763 // check and set the new value in the subobject
2764 function set($name, $value) {
2765 $pref = $this->_getPref($name);
2766 if ($pref === false)
2769 /* do it here or outside? */
2770 if ($name == 'passwd' and
2771 defined('PASSWORD_LENGTH_MINIMUM') and
2772 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2773 //TODO: How to notify the user?
2777 if ($name == 'theme' and $value == '')
2780 if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
2781 if ($name == 'emailVerified') $newvalue = $value;
2782 else $newvalue = $pref->sanify($value);
2783 $pref->set($name,$newvalue);
2785 $this->_prefs[$name] =& $pref;
2789 * use init to avoid update on set
2791 function updatePrefs($prefs, $init = false) {
2793 if ($init) $this->_init = $init;
2794 if (is_object($prefs)) {
2795 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2796 $obj->_init = $init;
2797 if ($obj->get($type) !== $prefs->get($type)) {
2798 if ($obj->set($type,$prefs->get($type)))
2801 foreach (array_keys($this->_prefs) as $type) {
2802 $obj =& $this->_prefs[$type];
2803 $obj->_init = $init;
2804 if ($prefs->get($type) !== $obj->get($type)) {
2805 // special systemdefault prefs: (probably not needed)
2806 if ($type == 'theme' and $prefs->get($type) == '' and $obj->get($type) == THEME) continue;
2807 if ($type == 'lang' and $prefs->get($type) == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue;
2808 if ($this->_prefs[$type]->set($type,$prefs->get($type)))
2812 } elseif (is_array($prefs)) {
2813 //unset($this->_prefs['userid']);
2815 if (isset($this->_method) and
2816 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2817 unset($this->_prefs['passwd']);
2820 // emailVerified at first, the rest later
2821 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2822 $obj->_init = $init;
2823 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2824 if ($obj->set($type,$prefs[$type]))
2827 foreach (array_keys($this->_prefs) as $type) {
2828 $obj =& $this->_prefs[$type];
2829 $obj->_init = $init;
2830 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2831 $prefs[$type] = false;
2832 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2833 $prefs[$type] = (int) $prefs[$type];
2834 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2835 // special systemdefault prefs:
2836 if ($type == 'theme' and $prefs[$type] == '' and $obj->get($type) == THEME) continue;
2837 if ($type == 'lang' and $prefs[$type] == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue;
2838 if ($obj->set($type,$prefs[$type]))
2846 // For now convert just array of objects => array of values
2847 // Todo: the specialized subobjects must override this.
2850 foreach ($this->_prefs as $name => $object) {
2851 if ($value = $object->getraw($name))
2852 $prefs[$name] = $value;
2853 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2854 $prefs['emailVerified'] = $value;
2855 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2856 $prefs['passwd'] = crypt($value);
2859 return $this->pack($prefs);
2862 // packed string or array of values => array of values
2863 // Todo: the specialized subobjects must override this.
2864 function retrieve($packed) {
2865 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2866 $packed = unserialize($packed);
2867 if (!is_array($packed)) return false;
2869 foreach ($packed as $name => $packed_pref) {
2870 if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2871 //legacy: check if it's an old array of objects
2872 // Looks like a serialized object.
2873 // This might fail if the object definition does not exist anymore.
2874 // object with ->$name and ->default_value vars.
2875 $pref = @unserialize($packed_pref);
2877 $pref = @unserialize(base64_decode($packed_pref));
2878 $prefs[$name] = $pref->get($name);
2879 // fix old-style prefs
2880 } elseif (is_numeric($name) and is_array($packed_pref)) {
2881 if (count($packed_pref) == 1) {
2882 list($name,$value) = each($packed_pref);
2883 $prefs[$name] = $value;
2886 $prefs[$name] = @unserialize($packed_pref);
2887 if (empty($prefs[$name]))
2888 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2889 // patched by frederik@pandora.be
2890 if (empty($prefs[$name]))
2891 $prefs[$name] = $packed_pref;
2898 * Check if the given prefs object is different from the current prefs object
2900 function isChanged($other) {
2901 foreach ($this->_prefs as $type => $obj) {
2902 if ($obj->get($type) !== $other->get($type))
2908 function defaultPreferences() {
2910 foreach ($this->_prefs as $key => $obj) {
2911 $prefs[$key] = $obj->default_value;
2918 return $this->_prefs;
2921 function pack($nonpacked) {
2922 return serialize($nonpacked);
2925 function unpack($packed) {
2928 //$packed = base64_decode($packed);
2929 if (substr($packed, 0, 2) == "O:") {
2930 // Looks like a serialized object
2931 return unserialize($packed);
2933 if (substr($packed, 0, 2) == "a:") {
2934 return unserialize($packed);
2936 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2942 return hash($this->_prefs);
2946 /** TODO: new pref storage classes
2947 * These are currently user specific and should be rewritten to be pref specific.
2948 * i.e. $this == $user->_prefs
2950 class CookieUserPreferences
2951 extends UserPreferences
2953 function CookieUserPreferences ($saved_prefs = false) {
2954 //_AnonUser::_AnonUser('',$saved_prefs);
2955 UserPreferences::UserPreferences($saved_prefs);
2959 class PageUserPreferences
2960 extends UserPreferences
2962 function PageUserPreferences ($saved_prefs = false) {
2963 UserPreferences::UserPreferences($saved_prefs);
2967 class PearDbUserPreferences
2968 extends UserPreferences
2970 function PearDbUserPreferences ($saved_prefs = false) {
2971 UserPreferences::UserPreferences($saved_prefs);
2975 class AdoDbUserPreferences
2976 extends UserPreferences
2978 function AdoDbUserPreferences ($saved_prefs = false) {
2979 UserPreferences::UserPreferences($saved_prefs);
2981 function getPreferences() {
2982 // override the generic slow method here for efficiency
2983 _AnonUser::getPreferences();
2984 $this->getAuthDbh();
2985 if (isset($this->_select)) {
2986 $dbh = & $this->_auth_dbi;
2987 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2991 $prefs_blob = $rs->fields['pref_blob'];
2993 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2994 $updated = $this->_prefs->updatePrefs($restored_from_db);
2995 //$this->_prefs = new UserPreferences($restored_from_db);
2996 return $this->_prefs;
3000 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
3001 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
3002 $updated = $this->_prefs->updatePrefs($restored_from_page);
3003 //$this->_prefs = new UserPreferences($restored_from_page);
3004 return $this->_prefs;
3007 return $this->_prefs;
3012 // $Log: not supported by cvs2svn $
3013 // Revision 1.92 2004/06/14 11:31:36 rurban
3014 // renamed global $Theme to $WikiTheme (gforge nameclash)
3015 // inherit PageList default options from PageList
3016 // default sortby=pagename
3017 // use options in PageList_Selectable (limit, sortby, ...)
3018 // added action revert, with button at action=diff
3019 // added option regex to WikiAdminSearchReplace
3021 // Revision 1.91 2004/06/08 14:57:43 rurban
3022 // stupid ldap bug detected by John Cole
3024 // Revision 1.90 2004/06/08 09:31:15 rurban
3025 // fixed typo detected by lucidcarbon (line 1663 assertion)
3027 // Revision 1.89 2004/06/06 16:58:51 rurban
3028 // added more required ActionPages for foreign languages
3029 // install now english ActionPages if no localized are found. (again)
3030 // fixed default anon user level to be 0, instead of -1
3031 // (wrong "required administrator to view this page"...)
3033 // Revision 1.88 2004/06/04 20:32:53 rurban
3034 // Several locale related improvements suggested by Pierrick Meignen
3035 // LDAP fix by John Cole
3036 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
3038 // Revision 1.87 2004/06/04 12:40:21 rurban
3039 // Restrict valid usernames to prevent from attacks against external auth or compromise
3041 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
3042 // Fxied more warnings
3044 // Revision 1.86 2004/06/03 18:06:29 rurban
3045 // fix file locking issues (only needed on write)
3046 // fixed immediate LANG and THEME in-session updates if not stored in prefs
3047 // advanced editpage toolbars (search & replace broken)
3049 // Revision 1.85 2004/06/03 12:46:03 rurban
3050 // fix signout, level must be 0 not -1
3052 // Revision 1.84 2004/06/03 12:36:03 rurban
3053 // fix eval warning on signin
3055 // Revision 1.83 2004/06/03 10:18:19 rurban
3056 // fix User locking issues, new config ENABLE_PAGEPERM
3058 // Revision 1.82 2004/06/03 09:39:51 rurban
3059 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
3061 // Revision 1.81 2004/06/02 18:01:45 rurban
3062 // init global FileFinder to add proper include paths at startup
3063 // adds PHPWIKI_DIR if started from another dir, lib/pear also
3064 // fix slashify for Windows
3065 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
3067 // Revision 1.80 2004/06/02 14:20:27 rurban
3068 // fix adodb DbPassUser login
3070 // Revision 1.79 2004/06/01 15:27:59 rurban
3071 // AdminUser only ADMIN_USER not member of Administrators
3072 // some RateIt improvements by dfrankow
3073 // edit_toolbar buttons
3075 // Revision 1.78 2004/05/27 17:49:06 rurban
3076 // renamed DB_Session to DbSession (in CVS also)
3077 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
3078 // remove leading slash in error message
3079 // added force_unlock parameter to File_Passwd (no return on stale locks)
3080 // fixed adodb session AffectedRows
3081 // added FileFinder helpers to unify local filenames and DATA_PATH names
3082 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
3084 // Revision 1.77 2004/05/18 14:49:51 rurban
3085 // Simplified strings for easier translation
3087 // Revision 1.76 2004/05/18 13:30:04 rurban
3088 // prevent from endless loop with oldstyle warnings
3090 // Revision 1.75 2004/05/16 22:07:35 rurban
3091 // check more config-default and predefined constants
3092 // various PagePerm fixes:
3093 // fix default PagePerms, esp. edit and view for Bogo and Password users
3094 // implemented Creator and Owner
3095 // BOGOUSERS renamed to BOGOUSER
3096 // fixed syntax errors in signin.tmpl
3098 // Revision 1.74 2004/05/15 19:48:33 rurban
3099 // fix some too loose PagePerms for signed, but not authenticated users
3100 // (admin, owner, creator)
3101 // no double login page header, better login msg.
3102 // moved action_pdf to lib/pdf.php
3104 // Revision 1.73 2004/05/15 18:31:01 rurban
3105 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
3107 // Revision 1.72 2004/05/12 10:49:55 rurban
3108 // require_once fix for those libs which are loaded before FileFinder and
3109 // its automatic include_path fix, and where require_once doesn't grok
3110 // dirname(__FILE__) != './lib'
3111 // upgrade fix with PearDB
3112 // navbar.tmpl: remove spaces for IE button alignment
3114 // Revision 1.71 2004/05/10 12:34:47 rurban
3115 // stabilize DbAuthParam statement pre-prozessor:
3116 // try old-style and new-style (double-)quoting
3117 // reject unknown $variables
3118 // use ->prepare() for all calls (again)
3120 // Revision 1.70 2004/05/06 19:26:16 rurban
3121 // improve stability, trying to find the InlineParser endless loop on sf.net
3123 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
3125 // Revision 1.69 2004/05/06 13:56:40 rurban
3126 // Enable the Administrators group, and add the WIKIPAGE group default root page.
3128 // Revision 1.68 2004/05/05 13:37:54 rurban
3129 // Support to remove all UserPreferences
3131 // Revision 1.66 2004/05/03 21:44:24 rurban
3132 // fixed sf,net bug #947264: LDAP options are constants, not strings!
3134 // Revision 1.65 2004/05/03 13:16:47 rurban
3135 // fixed UserPreferences update, esp for boolean and int
3137 // Revision 1.64 2004/05/02 15:10:06 rurban
3138 // new finally reliable way to detect if /index.php is called directly
3139 // and if to include lib/main.php
3140 // new global AllActionPages
3141 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
3142 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
3143 // PageGroupTestOne => subpages
3144 // renamed PhpWikiRss to PhpWikiRecentChanges
3145 // more docs, default configs, ...
3147 // Revision 1.63 2004/05/01 15:59:29 rurban
3148 // more php-4.0.6 compatibility: superglobals
3150 // Revision 1.62 2004/04/29 18:31:24 rurban
3151 // Prevent from warning where no db pref was previously stored.
3153 // Revision 1.61 2004/04/29 17:18:19 zorloc
3154 // 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.
3156 // Revision 1.60 2004/04/27 18:20:54 rurban
3157 // sf.net patch #940359 by rassie
3159 // Revision 1.59 2004/04/26 12:35:21 rurban
3160 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
3161 // File_Passwd is already loaded
3163 // Revision 1.58 2004/04/20 17:08:28 rurban
3164 // Some IniConfig fixes: prepend our private lib/pear dir
3165 // switch from " to ' in the auth statements
3166 // use error handling.
3167 // WikiUserNew changes for the new "'$variable'" syntax
3168 // in the statements
3169 // TODO: optimization to put config vars into the session.
3171 // Revision 1.57 2004/04/19 18:27:45 rurban
3172 // Prevent from some PHP5 warnings (ref args, no :: object init)
3173 // php5 runs now through, just one wrong XmlElement object init missing
3174 // Removed unneccesary UpgradeUser lines
3175 // Changed WikiLink to omit version if current (RecentChanges)
3177 // Revision 1.56 2004/04/19 09:13:24 rurban
3178 // new pref: googleLink
3180 // Revision 1.54 2004/04/18 00:24:45 rurban
3181 // re-use our simple prepare: just for table prefix warnings
3183 // Revision 1.53 2004/04/12 18:29:15 rurban
3184 // exp. Session auth for already authenticated users from another app
3186 // Revision 1.52 2004/04/12 13:04:50 rurban
3187 // added auth_create: self-registering Db users
3189 // removed rating recommendations
3190 // ziplib reformatting
3192 // Revision 1.51 2004/04/11 10:42:02 rurban
3193 // pgsrc/CreatePagePlugin
3195 // Revision 1.50 2004/04/10 05:34:35 rurban
3198 // Revision 1.49 2004/04/07 23:13:18 rurban
3199 // fixed pear/File_Passwd for Windows
3200 // fixed FilePassUser sessions (filehandle revive) and password update
3202 // Revision 1.48 2004/04/06 20:00:10 rurban
3203 // Cleanup of special PageList column types
3204 // Added support of plugin and theme specific Pagelist Types
3205 // Added support for theme specific UserPreferences
3206 // Added session support for ip-based throttling
3207 // sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
3208 // Enhanced postgres schema
3209 // Added DB_Session_dba support
3211 // Revision 1.47 2004/04/02 15:06:55 rurban
3212 // fixed a nasty ADODB_mysql session update bug
3213 // improved UserPreferences layout (tabled hints)
3214 // fixed UserPreferences auth handling
3215 // improved auth stability
3216 // improved old cookie handling: fixed deletion of old cookies with paths
3218 // Revision 1.46 2004/04/01 06:29:51 rurban
3220 // RateIt also for ADODB
3222 // Revision 1.45 2004/03/30 02:14:03 rurban
3223 // fixed yet another Prefs bug
3224 // added generic PearDb_iter
3225 // $request->appendValidators no so strict as before
3226 // added some box plugin methods
3227 // PageList commalist for condensed output
3229 // Revision 1.44 2004/03/27 22:01:03 rurban
3230 // two catches by Konstantin Zadorozhny
3232 // Revision 1.43 2004/03/27 19:40:09 rurban
3233 // init fix and validator reset
3235 // Revision 1.40 2004/03/25 22:54:31 rurban
3238 // Revision 1.38 2004/03/25 17:37:36 rurban
3239 // helper to patch to and from php5 (workaround for stricter parser, no macros in php)
3241 // Revision 1.37 2004/03/25 17:00:31 rurban
3242 // more code to convert old-style pref array to new hash
3244 // Revision 1.36 2004/03/24 19:39:02 rurban
3245 // php5 workaround code (plus some interim debugging code in XmlElement)
3246 // php5 doesn't work yet with the current XmlElement class constructors,
3247 // WikiUserNew does work better than php4.
3248 // rewrote WikiUserNew user upgrading to ease php5 update
3249 // fixed pref handling in WikiUserNew
3250 // added Email Notification
3251 // added simple Email verification
3252 // removed emailVerify userpref subclass: just a email property
3253 // changed pref binary storage layout: numarray => hash of non default values
3254 // print optimize message only if really done.
3255 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
3256 // prefs should be stored in db or homepage, besides the current session.
3258 // Revision 1.35 2004/03/18 22:18:31 rurban
3259 // workaround for php5 object upgrading problem
3261 // Revision 1.34 2004/03/18 21:41:09 rurban
3262 // fixed sqlite support
3263 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
3265 // Revision 1.33 2004/03/16 15:42:04 rurban
3266 // more fixes for undefined property warnings
3268 // Revision 1.32 2004/03/14 16:30:52 rurban
3269 // db-handle session revivification, dba fixes
3271 // Revision 1.31 2004/03/12 23:20:58 rurban
3272 // pref fixes (base64)
3274 // Revision 1.30 2004/03/12 20:59:17 rurban
3275 // important cookie fix by Konstantin Zadorozhny
3276 // new editpage feature: JS_SEARCHREPLACE
3278 // Revision 1.29 2004/03/11 13:30:47 rurban
3279 // fixed File Auth for user and group
3280 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
3282 // Revision 1.28 2004/03/08 18:17:09 rurban
3283 // added more WikiGroup::getMembersOf methods, esp. for special groups
3284 // fixed $LDAP_SET_OPTIONS
3285 // fixed _AuthInfo group methods
3287 // Revision 1.27 2004/03/01 09:35:13 rurban
3288 // fixed DbPassuser pref init; lost userid
3290 // Revision 1.26 2004/02/29 04:10:56 rurban
3291 // new POP3 auth (thanks to BiloBilo: pentothal at despammed dot com)
3292 // fixed syntax error in index.php
3294 // Revision 1.25 2004/02/28 22:25:07 rurban
3295 // First PagePerm implementation:
3297 // $WikiTheme->setAnonEditUnknownLinks(false);
3299 // Layout improvement with dangling links for mostly closed wiki's:
3300 // If false, only users with edit permissions will be presented the
3301 // special wikiunknown class with "?" and Tooltip.
3302 // If true (default), any user will see the ?, but will be presented
3303 // the PrintLoginForm on a click.
3305 // Revision 1.24 2004/02/28 21:14:08 rurban
3306 // generally more PHPDOC docs
3307 // see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
3308 // fxied WikiUserNew pref handling: empty theme not stored, save only
3309 // changed prefs, sql prefs improved, fixed password update,
3310 // removed REPLACE sql (dangerous)
3311 // moved gettext init after the locale was guessed
3312 // + some minor changes
3314 // Revision 1.23 2004/02/27 13:21:17 rurban
3315 // several performance improvements, esp. with peardb
3317 // storepass seperated from prefs if defined so
3318 // stacked and strict still not working
3320 // Revision 1.22 2004/02/27 05:15:40 rurban
3321 // more stability. detected by Micki
3323 // Revision 1.21 2004/02/26 20:43:49 rurban
3324 // new HttpAuthPassUser class (forces http auth if in the auth loop)
3325 // fixed user upgrade: don't return _PassUser in the first hand.
3327 // Revision 1.20 2004/02/26 01:29:11 rurban
3328 // important fixes: endless loops in certain cases. minor rewrite
3330 // Revision 1.19 2004/02/25 17:15:17 rurban
3331 // improve stability
3333 // Revision 1.18 2004/02/24 15:20:05 rurban
3334 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
3336 // Revision 1.17 2004/02/17 12:16:42 rurban
3337 // started with changePass support. not yet used.
3339 // Revision 1.16 2004/02/15 22:23:45 rurban
3340 // oops, fixed showstopper (endless recursion)
3342 // Revision 1.15 2004/02/15 21:34:37 rurban
3343 // PageList enhanced and improved.
3344 // fixed new WikiAdmin... plugins
3345 // editpage, Theme with exp. htmlarea framework
3346 // (htmlarea yet committed, this is really questionable)
3347 // WikiUser... code with better session handling for prefs
3348 // enhanced UserPreferences (again)
3349 // RecentChanges for show_deleted: how should pages be deleted then?
3351 // Revision 1.14 2004/02/15 17:30:13 rurban
3352 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
3353 // fixed getPreferences() (esp. from sessions)
3354 // fixed setPreferences() (update and set),
3355 // fixed AdoDb DB statements,
3356 // update prefs only at UserPreferences POST (for testing)
3357 // unified db prefs methods (but in external pref classes yet)
3359 // Revision 1.13 2004/02/09 03:58:12 rurban
3360 // for now default DB_SESSION to false
3362 // * not existing perms will now query the parent, and not
3363 // return the default perm
3364 // * added pagePermissions func which returns the object per page
3365 // * added getAccessDescription
3367 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
3368 // * force init of authdbh in the 2 db classes
3370 // * fixed session handling (not triple auth request anymore)
3371 // * don't store cookie prefs with sessions
3372 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
3374 // Revision 1.12 2004/02/07 10:41:25 rurban
3375 // fixed auth from session (still double code but works)
3377 // fixed DbPassUser upgrade and policy=old
3380 // Revision 1.11 2004/02/03 09:45:39 rurban
3381 // LDAP cleanup, start of new Pref classes
3383 // Revision 1.10 2004/02/01 09:14:11 rurban
3384 // Started with Group_Ldap (not yet ready)
3385 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
3386 // fixed some configurator vars
3387 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
3388 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
3389 // USE_DB_SESSION defaults to true on SQL
3390 // changed GROUP_METHOD definition to string, not constants
3391 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
3392 // create users. (Not to be used with external databases generally, but
3393 // with the default internal user table)
3395 // fixed the IndexAsConfigProblem logic. this was flawed:
3396 // scripts which are the same virtual path defined their own lib/main call
3397 // (hmm, have to test this better, phpwiki.sf.net/demo works again)
3399 // Revision 1.9 2004/01/30 19:57:58 rurban
3400 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
3402 // Revision 1.8 2004/01/30 18:46:15 rurban
3403 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
3405 // Revision 1.7 2004/01/27 23:23:39 rurban
3406 // renamed ->Username => _userid for consistency
3407 // renamed mayCheckPassword => mayCheckPass
3408 // fixed recursion problem in WikiUserNew
3409 // fixed bogo login (but not quite 100% ready yet, password storage)
3411 // Revision 1.6 2004/01/26 09:17:49 rurban
3412 // * changed stored pref representation as before.
3413 // the array of objects is 1) bigger and 2)
3414 // less portable. If we would import packed pref
3415 // objects and the object definition was changed, PHP would fail.
3416 // This doesn't happen with an simple array of non-default values.
3417 // * use $prefs->retrieve and $prefs->store methods, where retrieve
3418 // understands the interim format of array of objects also.
3419 // * simplified $prefs->get() and fixed $prefs->set()
3420 // * added $user->_userid and class '_WikiUser' portability functions
3421 // * fixed $user object ->_level upgrading, mostly using sessions.
3422 // this fixes yesterdays problems with loosing authorization level.
3423 // * fixed WikiUserNew::checkPass to return the _level
3424 // * fixed WikiUserNew::isSignedIn
3425 // * added explodePageList to class PageList, support sortby arg
3426 // * fixed UserPreferences for WikiUserNew
3427 // * fixed WikiPlugin for empty defaults array
3428 // * UnfoldSubpages: added pagename arg, renamed pages arg,
3429 // removed sort arg, support sortby arg
3431 // Revision 1.5 2004/01/25 03:05:00 rurban
3432 // First working version, but has some problems with the current main loop.
3433 // Implemented new auth method dispatcher and policies, all the external
3434 // _PassUser classes (also for ADODB and Pear DB).
3435 // The two global funcs UserExists() and CheckPass() are probably not needed,
3436 // since the auth loop is done recursively inside the class code, upgrading
3437 // the user class within itself.
3438 // Note: When a higher user class is returned, this doesn't mean that the user
3439 // is authorized, $user->_level is still low, and only upgraded on successful
3442 // Revision 1.4 2003/12/07 19:29:48 carstenklapp
3443 // Code Housecleaning: fixed syntax errors. (php -l *.php)
3445 // Revision 1.3 2003/12/06 19:10:46 carstenklapp
3446 // Finished off logic for determining user class, including
3447 // PassUser. Removed ability of BogoUser to save prefs into a page.
3449 // Revision 1.2 2003/12/03 21:45:48 carstenklapp
3450 // Added admin user, password user, and preference classes. Added
3451 // password checking functions for users and the admin. (Now the easy
3452 // parts are nearly done).
3454 // Revision 1.1 2003/12/02 05:46:36 carstenklapp
3455 // Complete rewrite of WikiUser.php.
3457 // This should make it easier to hook in user permission groups etc. some
3458 // time in the future. Most importantly, to finally get UserPreferences
3459 // fully working properly for all classes of users: AnonUser, BogoUser,
3460 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
3461 // want a cookie or not, and to bring back optional AutoLogin with the
3462 // UserName stored in a cookie--something that was lost after PhpWiki had
3463 // dropped the default http auth login method.
3465 // Added WikiUser classes which will (almost) work together with existing
3466 // UserPreferences class. Other parts of PhpWiki need to be updated yet
3467 // before this code can be hooked up.
3473 // c-basic-offset: 4
3474 // c-hanging-comment-ender-p: nil
3475 // indent-tabs-mode: nil