2 rcs_id('$Id: WikiUserNew.php,v 1.110 2004-10-14 19:19:33 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.
82 * Update: not needed anymore. we use eval to fool the load-time syntax checker.
84 * 6) enforced new cookie policy: prefs don't get stored in cookies
85 * anymore, only in homepage and/or database, but always in the
86 * current session. old pref cookies will get deleted.
88 * 7) Certain themes should be able to extend the predefined list
89 * of preferences. Display/editing is done in the theme specific userprefs.tmpl,
90 * but storage must be extended to the Get/SetPreferences methods.
91 * <theme>/themeinfo.php must provide CustomUserPreferences:
92 * A list of name => _UserPreference class pairs.
95 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
96 define('WIKIAUTH_ANON', 0); // Not signed in.
97 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
98 define('WIKIAUTH_USER', 2); // Bogo user with a password.
99 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
100 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
102 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
103 if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
105 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
106 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
107 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
109 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
110 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
111 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
113 define('TIMEOFFSET_MIN_HOURS', -26);
114 define('TIMEOFFSET_MAX_HOURS', 26);
115 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
118 * There are be the following constants in config/config.ini to
119 * establish login parameters:
121 * ALLOW_ANON_USER default true
122 * ALLOW_ANON_EDIT default true
123 * ALLOW_BOGO_LOGIN default true
124 * ALLOW_USER_PASSWORDS default true
125 * PASSWORD_LENGTH_MINIMUM default 6 ?
127 * To require user passwords for editing:
128 * ALLOW_ANON_USER = true
129 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
130 * ALLOW_BOGO_LOGIN = false
131 * ALLOW_USER_PASSWORDS = true
133 * To establish a COMPLETELY private wiki, such as an internal
135 * ALLOW_ANON_USER = false
136 * (and probably require user passwords as described above). In this
137 * case the user will be prompted to login immediately upon accessing
140 * There are other possible combinations, but the typical wiki (such
141 * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
146 // The last object in the row is the bad guy...
147 if (!is_array($USER_AUTH_ORDER))
148 $USER_AUTH_ORDER = array("Forbidden");
150 $USER_AUTH_ORDER[] = "Forbidden";
152 // Local convenience functions.
153 function _isAnonUserAllowed() {
154 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
156 function _isBogoUserAllowed() {
157 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
159 function _isUserPasswordsAllowed() {
160 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
163 // Possibly upgrade userobject functions.
164 function _determineAdminUserOrOtherUser($UserName) {
165 // Sanity check. User name is a condition of the definition of the
166 // _AdminUser, _BogoUser and _passuser.
168 return $GLOBALS['ForbiddenUser'];
170 //FIXME: check admin membership later at checkPass. now we cannot raise the level.
171 //$group = &WikiGroup::getGroup($GLOBALS['request']);
172 if ($UserName == ADMIN_USER)
173 return new _AdminUser($UserName);
174 /* elseif ($group->isMember(GROUP_ADMIN)) {
175 return _determineBogoUserOrPassUser($UserName);
179 return _determineBogoUserOrPassUser($UserName);
182 function _determineBogoUserOrPassUser($UserName) {
183 global $ForbiddenUser;
185 // Sanity check. User name is a condition of the definition of
186 // _BogoUser and _PassUser.
188 return $ForbiddenUser;
190 // Check for password and possibly upgrade user object.
191 // $_BogoUser = new _BogoUser($UserName);
192 if (_isBogoUserAllowed()) {
193 $_BogoUser = new _BogoLoginPassUser($UserName);
194 if ($_BogoUser->userExists())
197 if (_isUserPasswordsAllowed()) {
198 // PassUsers override BogoUsers if a password is stored
199 if (isset($_BogoUser) and isset($_BogoUser->_prefs) and $_BogoUser->_prefs->get('passwd'))
200 return new _PassUser($UserName,$_BogoUser->_prefs);
202 $_PassUser = new _PassUser($UserName,isset($_BogoUser) ? $_BogoUser->_prefs : false);
203 if ($_PassUser->userExists())
207 // No Bogo- or PassUser exists, or
208 // passwords are not allowed, and bogo is disallowed too.
209 // (Only the admin can sign in).
210 return $ForbiddenUser;
214 * Primary WikiUser function, called by lib/main.php.
216 * This determines the user's type and returns an appropriate user
217 * object. lib/main.php then querys the resultant object for password
218 * validity as necessary.
220 * If an _AnonUser object is returned, the user may only browse pages
221 * (and save prefs in a cookie).
223 * To disable access but provide prefs the global $ForbiddenUser class
224 * is returned. (was previously false)
227 function WikiUser ($UserName = '') {
228 global $ForbiddenUser;
230 //Maybe: Check sessionvar for username & save username into
231 //sessionvar (may be more appropriate to do this in lib/main.php).
233 $ForbiddenUser = new _ForbiddenUser($UserName);
234 // Found a user name.
235 return _determineAdminUserOrOtherUser($UserName);
237 elseif (!empty($_SESSION['userid'])) {
238 // Found a user name.
239 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
240 return _determineAdminUserOrOtherUser($_SESSION['userid']);
243 // Check for autologin pref in cookie and possibly upgrade
244 // user object to another type.
245 $_AnonUser = new _AnonUser();
246 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
247 // Found a user name.
248 $ForbiddenUser = new _ForbiddenUser($UserName);
249 return _determineAdminUserOrOtherUser($UserName);
252 $ForbiddenUser = new _ForbiddenUser();
253 if (_isAnonUserAllowed())
255 return $ForbiddenUser; // User must sign in to browse pages.
257 return $ForbiddenUser; // User must sign in with a password.
260 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
261 . "Unexpectedly, an appropriate user class could not be determined.");
262 return $ForbiddenUser; // Failsafe.
267 * WikiUser.php use the name 'WikiUser'
269 function WikiUserClassname() {
275 * Upgrade olduser by copying properties from user to olduser.
276 * We are not sure yet, for which php's a simple $this = $user works reliably,
277 * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
278 * that's why try it the hard way.
280 function UpgradeUser ($olduser, $user) {
281 if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
282 // populate the upgraded class $olduser with the values from the new user object
283 //only _auth_level, _current_method, _current_index,
284 if (!empty($user->_level) and
285 $user->_level > $olduser->_level)
286 $olduser->_level = $user->_level;
287 if (!empty($user->_current_index) and
288 $user->_current_index > $olduser->_current_index) {
289 $olduser->_current_index = $user->_current_index;
290 $olduser->_current_method = $user->_current_method;
292 if (!empty($user->_authmethod))
293 $olduser->_authmethod = $user->_authmethod;
295 foreach (get_object_vars($user) as $k => $v) {
296 if (!empty($v)) $olduser->$k = $v;
299 $olduser->hasHomePage(); // revive db handle, because these don't survive sessions
300 //$GLOBALS['request']->_user = $olduser;
308 * Probably not needed, since we use the various user objects methods so far.
309 * Anyway, here it is, looping through all available objects.
311 function UserExists ($UserName) {
313 if (!($user = $request->getUser()))
314 $user = WikiUser($UserName);
317 if ($user->userExists($UserName)) {
318 $request->_user = $user;
321 if (isa($user,'_BogoUser'))
322 $user = new _PassUser($UserName,$user->_prefs);
323 $class = $user->nextClass();
324 if ($user = new $class($UserName,$user->_prefs)) {
325 return $user->userExists($UserName);
327 $request->_user = $GLOBALS['ForbiddenUser'];
331 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
334 * Base WikiUser class.
339 var $_level = WIKIAUTH_ANON;
341 var $_HomePagehandle = false;
344 function _WikiUser($UserName='', $prefs=false) {
346 $this->_userid = $UserName;
347 $this->_HomePagehandle = false;
349 $this->hasHomePage();
351 if (empty($this->_prefs)) {
352 if ($prefs) $this->_prefs = $prefs;
353 else $this->getPreferences();
357 function UserName() {
358 if (!empty($this->_userid))
359 return $this->_userid;
362 function getPreferences() {
363 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
364 . "New subclasses of _WikiUser must override this function.");
368 function setPreferences($prefs, $id_only) {
369 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
370 . "New subclasses of _WikiUser must override this function.");
374 function userExists() {
375 return $this->hasHomePage();
378 function checkPass($submitted_password) {
379 // By definition, an undefined user class cannot sign in.
380 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
381 . "New subclasses of _WikiUser must override this function.");
385 // returns page_handle to user's home page or false if none
386 function hasHomePage() {
387 if ($this->_userid) {
388 if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
389 return $this->_HomePagehandle->exists();
392 // check db again (maybe someone else created it since
395 $this->_HomePagehandle = $request->getPage($this->_userid);
396 return $this->_HomePagehandle->exists();
403 // innocent helper: case-insensitive position in _auth_methods
404 function array_position ($string, $array) {
405 $string = strtolower($string);
406 for ($found = 0; $found < count($array); $found++) {
407 if (strtolower($array[$found]) == $string)
413 function nextAuthMethodIndex() {
414 if (empty($this->_auth_methods))
415 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
416 if (empty($this->_current_index)) {
417 if (strtolower(get_class($this)) != '_passuser') {
418 $this->_current_method = substr(get_class($this),1,-8);
419 $this->_current_index = $this->array_position($this->_current_method,
420 $this->_auth_methods);
422 $this->_current_index = -1;
425 $this->_current_index++;
426 if ($this->_current_index >= count($this->_auth_methods))
428 $this->_current_method = $this->_auth_methods[$this->_current_index];
429 return $this->_current_index;
432 function AuthMethod($index = false) {
433 return $this->_auth_methods[ $index === false ? 0 : $index];
436 // upgrade the user object
437 function nextClass() {
438 if (($next = $this->nextAuthMethodIndex()) !== false) {
439 $method = $this->AuthMethod($next);
440 return "_".$method."PassUser";
442 if ($user = new $class($this->_userid)) {
443 // prevent from endless recursion.
444 //$user->_current_method = $this->_current_method;
445 //$user->_current_index = $this->_current_index;
446 $user = UpgradeUser($user, $this);
451 return "_ForbiddenPassUser";
454 //Fixme: for _HttpAuthPassUser
455 function PrintLoginForm (&$request, $args, $fail_message = false,
456 $seperate_page = false) {
457 include_once('lib/Template.php');
458 // Call update_locale in case the system's default language is not 'en'.
459 // (We have no user pref for lang at this point yet, no one is logged in.)
460 if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
461 update_locale(DEFAULT_LANGUAGE);
462 $userid = $this->_userid;
464 extract($args); // fixme
466 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
468 $pagename = $request->getArg('pagename');
470 $login = Template('login',
471 compact('pagename', 'userid', 'require_level',
472 'fail_message', 'pass_required', 'nocache'));
473 // check if the html template was already processed
474 $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
475 if ($seperate_page) {
476 $page = $request->getPage($pagename);
477 $revision = $page->getCurrentRevision();
478 return GeneratePage($login,_("Sign In"),$revision);
480 return $login->printExpansion();
484 /** Signed in but not password checked or empty password.
486 function isSignedIn() {
487 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
490 /** This is password checked for sure.
492 function isAuthenticated () {
493 //return isa($this,'_PassUser');
494 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
495 return $this->_level >= WIKIAUTH_BOGO;
498 function isAdmin () {
500 if ($this->_level == WIKIAUTH_ADMIN) return true;
502 if (!$group) $group = &$GLOBALS['request']->getGroup();
503 return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
506 /** Name or IP for a signed user. UserName could come from a cookie e.g.
509 return ( $this->UserName()
511 : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
514 /** Name for an authenticated user. No IP here.
516 function getAuthenticatedId() {
517 return ( $this->isAuthenticated()
519 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
522 function hasAuthority ($require_level) {
523 return $this->_level >= $require_level;
526 function isValidName ($userid = false) {
528 $userid = $this->_userid;
529 return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32;
533 * Called on an auth_args POST request, such as login, logout or signin.
534 * TODO: Check BogoLogin users with empty password. (self-signed users)
536 function AuthCheck ($postargs) {
537 // Normalize args, and extract.
538 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
540 foreach ($keys as $key)
541 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
543 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
545 if ($logout) { // Log out
546 $GLOBALS['request']->_user = new _AnonUser();
547 $GLOBALS['request']->_user->_userid = '';
548 $GLOBALS['request']->_user->_level = WIKIAUTH_ANON;
549 return $GLOBALS['request']->_user;
551 return false; // User hit cancel button.
552 elseif (!$login && !$userid)
553 return false; // Nothing to do?
555 if (!$this->isValidName($userid))
556 return _("Invalid username.");;
558 $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
559 if ($authlevel <= 0) { // anon or forbidden
561 return _("Invalid password.");
563 return _("Invalid password or userid.");
564 } elseif ($authlevel < $require_level) { // auth ok, but not enough
565 if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
568 $class = "_" . $this->_current_method . "PassUser";
569 $user = new $class($userid,$this->_prefs);
570 if (!check_php_version(5))
571 eval("\$this = \$user;");
572 // /*PHP5 patch*/$this = $user;
573 $this->_level = $authlevel;
576 $this->_userid = $userid;
577 $this->_level = $authlevel;
578 return _("Insufficient permissions.");
582 //$user = $GLOBALS['request']->_user;
583 if (!empty($this->_current_method) and
584 strtolower(get_class($this)) == '_passuser')
587 $class = "_" . $this->_current_method . "PassUser";
588 $user = new $class($userid,$this->_prefs);
589 if (!check_php_version(5))
590 eval("\$this = \$user;");
591 // /*PHP5 patch*/$this = $user;
592 $user->_level = $authlevel;
595 $this->_userid = $userid;
596 $this->_level = $authlevel;
603 * Not authenticated in user, but he may be signed in. Basicly with view access only.
604 * prefs are stored in cookies, but only the userid.
609 var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
611 /** Anon only gets to load and save prefs in a cookie, that's it.
613 function getPreferences() {
616 if (empty($this->_prefs))
617 $this->_prefs = new UserPreferences;
618 $UserName = $this->UserName();
620 // Try to read deprecated 1.3.x style cookies
621 if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
622 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
623 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
625 . sprintf("%s='%s'", WIKI_NAME, $cookie)
627 . _("Default preferences will be used."),
631 * Only set if it matches the UserName who is
632 * signing in or if this really is an Anon login (no
633 * username). (Remember, _BogoUser and higher inherit this
636 if (! $UserName || $UserName == @$unboxedcookie['userid']) {
637 $updated = $this->_prefs->updatePrefs($unboxedcookie);
638 //$this->_prefs = new UserPreferences($unboxedcookie);
639 $UserName = @$unboxedcookie['userid'];
640 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
641 $this->_userid = $UserName;
645 // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
647 $request->deleteCookieVar(WIKI_NAME);
649 // Try to read deprecated 1.3.4 style cookies
650 if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
651 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
652 if (! $UserName || $UserName == $unboxedcookie['userid']) {
653 $updated = $this->_prefs->updatePrefs($unboxedcookie);
654 //$this->_prefs = new UserPreferences($unboxedcookie);
655 $UserName = $unboxedcookie['userid'];
656 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
657 $this->_userid = $UserName;
662 $request->deleteCookieVar("WIKI_PREF2");
666 // Try reading userid from old PhpWiki cookie formats:
667 if ($cookie = $request->cookies->get_old('WIKI_ID')) {
668 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
670 elseif (is_array($cookie) and !empty($cookie['userid']))
671 $UserName = $cookie['userid'];
673 if (! $UserName and !headers_sent())
674 $request->deleteCookieVar("WIKI_ID");
676 $this->_userid = $UserName;
679 // initializeTheme() needs at least an empty object
681 if (empty($this->_prefs))
682 $this->_prefs = new UserPreferences;
684 return $this->_prefs;
687 /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
689 * Allow for multiple wikis in same domain. Encode only the
690 * _prefs array of the UserPreference object. Ideally the
691 * prefs array should just be imploded into a single string or
692 * something so it is completely human readable by the end
693 * user. In that case stricter error checking will be needed
694 * when loading the cookie.
696 function setPreferences($prefs, $id_only=false) {
697 if (!is_object($prefs)) {
698 if (is_object($this->_prefs)) {
699 $updated = $this->_prefs->updatePrefs($prefs);
700 $prefs =& $this->_prefs;
702 // update the prefs values from scratch. This could leed to unnecessary
703 // side-effects: duplicate emailVerified, ...
704 $this->_prefs = new UserPreferences($prefs);
708 if (!isset($this->_prefs))
709 $this->_prefs =& $prefs;
711 $updated = $this->_prefs->isChanged($prefs);
714 if ($id_only and !headers_sent()) {
716 // new 1.3.8 policy: no array cookies, only plain userid string as in
717 // the pre 1.3.x versions.
718 // prefs should be stored besides the session in the homepagehandle or in a db.
719 $request->setCookieVar('WIKI_ID', $this->_userid,
720 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
721 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
722 // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
725 $packed = $prefs->store();
726 $unpacked = $prefs->unpack($packed);
727 if (count($unpacked)) {
728 foreach (array('_method','_select','_update') as $param) {
729 if (!empty($this->_prefs->{$param}))
730 $prefs->{$param} = $this->_prefs->{$param};
732 $this->_prefs = $prefs;
733 //FIXME! The following must be done in $request->_setUser(), not here,
734 // to be able to iterate over multiple users, without tampering the current user.
737 $request->_prefs =& $this->_prefs;
738 $request->_user->_prefs =& $this->_prefs;
739 if (isset($request->_user->_auth_dbi)) {
740 $user = $request->_user;
741 unset($user->_auth_dbi);
742 $request->setSessionVar('wiki_user', $user);
744 //$request->setSessionVar('wiki_prefs', $this->_prefs);
745 $request->setSessionVar('wiki_user', $request->_user);
752 function userExists() {
756 function checkPass($submitted_password) {
758 // this might happen on a old-style signin button.
760 // By definition, the _AnonUser does not HAVE a password
761 // (compared to _BogoUser, who has an EMPTY password).
762 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
763 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
764 . "New subclasses of _WikiUser must override this function.");
771 * Helper class to finish the PassUser auth loop.
772 * This is added automatically to USER_AUTH_ORDER.
777 var $_level = WIKIAUTH_FORBIDDEN;
779 function checkPass($submitted_password) {
780 return WIKIAUTH_FORBIDDEN;
783 function userExists() {
784 if ($this->_HomePagehandle) return true;
789 * The PassUser name gets created automatically.
790 * That's why this class is empty, but must exist.
792 class _ForbiddenPassUser
793 extends _ForbiddenUser
801 * Do NOT extend _BogoUser to other classes, for checkPass()
802 * security. (In case of defects in code logic of the new class!)
803 * The intermediate step between anon and passuser.
804 * We also have the _BogoLoginPassUser class with stricter
805 * password checking, which fits into the auth loop.
806 * Note: This class is not called anymore by WikiUser()
811 function userExists() {
812 if (isWikiWord($this->_userid)) {
813 $this->_level = WIKIAUTH_BOGO;
816 $this->_level = WIKIAUTH_ANON;
821 function checkPass($submitted_password) {
822 // By definition, BogoUser has an empty password.
824 return $this->_level;
831 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
833 * The classes for all subsequent auth methods extend from this class.
834 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
835 * the three auth method policies first-only, strict and stacked
836 * and the two methods for prefs: homepage or database,
837 * if $DBAuthParams['pref_select'] is defined.
839 * Default is PersonalPage auth and prefs.
841 * @author: Reini Urban
845 var $_auth_dbi, $_prefs;
846 var $_current_method, $_current_index;
848 // check and prepare the auth and pref methods only once
849 function _PassUser($UserName='', $prefs=false) {
850 //global $DBAuthParams, $DBParams;
852 if (!$this->isValidName($UserName))
854 $this->_userid = $UserName;
855 if ($this->hasHomePage())
856 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
858 $this->_authmethod = substr(get_class($this),1,-8);
859 if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
861 // Check the configured Prefs methods
862 $dbi = $this->getAuthDbh();
863 $dbh = $GLOBALS['request']->getDbh();
864 if ( $dbi and !isset($this->_prefs->_select) and $dbh->getAuthParam('pref_select')) {
865 if (!$this->_prefs) {
866 $this->_prefs = new UserPreferences();
869 $this->_prefs->_method = $dbh->getParam('dbtype');
870 $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
872 if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
873 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
874 array("userid", "pref_blob"));
877 if (!$this->_prefs) {
878 $this->_prefs = new UserPreferences();
881 $this->_prefs->_method = 'HomePage';
884 if (! $this->_prefs or isset($need_pref) ) {
885 if ($prefs) $this->_prefs = $prefs;
886 else $this->getPreferences();
889 // Upgrade to the next parent _PassUser class. Avoid recursion.
890 if ( strtolower(get_class($this)) === '_passuser' ) {
891 //auth policy: Check the order of the configured auth methods
892 // 1. first-only: Upgrade the class here in the constructor
893 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as
894 /// in the previous PhpWiki releases (slow)
895 // 3. strict: upgrade the class after checking the user existance in userExists()
896 // 4. stacked: upgrade the class after the password verification in checkPass()
897 // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
898 if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
899 if (defined('USER_AUTH_POLICY')) {
900 // policy 1: only pre-define one method for all users
901 if (USER_AUTH_POLICY === 'first-only') {
902 $class = $this->nextClass();
903 return new $class($UserName,$this->_prefs);
905 // Use the default behaviour from the previous versions:
906 elseif (USER_AUTH_POLICY === 'old') {
907 // Default: try to be smart
908 // On php5 we can directly return and upgrade the Object,
909 // before we have to upgrade it manually.
910 if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
911 if (check_php_version(5))
912 return new _HttpAuthPassUser($UserName,$this->_prefs);
914 $user = new _HttpAuthPassUser($UserName,$this->_prefs);
915 eval("\$this = \$user;");
916 // /*PHP5 patch*/$this = $user;
919 } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
920 $dbh->getAuthParam('auth_check') and
921 ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
922 if (check_php_version(5))
923 return new _DbPassUser($UserName,$this->_prefs);
925 $user = new _DbPassUser($UserName,$this->_prefs);
926 eval("\$this = \$user;");
927 // /*PHP5 patch*/$this = $user;
930 } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
931 defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
932 function_exists('ldap_connect')) {
933 if (check_php_version(5))
934 return new _LDAPPassUser($UserName,$this->_prefs);
936 $user = new _LDAPPassUser($UserName,$this->_prefs);
937 eval("\$this = \$user;");
938 // /*PHP5 patch*/$this = $user;
941 } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
942 defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
943 if (check_php_version(5))
944 return new _IMAPPassUser($UserName,$this->_prefs);
946 $user = new _IMAPPassUser($UserName,$this->_prefs);
947 eval("\$this = \$user;");
948 // /*PHP5 patch*/$this = $user;
951 } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
952 defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
953 if (check_php_version(5))
954 return new _FilePassUser($UserName, $this->_prefs);
956 $user = new _FilePassUser($UserName, $this->_prefs);
957 eval("\$this = \$user;");
958 // /*PHP5 patch*/$this = $user;
962 if (check_php_version(5))
963 return new _PersonalPagePassUser($UserName,$this->_prefs);
965 $user = new _PersonalPagePassUser($UserName,$this->_prefs);
966 eval("\$this = \$user;");
967 // /*PHP5 patch*/$this = $user;
973 // else use the page methods defined in _PassUser.
979 function getAuthDbh () {
980 global $request; //, $DBParams, $DBAuthParams;
982 $dbh = $request->getDbh();
983 // session restauration doesn't re-connect to the database automatically,
984 // so dirty it here, to force a reconnect.
985 if (isset($this->_auth_dbi)) {
986 if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
987 unset($this->_auth_dbi);
988 if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
989 unset($this->_auth_dbi);
991 if (empty($this->_auth_dbi)) {
992 if ($dbh->getParam('dbtype') != 'SQL' and $dbh->getParam('dbtype') != 'ADODB')
994 if (empty($GLOBALS['DBAuthParams']))
996 if (!$dbh->getAuthParam('auth_dsn')) {
997 $dbh = $request->getDbh(); // use phpwiki database
998 } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
999 $dbh = $request->getDbh(); // same phpwiki database
1000 } else { // use another external database handle. needs PHP >= 4.1
1001 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1002 $local_params['dsn'] = $local_params['auth_dsn'];
1003 $dbh = WikiDB::open($local_params);
1005 $this->_auth_dbi =& $dbh->_backend->_dbh;
1007 return $this->_auth_dbi;
1010 function _normalize_stmt_var($var, $oldstyle = false) {
1011 static $valid_variables = array('userid','password','pref_blob','groupname');
1012 // old-style: "'$userid'"
1013 // new-style: '"\$userid"' or just "userid"
1014 $new = str_replace(array("'",'"','\$','$'),'',$var);
1015 if (!in_array($new,$valid_variables)) {
1016 trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1019 return !$oldstyle ? "'$".$new."'" : '"\$'.$new.'"';
1022 // TODO: use it again for the auth and member tables
1023 function prepare ($stmt, $variables, $oldstyle = false) {
1025 $dbi = $request->getDbh();
1026 $this->getAuthDbh();
1027 // "'\$userid"' => '%s'
1028 // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1029 // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1031 if (is_array($variables)) {
1032 for ($i=0; $i < count($variables); $i++) {
1033 $var = $this->_normalize_stmt_var($variables[$i],$oldstyle);
1035 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1036 $variables[$i], $stmt), E_USER_WARNING);
1037 $variables[$i] = $var;
1038 if (!$var) $new[] = '';
1042 $var = $this->_normalize_stmt_var($variables,$oldstyle);
1044 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1045 $variables,$stmt), E_USER_WARNING);
1047 if (!$var) $new = '';
1050 $prefix = $dbi->getParam('prefix');
1051 // probably prefix table names if in same database
1052 if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1053 ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1055 if (!stristr($stmt, $prefix)) {
1056 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1057 trigger_error("TODO: Need to prefix the DBAuthParam tablename in config/config.ini:\n $stmt",
1059 $stmt = str_replace(array(" user "," pref "," member "),
1060 array(" ".$prefix."user ",
1061 " ".$prefix."pref ",
1062 " ".$prefix."member "),$stmt);
1065 // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1066 // Simple sprintf-style.
1067 $new_stmt = str_replace($variables, $new, $stmt);
1068 if ($new_stmt == $stmt) {
1070 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1071 $stmt), E_USER_WARNING);
1073 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1074 $stmt), E_USER_WARNING);
1075 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1081 function getPreferences() {
1082 if (!empty($this->_prefs->_method)) {
1083 if ($this->_prefs->_method == 'ADODB') {
1084 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
1085 return _AdoDbPassUser::getPreferences();
1086 } elseif ($this->_prefs->_method == 'SQL') {
1087 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
1088 return _PearDbPassUser::getPreferences();
1092 // We don't necessarily have to read the cookie first. Since
1093 // the user has a password, the prefs stored in the homepage
1094 // cannot be arbitrarily altered by other Bogo users.
1095 _AnonUser::getPreferences();
1096 // User may have deleted cookie, retrieve from his
1097 // PersonalPage if there is one.
1098 if ($this->_HomePagehandle) {
1099 if ($restored_from_page = $this->_prefs->retrieve
1100 ($this->_HomePagehandle->get('pref'))) {
1101 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1102 //$this->_prefs = new UserPreferences($restored_from_page);
1103 return $this->_prefs;
1106 return $this->_prefs;
1109 function setPreferences($prefs, $id_only=false) {
1110 if (!empty($this->_prefs->_method)) {
1111 if ($this->_prefs->_method == 'ADODB') {
1112 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
1113 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1115 elseif ($this->_prefs->_method == 'SQL') {
1116 _PearDbPassUser::_PearDbPassUser($this->_userid, $prefs);
1117 return _PearDbPassUser::setPreferences($prefs, $id_only);
1120 if (_AnonUser::setPreferences($prefs, $id_only)) {
1121 // Encode only the _prefs array of the UserPreference object
1122 if ($this->_HomePagehandle and !$id_only) {
1123 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1129 function mayChangePass() {
1133 //The default method is getting the password from prefs.
1134 // child methods obtain $stored_password from external auth.
1135 function userExists() {
1136 //if ($this->_HomePagehandle) return true;
1137 $class = $this->nextClass();
1138 while ($user = new $class($this->_userid, $this->_prefs)) {
1139 if (!check_php_version(5))
1140 eval("\$this = \$user;");
1141 // /*PHP5 patch*/$this = $user;
1142 UpgradeUser($this,$user);
1143 if ($user->userExists()) {
1146 // prevent endless loop. does this work on all PHP's?
1147 // it just has to set the classname, what it correctly does.
1148 $class = $user->nextClass();
1149 if ($class == "_ForbiddenPassUser")
1155 //The default method is getting the password from prefs.
1156 // child methods obtain $stored_password from external auth.
1157 function checkPass($submitted_password) {
1158 $stored_password = $this->_prefs->get('passwd');
1159 if ($this->_checkPass($submitted_password, $stored_password)) {
1160 $this->_level = WIKIAUTH_USER;
1161 return $this->_level;
1163 return $this->_tryNextPass($submitted_password);
1168 * The basic password checker for all PassUser objects.
1169 * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1170 * Empty passwords are always false!
1171 * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1172 * @see UserPreferences::set
1174 * DBPassUser password's have their own crypt definition.
1175 * That's why DBPassUser::checkPass() doesn't call this method, if
1176 * the db password method is 'plain', which means that the DB SQL
1177 * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1178 * don't store plain passwords in the DB.
1180 * TODO: remove crypt() function check from config.php:396 ??
1182 function _checkPass($submitted_password, $stored_password) {
1183 if(!empty($submitted_password)) {
1184 //FIXME: This will work only on plaintext passwords.
1185 if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1186 // With the EditMetaData plugin
1187 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."));
1190 if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
1192 if (ENCRYPTED_PASSWD) {
1193 // Verify against encrypted password.
1194 if (function_exists('crypt')) {
1195 if (crypt($submitted_password, $stored_password) == $stored_password )
1196 return true; // matches encrypted password
1201 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1202 . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1208 // Verify against cleartext password.
1209 if ($submitted_password == $stored_password)
1212 // Check whether we forgot to enable ENCRYPTED_PASSWD
1213 if (function_exists('crypt')) {
1214 if (crypt($submitted_password, $stored_password) == $stored_password) {
1215 trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1226 /** The default method is storing the password in prefs.
1227 * Child methods (DB,File) may store in external auth also, but this
1228 * must be explicitly enabled.
1229 * This may be called by plugin/UserPreferences or by ->SetPreferences()
1231 function changePass($submitted_password) {
1232 $stored_password = $this->_prefs->get('passwd');
1233 // check if authenticated
1234 if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1235 $this->_prefs->set('passwd',$submitted_password);
1236 //update the storage (session, homepage, ...)
1237 $this->SetPreferences($this->_prefs);
1240 //Todo: return an error msg to the caller what failed?
1241 // same password or no privilege
1245 function _tryNextPass($submitted_password) {
1246 if (USER_AUTH_POLICY === 'strict') {
1247 $class = $this->nextClass();
1248 if ($user = new $class($this->_userid,$this->_prefs)) {
1249 if ($user->userExists()) {
1250 return $user->checkPass($submitted_password);
1254 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1255 $class = $this->nextClass();
1256 if ($user = new $class($this->_userid,$this->_prefs))
1257 return $user->checkPass($submitted_password);
1259 return $this->_level;
1262 function _tryNextUser() {
1263 if (USER_AUTH_POLICY === 'strict') {
1264 $class = $this->nextClass();
1265 while ($user = new $class($this->_userid,$this->_prefs)) {
1266 if (!check_php_version(5))
1267 eval("\$this = \$user;");
1268 // /*PHP5 patch*/$this = $user;
1269 //$user = UpgradeUser($this, $user);
1270 if ($user->userExists()) {
1273 $class = $this->nextClass();
1281 /** Without stored password. A _BogoLoginPassUser with password
1282 * is automatically upgraded to a PersonalPagePassUser.
1284 class _BogoLoginPassUser
1287 var $_authmethod = 'BogoLogin';
1288 function userExists() {
1289 if (isWikiWord($this->_userid)) {
1290 $this->_level = WIKIAUTH_BOGO;
1293 $this->_level = WIKIAUTH_ANON;
1298 /** A BogoLoginUser requires no password at all
1299 * But if there's one stored, we should prefer PersonalPage instead
1301 function checkPass($submitted_password) {
1302 if ($this->_prefs->get('passwd')) {
1303 if (isset($this->_prefs->_method) and $this->_prefs->_method == 'HomePage') {
1304 $user = new _PersonalPagePassUser($this->_userid, $this->_prefs);
1305 if ($user->checkPass($submitted_password)) {
1306 if (!check_php_version(5))
1307 eval("\$this = \$user;");
1308 // /*PHP5 patch*/$this = $user;
1309 $user = UpgradeUser($this, $user);
1310 $this->_level = WIKIAUTH_USER;
1311 return $this->_level;
1313 $this->_level = WIKIAUTH_ANON;
1314 return $this->_level;
1317 $stored_password = $this->_prefs->get('passwd');
1318 if ($this->_checkPass($submitted_password, $stored_password)) {
1319 $this->_level = WIKIAUTH_USER;
1320 return $this->_level;
1322 return $this->_tryNextPass($submitted_password);
1326 if (isWikiWord($this->_userid)) {
1327 $this->_level = WIKIAUTH_BOGO;
1329 $this->_level = WIKIAUTH_ANON;
1331 return $this->_level;
1337 * This class is only to simplify the auth method dispatcher.
1338 * It inherits almost all all methods from _PassUser.
1340 class _PersonalPagePassUser
1343 var $_authmethod = 'PersonalPage';
1345 function userExists() {
1346 return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1349 /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1350 * BUT if the user already has a homepage with an empty password
1351 * stored, allow login but warn him to change it.
1353 function checkPass($submitted_password) {
1354 if ($this->userExists()) {
1355 $stored_password = $this->_prefs->get('passwd');
1356 if (empty($stored_password)) {
1357 trigger_error(sprintf(
1358 _("PersonalPage login method:\n").
1359 _("You stored an empty password in your '%s' page.\n").
1360 _("Your access permissions are only for a BogoUser.\n").
1361 _("Please set your password in UserPreferences."),
1362 $this->_userid), E_USER_WARNING);
1363 $this->_level = WIKIAUTH_BOGO;
1364 return $this->_level;
1366 if ($this->_checkPass($submitted_password, $stored_password))
1367 return ($this->_level = WIKIAUTH_USER);
1368 return _PassUser::checkPass($submitted_password);
1370 return WIKIAUTH_ANON;
1375 * We have two possibilities here.
1376 * 1) The webserver location is already HTTP protected (usually Basic). Then just
1377 * use the username and do nothing
1378 * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1379 * by sending a 401 error and let the client display the login dialog.
1380 * This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1381 * since the other methods cannot be transparently called after this enforced
1383 * Try the available auth methods (most likely Bogo) and sent this header back.
1384 * header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1386 class _HttpAuthPassUser
1389 function _HttpAuthPassUser($UserName='',$prefs=false) {
1390 if ($prefs) $this->_prefs = $prefs;
1391 if (!isset($this->_prefs->_method))
1392 _PassUser::_PassUser($UserName);
1393 if ($UserName) $this->_userid = $UserName;
1394 $this->_authmethod = 'HttpAuth';
1395 if ($this->userExists())
1398 return $GLOBALS['ForbiddenUser'];
1401 function _http_username() {
1402 if (!isset($_SERVER))
1403 $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
1404 if (!empty($_SERVER['PHP_AUTH_USER']))
1405 return $_SERVER['PHP_AUTH_USER'];
1406 if (!empty($_SERVER['REMOTE_USER']))
1407 return $_SERVER['REMOTE_USER'];
1408 if (!empty($GLOBALS['HTTP_ENV_VARS']['REMOTE_USER']))
1409 return $GLOBALS['HTTP_ENV_VARS']['REMOTE_USER'];
1410 if (!empty($GLOBALS['REMOTE_USER']))
1411 return $GLOBALS['REMOTE_USER'];
1415 //force http auth authorization
1416 function userExists() {
1417 // todo: older php's
1418 $username = $this->_http_username();
1419 if (empty($username) or strtolower($username) != strtolower($this->_userid)) {
1420 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1421 header('HTTP/1.0 401 Unauthorized');
1424 $this->_userid = $username;
1425 // we should check if he is a member of admin,
1426 // because HttpAuth has its own logic.
1427 $this->_level = WIKIAUTH_USER;
1428 if ($this->isAdmin())
1429 $this->_level = WIKIAUTH_ADMIN;
1433 function checkPass($submitted_password) {
1434 return $this->userExists()
1435 ? ($this->isAdmin() ? WIKIAUTH_ADMIN : WIKIAUTH_USER)
1439 function mayChangePass() {
1443 // hmm... either the server dialog or our own.
1444 function PrintLoginForm (&$request, $args, $fail_message = false,
1445 $seperate_page = true) {
1446 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1447 header('HTTP/1.0 401 Unauthorized');
1454 * Support reuse of existing user session from another application.
1455 * You have to define which session variable holds the userid, and
1456 * at what level is that user then. 1: BogoUser, 2: PassUser
1457 * define('AUTH_SESS_USER','userid');
1458 * define('AUTH_SESS_LEVEL',2);
1460 class _SessionPassUser
1463 function _SessionPassUser($UserName='',$prefs=false) {
1464 if ($prefs) $this->_prefs = $prefs;
1465 if (!defined("AUTH_SESS_USER") or !defined("AUTH_SESS_LEVEL")) {
1467 "AUTH_SESS_USER or AUTH_SESS_LEVEL is not defined for the SessionPassUser method",
1471 $sess =& $GLOBALS['HTTP_SESSION_VARS'];
1472 // user hash: "[user][userid]" or object "user->id"
1473 if (strstr(AUTH_SESS_USER,"][")) {
1474 $sess = $GLOBALS['HTTP_SESSION_VARS'];
1475 // recurse into hashes: "[user][userid]", sess = sess[user] => sess = sess[userid]
1476 foreach (split("][",AUTH_SESS_USER) as $v) {
1477 $v = str_replace(array("[","]"),'',$v);
1480 $this->_userid = $sess;
1481 } elseif (strstr(AUTH_SESS_USER,"->")) {
1482 // object "user->id" (no objects inside hashes supported!)
1483 list($obj,$key) = split("->",AUTH_SESS_USER);
1484 $this->_userid = $sess[$obj]->$key;
1486 $this->_userid = $sess[AUTH_SESS_USER];
1488 if (!isset($this->_prefs->_method))
1489 _PassUser::_PassUser($this->_userid);
1490 $this->_level = AUTH_SESS_LEVEL;
1491 $this->_authmethod = 'Session';
1493 function userExists() {
1494 return !empty($this->_userid);
1496 function checkPass($submitted_password) {
1497 return $this->userExists() and $this->_level;
1499 function mayChangePass() {
1505 * Baseclass for PearDB and ADODB PassUser's
1506 * Authenticate against a database, to be able to use shared users.
1507 * internal: no different $DbAuthParams['dsn'] defined, or
1508 * external: different $DbAuthParams['dsn']
1509 * The magic is done in the symbolic SQL statements in config/config.ini, similar to
1512 * We support only the SQL and ADODB backends.
1513 * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages,
1514 * not for auth stuff. If one would like to use e.g. dba for auth, he should
1515 * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
1516 * (Not supported yet, since we require SQL. SQLite would make since when
1517 * it will come to PHP)
1519 * @tables: user, pref
1521 * Preferences are handled in the parent class _PassUser, because the
1522 * previous classes may also use DB pref_select and pref_update.
1524 * Flat files auth is handled by the auth method "File".
1529 var $_authselect, $_authupdate, $_authcreate;
1531 // This can only be called from _PassUser, because the parent class
1532 // sets the auth_dbi and pref methods, before this class is initialized.
1533 function _DbPassUser($UserName='',$prefs=false) {
1534 if (!$this->_prefs) {
1535 if ($prefs) $this->_prefs = $prefs;
1537 if (!isset($this->_prefs->_method))
1538 _PassUser::_PassUser($UserName);
1539 elseif (!$this->isValidName($UserName)) {
1540 trigger_error(_("Invalid username."),E_USER_WARNING);
1543 $this->_authmethod = 'Db';
1544 //$this->getAuthDbh();
1545 //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1546 $dbi =& $GLOBALS['request']->_dbi;
1547 $dbtype = $dbi->getParam('dbtype');
1548 if ($dbtype == 'ADODB') {
1549 if (check_php_version(5))
1550 return new _AdoDbPassUser($UserName,$this->_prefs);
1552 $user = new _AdoDbPassUser($UserName,$this->_prefs);
1553 eval("\$this = \$user;");
1557 elseif ($dbtype == 'SQL') {
1558 if (check_php_version(5))
1559 return new _PearDbPassUser($UserName,$this->_prefs);
1561 $user = new _PearDbPassUser($UserName,$this->_prefs);
1562 eval("\$this = \$user;");
1569 function mayChangePass() {
1570 return !isset($this->_authupdate);
1575 class _PearDbPassUser
1579 * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1580 * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1586 var $_authmethod = 'PearDb';
1587 function _PearDbPassUser($UserName='',$prefs=false) {
1588 //global $DBAuthParams;
1589 if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1590 if ($prefs) $this->_prefs = $prefs;
1592 if (!isset($this->_prefs->_method))
1593 _PassUser::_PassUser($UserName);
1594 elseif (!$this->isValidName($UserName)) {
1595 trigger_error(_("Invalid username."), E_USER_WARNING);
1598 $this->_userid = $UserName;
1599 // make use of session data. generally we only initialize this every time,
1600 // but do auth checks only once
1601 $this->_auth_crypt_method = $GLOBALS['request']->_dbi->getAuthParam('auth_crypt_method');
1605 function getPreferences() {
1606 // override the generic slow method here for efficiency and not to
1607 // clutter the homepage metadata with prefs.
1608 _AnonUser::getPreferences();
1609 $this->getAuthDbh();
1610 if (isset($this->_prefs->_select)) {
1611 $dbh = &$this->_auth_dbi;
1612 $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1613 // patched by frederik@pandora.be
1614 $prefs = $db_result->fetchRow();
1615 $prefs_blob = @$prefs["prefs"];
1616 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1617 $updated = $this->_prefs->updatePrefs($restored_from_db);
1618 //$this->_prefs = new UserPreferences($restored_from_db);
1619 return $this->_prefs;
1622 if ($this->_HomePagehandle) {
1623 if ($restored_from_page = $this->_prefs->retrieve
1624 ($this->_HomePagehandle->get('pref'))) {
1625 $updated = $this->_prefs->updatePrefs($restored_from_page);
1626 //$this->_prefs = new UserPreferences($restored_from_page);
1627 return $this->_prefs;
1630 return $this->_prefs;
1633 function setPreferences($prefs, $id_only=false) {
1634 // if the prefs are changed
1635 if ($count = _AnonUser::setPreferences($prefs, 1)) {
1637 //$user = $request->_user;
1638 //unset($user->_auth_dbi);
1639 // this must be done in $request->_setUser, not here!
1640 //$request->setSessionVar('wiki_user', $user);
1641 $this->getAuthDbh();
1642 $packed = $this->_prefs->store();
1643 if (!$id_only and isset($this->_prefs->_update)) {
1644 $dbh = &$this->_auth_dbi;
1645 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1646 $dbh->quote($packed),
1647 $dbh->quote($this->_userid)));
1649 if ($this->_HomePagehandle and $this->_HomePagehandle->get('pref'))
1650 $this->_HomePagehandle->set('pref', '');
1652 //store prefs in homepage, not in cookie
1653 if ($this->_HomePagehandle and !$id_only)
1654 $this->_HomePagehandle->set('pref', $packed);
1656 return $count; //count($this->_prefs->unpack($packed));
1661 function userExists() {
1662 //global $DBAuthParams;
1663 $this->getAuthDbh();
1664 $dbh = &$this->_auth_dbi;
1665 if (!$dbh) { // needed?
1666 return $this->_tryNextUser();
1668 if (!$this->isValidName()) {
1669 return $this->_tryNextUser();
1671 $dbi =& $GLOBALS['request']->_dbi;
1672 // Prepare the configured auth statements
1673 if ($dbi->getAuthParam('auth_check') and empty($this->_authselect)) {
1674 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1675 array("userid", "password"));
1677 if (empty($this->_authselect))
1678 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1679 'DBAUTH_AUTH_CHECK', 'SQL'),
1681 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1682 if ($this->_auth_crypt_method == 'crypt') {
1683 $rs = $dbh->query(sprintf($this->_authselect, $dbh->quote($this->_userid)));
1688 if (! $dbi->getAuthParam('auth_user_exists'))
1689 trigger_error(fmt("%s is missing",'DBAUTH_AUTH_USER_EXISTS'),
1691 $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'),"userid");
1692 $rs = $dbh->query(sprintf($this->_authcheck, $dbh->quote($this->_userid)));
1696 // maybe the user is allowed to create himself. Generally not wanted in
1697 // external databases, but maybe wanted for the wiki database, for performance
1699 if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) {
1700 $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'),
1701 array("userid", "password"));
1703 if (!empty($this->_authcreate) and isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd'])) {
1704 $passwd = $GLOBALS['HTTP_POST_VARS']['auth']['passwd'];
1705 $dbh->simpleQuery(sprintf($this->_authcreate,
1706 $dbh->quote($passwd),
1707 $dbh->quote($this->_userid)
1711 return $this->_tryNextUser();
1714 function checkPass($submitted_password) {
1715 //global $DBAuthParams;
1716 $this->getAuthDbh();
1717 if (!$this->_auth_dbi) { // needed?
1718 return $this->_tryNextPass($submitted_password);
1720 if (!$this->isValidName()) {
1721 return $this->_tryNextPass($submitted_password);
1723 if (!isset($this->_authselect))
1724 $this->userExists();
1725 if (!isset($this->_authselect))
1726 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1727 'DBAUTH_AUTH_CHECK','SQL'),
1730 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1731 $dbh = &$this->_auth_dbi;
1732 if ($this->_auth_crypt_method == 'crypt') {
1733 $stored_password = $dbh->getOne(sprintf($this->_authselect,
1734 $dbh->quote($this->_userid)));
1735 $result = $this->_checkPass($submitted_password, $stored_password);
1737 $okay = $dbh->getOne(sprintf($this->_authselect,
1738 $dbh->quote($submitted_password),
1739 $dbh->quote($this->_userid)));
1740 $result = !empty($okay);
1744 $this->_level = WIKIAUTH_USER;
1745 return $this->_level;
1747 return $this->_tryNextPass($submitted_password);
1751 function mayChangePass() {
1752 return $GLOBALS['request']->_dbi->getAuthParam('auth_update');
1755 function storePass($submitted_password) {
1756 if (!$this->isValidName()) {
1759 $this->getAuthDbh();
1760 $dbh = &$this->_auth_dbi;
1761 $dbi =& $GLOBALS['request']->_dbi;
1762 if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) {
1763 $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'),
1764 array("userid", "password"));
1766 if (empty($this->_authupdate)) {
1767 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1768 'DBAUTH_AUTH_UPDATE','SQL'),
1773 if ($this->_auth_crypt_method == 'crypt') {
1774 if (function_exists('crypt'))
1775 $submitted_password = crypt($submitted_password);
1777 $dbh->simpleQuery(sprintf($this->_authupdate,
1778 $dbh->quote($submitted_password),
1779 $dbh->quote($this->_userid)
1785 class _AdoDbPassUser
1789 * Simple sprintf, no prepare.
1791 * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster
1792 * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1794 * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1799 var $_authmethod = 'AdoDb';
1800 function _AdoDbPassUser($UserName='',$prefs=false) {
1801 if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1802 if ($prefs) $this->_prefs = $prefs;
1803 if (!isset($this->_prefs->_method))
1804 _PassUser::_PassUser($UserName);
1806 if (!$this->isValidName($UserName)) {
1807 trigger_error(_("Invalid username."),E_USER_WARNING);
1810 $this->_userid = $UserName;
1811 $this->getAuthDbh();
1812 $this->_auth_crypt_method = $GLOBALS['request']->_dbi->getAuthParam('auth_crypt_method');
1813 // Don't prepare the configured auth statements anymore
1817 function getPreferences() {
1818 // override the generic slow method here for efficiency
1819 _AnonUser::getPreferences();
1820 $this->getAuthDbh();
1821 if (isset($this->_prefs->_select)) {
1822 $dbh = & $this->_auth_dbi;
1823 $rs = $dbh->Execute(sprintf($this->_prefs->_select, $dbh->qstr($this->_userid)));
1827 $prefs_blob = @$rs->fields['prefs'];
1829 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1830 $updated = $this->_prefs->updatePrefs($restored_from_db);
1831 //$this->_prefs = new UserPreferences($restored_from_db);
1832 return $this->_prefs;
1836 if ($this->_HomePagehandle) {
1837 if ($restored_from_page = $this->_prefs->retrieve
1838 ($this->_HomePagehandle->get('pref'))) {
1839 $updated = $this->_prefs->updatePrefs($restored_from_page);
1840 //$this->_prefs = new UserPreferences($restored_from_page);
1841 return $this->_prefs;
1844 return $this->_prefs;
1847 function setPreferences($prefs, $id_only=false) {
1848 // if the prefs are changed
1849 if (_AnonUser::setPreferences($prefs, 1)) {
1851 $packed = $this->_prefs->store();
1852 //$user = $request->_user;
1853 //unset($user->_auth_dbi);
1854 if (!$id_only and isset($this->_prefs->_update)) {
1855 $this->getAuthDbh();
1856 $dbh = &$this->_auth_dbi;
1857 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1858 $dbh->qstr($packed),
1859 $dbh->qstr($this->_userid)));
1860 $db_result->Close();
1862 if ($this->_HomePagehandle and $this->_HomePagehandle->get('pref'))
1863 $this->_HomePagehandle->set('pref', '');
1865 //store prefs in homepage, not in cookie
1866 if ($this->_HomePagehandle and !$id_only)
1867 $this->_HomePagehandle->set('pref', $packed);
1869 return count($this->_prefs->unpack($packed));
1874 function userExists() {
1875 $this->getAuthDbh();
1876 $dbh = &$this->_auth_dbi;
1877 if (!$dbh) { // needed?
1878 return $this->_tryNextUser();
1880 if (!$this->isValidName()) {
1881 return $this->_tryNextUser();
1883 $dbi =& $GLOBALS['request']->_dbi;
1884 if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) {
1885 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1886 array("userid","password"));
1888 if (empty($this->_authselect))
1889 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1890 'DBAUTH_AUTH_CHECK', 'ADODB'),
1892 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1893 if ($this->_auth_crypt_method == 'crypt') {
1894 $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid)));
1903 if (! $dbi->getAuthParam('auth_user_exists'))
1904 trigger_error(fmt("%s is missing", 'DBAUTH_AUTH_USER_EXISTS'),
1906 $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'),
1908 $rs = $dbh->Execute(sprintf($this->_authcheck, $dbh->qstr($this->_userid)));
1916 // maybe the user is allowed to create himself. Generally not wanted in
1917 // external databases, but maybe wanted for the wiki database, for performance
1919 if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) {
1920 $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'),
1921 array("userid", "password"));
1923 if (!empty($this->_authcreate) and
1924 isset($GLOBALS['HTTP_POST_VARS']['auth']) and
1925 isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd']))
1927 $dbh->Execute(sprintf($this->_authcreate,
1928 $dbh->qstr($GLOBALS['HTTP_POST_VARS']['auth']['passwd']),
1929 $dbh->qstr($this->_userid)));
1933 return $this->_tryNextUser();
1936 function checkPass($submitted_password) {
1937 //global $DBAuthParams;
1938 $this->getAuthDbh();
1939 if (!$this->_auth_dbi) { // needed?
1940 return $this->_tryNextPass($submitted_password);
1942 if (!$this->isValidName()) {
1943 return $this->_tryNextPass($submitted_password);
1945 $dbh =& $this->_auth_dbi;
1946 $dbi =& $GLOBALS['request']->_dbi;
1947 if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) {
1948 $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'),
1949 array("userid", "password"));
1951 if (!isset($this->_authselect))
1952 $this->userExists();
1953 if (!isset($this->_authselect))
1954 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
1955 'DBAUTH_AUTH_CHECK', 'ADODB'),
1957 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1958 if ($this->_auth_crypt_method == 'crypt') {
1959 $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid)));
1961 $stored_password = $rs->fields['password'];
1963 $result = $this->_checkPass($submitted_password, $stored_password);
1969 $rs = $dbh->Execute(sprintf($this->_authselect,
1970 $dbh->qstr($submitted_password),
1971 $dbh->qstr($this->_userid)));
1972 if (isset($rs->fields['ok']))
1973 $okay = $rs->fields['ok'];
1974 elseif (isset($rs->fields[1]))
1975 $okay = $rs->fields[1];
1977 $okay = reset($rs->fields);
1980 $result = !empty($okay);
1984 $this->_level = WIKIAUTH_USER;
1985 return $this->_level;
1987 return $this->_tryNextPass($submitted_password);
1991 function mayChangePass() {
1992 return $GLOBALS['request']->_dbi->getAuthParam('auth_update');
1995 function storePass($submitted_password) {
1996 $this->getAuthDbh();
1997 $dbh = &$this->_auth_dbi;
1998 $dbi =& $GLOBALS['request']->_dbi;
1999 if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) {
2000 $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'),
2001 array("userid", "password"));
2003 if (!isset($this->_authupdate)) {
2004 trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'",
2005 'DBAUTH_AUTH_UPDATE', 'ADODB'),
2010 if ($this->_auth_crypt_method == 'crypt') {
2011 if (function_exists('crypt'))
2012 $submitted_password = crypt($submitted_password);
2014 $rs = $dbh->Execute(sprintf($this->_authupdate,
2015 $dbh->qstr($submitted_password),
2016 $dbh->qstr($this->_userid)
2026 * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in config/config.ini
2028 * Preferences are handled in _PassUser
2033 if ($this->_ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
2034 global $LDAP_SET_OPTION;
2035 if (!empty($LDAP_SET_OPTION)) {
2036 foreach ($LDAP_SET_OPTION as $key => $value) {
2037 //if (is_string($key) and defined($key))
2038 // $key = constant($key);
2039 ldap_set_option($this->_ldap, $key, $value);
2043 if (LDAP_AUTH_PASSWORD)
2044 // Windows Active Directory Server is strict
2045 $r = ldap_bind($this->_ldap, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD);
2047 $r = ldap_bind($this->_ldap, LDAP_AUTH_USER);
2049 $r = true; // anonymous bind allowed
2052 trigger_error(sprintf("Unable to bind LDAP server %s", LDAP_AUTH_HOST),
2056 return $this->_ldap;
2063 if (isset($this->_sr) and is_resource($this->_sr)) ldap_free_result($this->_sr);
2064 if (isset($this->_ldap) and is_resource($this->_ldap)) ldap_close($this->_ldap);
2066 unset($this->_ldap);
2069 function checkPass($submitted_password) {
2071 $this->_authmethod = 'LDAP';
2072 $userid = $this->_userid;
2073 if (!$this->isValidName()) {
2074 return $this->_tryNextPass($submitted_password);
2076 if (strstr($userid,'*')) {
2077 trigger_error(fmt("Invalid username '%s' for LDAP Auth",$userid),
2079 return WIKIAUTH_FORBIDDEN;
2082 if ($ldap = $this->_init()) {
2083 // Need to set the right root search information. See config/config.ini
2084 $st_search = LDAP_SEARCH_FIELD
2085 ? LDAP_SEARCH_FIELD."=$userid"
2087 if (!$this->_sr = ldap_search($ldap, LDAP_BASE_DN, $st_search)) {
2089 return $this->_tryNextPass($submitted_password);
2091 $info = ldap_get_entries($ldap, $this->_sr);
2092 if (empty($info["count"])) {
2094 return $this->_tryNextPass($submitted_password);
2096 // There may be more hits with this userid.
2097 // Of course it would be better to narrow down the BASE_DN
2098 for ($i = 0; $i < $info["count"]; $i++) {
2099 $dn = $info[$i]["dn"];
2100 // The password is still plain text.
2101 // On wrong password the ldap server will return:
2102 // "Unable to bind to server: Server is unwilling to perform"
2103 // The @ catches this error message.
2104 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
2105 // ldap_bind will return TRUE if everything matches
2107 $this->_level = WIKIAUTH_USER;
2108 return $this->_level;
2114 return $this->_tryNextPass($submitted_password);
2117 function userExists() {
2118 $userid = $this->_userid;
2119 if (strstr($userid,'*')) {
2120 trigger_error(fmt("Invalid username '%s' for LDAP Auth", $userid),
2124 if ($ldap = $this->_init()) {
2125 // Need to set the right root search information. see ../index.php
2126 $st_search = LDAP_SEARCH_FIELD
2127 ? LDAP_SEARCH_FIELD."=$userid"
2129 if (!$this->_sr = ldap_search($ldap, LDAP_BASE_DN, $st_search)) {
2131 return $this->_tryNextUser();
2133 $info = ldap_get_entries($ldap, $this->_sr);
2135 if ($info["count"] > 0) {
2141 return $this->_tryNextUser();
2144 function mayChangePass() {
2153 * Define the var IMAP_AUTH_HOST in config/config.ini (with port probably)
2155 * Preferences are handled in _PassUser
2158 function checkPass($submitted_password) {
2159 if (!$this->isValidName()) {
2160 return $this->_tryNextPass($submitted_password);
2162 $userid = $this->_userid;
2163 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
2164 $userid, $submitted_password, OP_HALFOPEN );
2167 $this->_authmethod = 'IMAP';
2168 $this->_level = WIKIAUTH_USER;
2169 return $this->_level;
2171 trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST,
2175 return $this->_tryNextPass($submitted_password);
2178 //CHECKME: this will not be okay for the auth policy strict
2179 function userExists() {
2182 if (checkPass($this->_prefs->get('passwd')))
2184 return $this->_tryNextUser();
2187 function mayChangePass() {
2194 extends _IMAPPassUser {
2196 * Define the var POP3_AUTH_HOST in config/config.ini
2197 * Preferences are handled in _PassUser
2199 function checkPass($submitted_password) {
2200 if (!$this->isValidName()) {
2201 return $this->_tryNextPass($submitted_password);
2203 $userid = $this->_userid;
2204 $pass = $submitted_password;
2205 $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost:110';
2206 if (defined('POP3_AUTH_PORT'))
2207 $port = POP3_AUTH_PORT;
2208 elseif (strstr($host,':')) {
2209 list(,$port) = split(':',$host);
2214 $fp = fsockopen($host, $port, $errno, $errstr, 10);
2216 // Get welcome string
2217 $line = fgets($fp, 1024);
2218 if (! strncmp("+OK ", $line, 4)) {
2220 fputs($fp, "user $userid\n");
2222 $line = fgets($fp, 1024);
2223 if (! strncmp("+OK ", $line, 4)) {
2225 fputs($fp, "pass $pass\n");
2227 $line = fgets($fp, 1024);
2228 if (! strncmp("+OK ", $line, 4)) {
2233 // quit the connection
2234 fputs($fp, "quit\n");
2235 // Get the sayonara message
2236 $line = fgets($fp, 1024);
2239 trigger_error(_("Couldn't connect to %s","POP3_AUTH_HOST ".$host.':'.$port),
2242 $this->_authmethod = 'POP3';
2244 $this->_level = WIKIAUTH_USER;
2246 $this->_level = WIKIAUTH_ANON;
2248 return $this->_level;
2255 * Check users defined in a .htaccess style file
2256 * username:crypt\n...
2258 * Preferences are handled in _PassUser
2261 var $_file, $_may_change;
2263 // This can only be called from _PassUser, because the parent class
2264 // sets the pref methods, before this class is initialized.
2265 function _FilePassUser($UserName='', $prefs=false, $file='') {
2266 if (!$this->_prefs and isa($this, "_FilePassUser")) {
2267 if ($prefs) $this->_prefs = $prefs;
2268 if (!isset($this->_prefs->_method))
2269 _PassUser::_PassUser($UserName);
2271 $this->_userid = $UserName;
2272 // read the .htaccess style file. We use our own copy of the standard pear class.
2273 //include_once 'lib/pear/File_Passwd.php';
2274 $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
2275 if (empty($file) and defined('AUTH_USER_FILE'))
2276 $file = AUTH_USER_FILE;
2277 include_once(dirname(__FILE__)."/pear/File_Passwd.php"); // same style as in main.php
2278 // "__PHP_Incomplete_Class"
2279 if (!empty($file) or empty($this->_file) or !isa($this->_file,"File_Passwd"))
2280 $this->_file = new File_Passwd($file, false, $file.'.lock');
2286 function mayChangePass() {
2287 return $this->_may_change;
2290 function userExists() {
2291 if (!$this->isValidName()) {
2292 return $this->_tryNextUser();
2294 $this->_authmethod = 'File';
2295 if (isset($this->_file->users[$this->_userid]))
2298 return $this->_tryNextUser();
2301 function checkPass($submitted_password) {
2302 if (!$this->isValidName()) {
2303 trigger_error(_("Invalid username"),E_USER_WARNING);
2304 return $this->_tryNextPass($submitted_password);
2306 //include_once 'lib/pear/File_Passwd.php';
2307 if ($this->_file->verifyPassword($this->_userid, $submitted_password)) {
2308 $this->_authmethod = 'File';
2309 $this->_level = WIKIAUTH_USER;
2310 if ($this->isAdmin()) // member of the Administrators group
2311 $this->_level = WIKIAUTH_ADMIN;
2312 return $this->_level;
2315 return $this->_tryNextPass($submitted_password);
2318 function storePass($submitted_password) {
2319 if (!$this->isValidName()) {
2322 if ($this->_may_change) {
2323 $this->_file = new File_Passwd($this->_file->_filename, true,
2324 $this->_file->_filename.'.lock');
2325 $result = $this->_file->modUser($this->_userid,$submitted_password);
2326 $this->_file->close();
2327 $this->_file = new File_Passwd($this->_file->_filename, false);
2336 * Insert more auth classes here...
2337 * For example a customized db class for another db connection
2338 * or a socket-based auth server.
2344 * For security, this class should not be extended. Instead, extend
2345 * from _PassUser (think of this as unix "root").
2347 * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
2348 * Other members of the Administrators group must raise their level otherwise somehow.
2349 * Currently every member is a AdminUser, which will not work for the various
2355 function mayChangePass() {
2358 function checkPass($submitted_password) {
2359 if ($this->_userid == ADMIN_USER)
2360 $stored_password = ADMIN_PASSWD;
2362 return $this->_tryNextPass($submitted_password);
2363 // TODO: safety check if really member of the ADMIN group?
2364 $stored_password = $this->_pref->get('passwd');
2366 if ($this->_checkPass($submitted_password, $stored_password)) {
2367 $this->_level = WIKIAUTH_ADMIN;
2368 return $this->_level;
2370 return $this->_tryNextPass($submitted_password);
2371 //$this->_level = WIKIAUTH_ANON;
2372 //return $this->_level;
2376 function storePass($submitted_password) {
2381 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2383 * Various data classes for the preference types,
2384 * to support get, set, sanify (range checking, ...)
2385 * update() will do the neccessary side-effects if a
2386 * setting gets changed (theme, language, ...)
2389 class _UserPreference
2393 function _UserPreference ($default_value) {
2394 $this->default_value = $default_value;
2397 function sanify ($value) {
2398 return (string)$value;
2401 function get ($name) {
2402 if (isset($this->{$name}))
2403 return $this->{$name};
2405 return $this->default_value;
2408 function getraw ($name) {
2409 if (!empty($this->{$name}))
2410 return $this->{$name};
2413 // stores the value as $this->$name, and not as $this->value (clever?)
2414 function set ($name, $value) {
2416 $value = $this->sanify($value);
2417 if ($this->get($name) != $value) {
2418 $this->update($value);
2421 if ($value != $this->default_value) {
2422 $this->{$name} = $value;
2424 unset($this->{$name});
2429 // default: no side-effects
2430 function update ($value) {
2435 class _UserPreference_numeric
2436 extends _UserPreference
2438 function _UserPreference_numeric ($default, $minval = false,
2440 $this->_UserPreference((double)$default);
2441 $this->_minval = (double)$minval;
2442 $this->_maxval = (double)$maxval;
2445 function sanify ($value) {
2446 $value = (double)$value;
2447 if ($this->_minval !== false && $value < $this->_minval)
2448 $value = $this->_minval;
2449 if ($this->_maxval !== false && $value > $this->_maxval)
2450 $value = $this->_maxval;
2455 class _UserPreference_int
2456 extends _UserPreference_numeric
2458 function _UserPreference_int ($default, $minval = false, $maxval = false) {
2459 $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
2462 function sanify ($value) {
2463 return (int)parent::sanify((int)$value);
2467 class _UserPreference_bool
2468 extends _UserPreference
2470 function _UserPreference_bool ($default = false) {
2471 $this->_UserPreference((bool)$default);
2474 function sanify ($value) {
2475 if (is_array($value)) {
2476 /* This allows for constructs like:
2478 * <input type="hidden" name="pref[boolPref][]" value="0" />
2479 * <input type="checkbox" name="pref[boolPref][]" value="1" />
2481 * (If the checkbox is not checked, only the hidden input
2482 * gets sent. If the checkbox is sent, both inputs get
2485 foreach ($value as $val) {
2491 return (bool) $value;
2495 class _UserPreference_language
2496 extends _UserPreference
2498 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
2499 $this->_UserPreference($default);
2502 // FIXME: check for valid locale
2503 function sanify ($value) {
2504 // Revert to DEFAULT_LANGUAGE if user does not specify
2505 // language in UserPreferences or chooses <system language>.
2506 if ($value == '' or empty($value))
2507 $value = DEFAULT_LANGUAGE;
2509 return (string) $value;
2512 function update ($newvalue) {
2513 if (! $this->_init ) {
2514 // invalidate etag to force fresh output
2515 $GLOBALS['request']->setValidators(array('%mtime' => false));
2516 update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
2521 class _UserPreference_theme
2522 extends _UserPreference
2524 function _UserPreference_theme ($default = THEME) {
2525 $this->_UserPreference($default);
2528 function sanify ($value) {
2529 if (!empty($value) and FindFile($this->_themefile($value)))
2531 return $this->default_value;
2534 function update ($newvalue) {
2536 // invalidate etag to force fresh output
2537 if (! $this->_init )
2538 $GLOBALS['request']->setValidators(array('%mtime' => false));
2540 include_once($this->_themefile($newvalue));
2541 if (empty($WikiTheme))
2542 include_once($this->_themefile(THEME));
2545 function _themefile ($theme) {
2546 return "themes/$theme/themeinfo.php";
2550 class _UserPreference_notify
2551 extends _UserPreference
2553 function sanify ($value) {
2557 return $this->default_value;
2560 /** update to global user prefs: side-effect on set notify changes
2561 * use a global_data notify hash:
2562 * notify = array('pagematch' => array(userid => ('email' => mail,
2563 * 'verified' => 0|1),
2567 function update ($value) {
2568 if (!empty($this->_init)) return;
2569 $dbh = $GLOBALS['request']->getDbh();
2570 $notify = $dbh->get('notify');
2575 // expand to existing pages only or store matches?
2576 // for now we store (glob-style) matches which is easier for the user
2577 $pages = $this->_page_split($value);
2578 // Limitation: only current user.
2579 $user = $GLOBALS['request']->getUser();
2580 if (!$user or !method_exists($user,'UserName')) return;
2581 // This fails with php5 and a WIKI_ID cookie:
2582 $userid = $user->UserName();
2583 $email = $user->_prefs->get('email');
2584 $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
2585 // check existing notify hash and possibly delete pages for email
2586 if (!empty($data)) {
2587 foreach ($data as $page => $users) {
2588 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
2589 unset($data[$page][$userid]);
2591 if (count($data[$page]) == 0)
2592 unset($data[$page]);
2595 // add the new pages
2596 if (!empty($pages)) {
2597 foreach ($pages as $page) {
2598 if (!isset($data[$page]))
2599 $data[$page] = array();
2600 if (!isset($data[$page][$userid])) {
2601 // should we really store the verification notice here or
2602 // check it dynamically at every page->save?
2604 $data[$page][$userid] = array('email' => $email,
2605 'verified' => $verified);
2607 $data[$page][$userid] = array('email' => $email);
2612 // store users changes
2613 $dbh->set('notify',$data);
2616 /** split the user-given comma or whitespace delimited pagenames
2619 function _page_split($value) {
2620 return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
2624 class _UserPreference_email
2625 extends _UserPreference
2627 function sanify($value) {
2628 // check for valid email address
2629 if ($this->get('email') == $value and $this->getraw('emailVerified'))
2632 if ($value == 1 or $value === true)
2634 list($ok,$msg) = ValidateMail($value,'noconnect');
2638 trigger_error("E-Mail Validation Error: ".$msg, E_USER_WARNING);
2639 return $this->default_value;
2643 /** Side-effect on email changes:
2644 * Send a verification mail or for now just a notification email.
2645 * For true verification (value = 2), we'd need a mailserver hook.
2647 function update($value) {
2648 if (!empty($this->_init)) return;
2649 $verified = $this->getraw('emailVerified');
2651 if (($value == 1 or $value === true) and $verified)
2653 if (!empty($value) and !$verified) {
2654 list($ok,$msg) = ValidateMail($value);
2655 if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
2656 sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
2657 WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true))))
2658 $this->set('emailVerified',1);
2663 /** Check for valid email address
2664 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
2666 function ValidateMail($email, $noconnect=false) {
2667 $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
2669 // well, technically ".a.a.@host.com" is also valid
2670 if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
2672 $result[1] = sprintf(_("E-Mail address '%s' is not properly formatted"), $email);
2676 return array(true,sprintf(_("E-Mail address '%s' is properly formatted"), $email));
2678 list ( $Username, $Domain ) = split ("@", $email);
2679 //Todo: getmxrr workaround on windows or manual input field to verify it manually
2680 if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
2681 $ConnectAddress = $MXHost[0];
2683 $ConnectAddress = $Domain;
2685 $Connect = @fsockopen ( $ConnectAddress, 25 );
2687 if (ereg("^220", $Out = fgets($Connect, 1024))) {
2688 fputs ($Connect, "HELO $HTTP_HOST\r\n");
2689 $Out = fgets ( $Connect, 1024 );
2690 fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
2691 $From = fgets ( $Connect, 1024 );
2692 fputs ($Connect, "RCPT TO: <".$email.">\r\n");
2693 $To = fgets ($Connect, 1024);
2694 fputs ($Connect, "QUIT\r\n");
2696 if (!ereg ("^250", $From)) {
2698 $result[1]="Server rejected address: ". $From;
2701 if (!ereg ( "^250", $To )) {
2703 $result[1]="Server rejected address: ". $To;
2708 $result[1] = "No response from server";
2713 $result[1]="Can not connect E-Mail server.";
2717 $result[1]="E-Mail address '$email' appears to be valid.";
2719 } // end of function
2721 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2726 * This object holds the $request->_prefs subobjects.
2727 * A simple packed array of non-default values get's stored as cookie,
2728 * homepage, or database, which are converted to the array of
2730 * We don't store the objects, because otherwise we will
2731 * not be able to upgrade any subobject. And it's a waste of space also.
2734 class UserPreferences
2736 function UserPreferences($saved_prefs = false) {
2737 // userid stored too, to ensure the prefs are being loaded for
2738 // the correct (currently signing in) userid if stored in a
2740 // Update: for db prefs we disallow passwd.
2741 // userid is needed for pref reflexion. current pref must know its username,
2742 // if some app needs prefs from different users, different from current user.
2745 'userid' => new _UserPreference(''),
2746 'passwd' => new _UserPreference(''),
2747 'autologin' => new _UserPreference_bool(),
2748 //'emailVerified' => new _UserPreference_emailVerified(),
2749 //fixed: store emailVerified as email parameter, 1.3.8
2750 'email' => new _UserPreference_email(''),
2751 'notifyPages' => new _UserPreference_notify(''), // 1.3.8
2752 'theme' => new _UserPreference_theme(THEME),
2753 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
2754 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2756 EDITWIDTH_MAX_COLS),
2757 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
2758 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2759 EDITHEIGHT_MIN_ROWS,
2760 EDITHEIGHT_DEFAULT_ROWS),
2761 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2762 TIMEOFFSET_MIN_HOURS,
2763 TIMEOFFSET_MAX_HOURS),
2764 'relativeDates' => new _UserPreference_bool(),
2765 'googleLink' => new _UserPreference_bool(), // 1.3.10
2767 // add custom theme-specific pref types:
2768 // FIXME: on theme changes the wiki_user session pref object will fail.
2769 // We will silently ignore this.
2770 if (!empty($customUserPreferenceColumns))
2771 $this->_prefs = array_merge($this->_prefs,$customUserPreferenceColumns);
2773 if (isset($this->_method) and $this->_method == 'SQL') {
2774 //unset($this->_prefs['userid']);
2775 unset($this->_prefs['passwd']);
2778 if (is_array($saved_prefs)) {
2779 foreach ($saved_prefs as $name => $value)
2780 $this->set($name, $value);
2784 function _getPref($name) {
2785 if ($name == 'emailVerified')
2787 if (!isset($this->_prefs[$name])) {
2788 if ($name == 'passwd2') return false;
2789 if ($name == 'passwd') return false;
2790 trigger_error("$name: unknown preference", E_USER_NOTICE);
2793 return $this->_prefs[$name];
2796 // get the value or default_value of the subobject
2797 function get($name) {
2798 if ($_pref = $this->_getPref($name))
2799 if ($name == 'emailVerified')
2800 return $_pref->getraw($name);
2802 return $_pref->get($name);
2807 // check and set the new value in the subobject
2808 function set($name, $value) {
2809 $pref = $this->_getPref($name);
2810 if ($pref === false)
2813 /* do it here or outside? */
2814 if ($name == 'passwd' and
2815 defined('PASSWORD_LENGTH_MINIMUM') and
2816 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2817 //TODO: How to notify the user?
2821 if ($name == 'theme' and $value == '')
2824 if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
2825 if ($name == 'emailVerified') $newvalue = $value;
2826 else $newvalue = $pref->sanify($value);
2827 $pref->set($name,$newvalue);
2829 $this->_prefs[$name] =& $pref;
2833 * use init to avoid update on set
2835 function updatePrefs($prefs, $init = false) {
2837 if ($init) $this->_init = $init;
2838 if (is_object($prefs)) {
2839 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2840 $obj->_init = $init;
2841 if ($obj->get($type) !== $prefs->get($type)) {
2842 if ($obj->set($type,$prefs->get($type)))
2845 foreach (array_keys($this->_prefs) as $type) {
2846 $obj =& $this->_prefs[$type];
2847 $obj->_init = $init;
2848 if ($prefs->get($type) !== $obj->get($type)) {
2849 // special systemdefault prefs: (probably not needed)
2850 if ($type == 'theme' and $prefs->get($type) == '' and
2851 $obj->get($type) == THEME) continue;
2852 if ($type == 'lang' and $prefs->get($type) == '' and
2853 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2854 if ($this->_prefs[$type]->set($type,$prefs->get($type)))
2858 } elseif (is_array($prefs)) {
2859 //unset($this->_prefs['userid']);
2861 if (isset($this->_method) and
2862 ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2863 unset($this->_prefs['passwd']);
2866 // emailVerified at first, the rest later
2867 $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2868 $obj->_init = $init;
2869 if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2870 if ($obj->set($type,$prefs[$type]))
2873 foreach (array_keys($this->_prefs) as $type) {
2874 $obj =& $this->_prefs[$type];
2875 $obj->_init = $init;
2876 if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool"))
2877 $prefs[$type] = false;
2878 if (isset($prefs[$type]) and isa($obj,"_UserPreference_int"))
2879 $prefs[$type] = (int) $prefs[$type];
2880 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2881 // special systemdefault prefs:
2882 if ($type == 'theme' and $prefs[$type] == '' and
2883 $obj->get($type) == THEME) continue;
2884 if ($type == 'lang' and $prefs[$type] == '' and
2885 $obj->get($type) == DEFAULT_LANGUAGE) continue;
2886 if ($obj->set($type,$prefs[$type]))
2894 // For now convert just array of objects => array of values
2895 // Todo: the specialized subobjects must override this.
2898 foreach ($this->_prefs as $name => $object) {
2899 if ($value = $object->getraw($name))
2900 $prefs[$name] = $value;
2901 if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2902 $prefs['emailVerified'] = $value;
2903 if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2904 $prefs['passwd'] = crypt($value);
2907 return $this->pack($prefs);
2910 // packed string or array of values => array of values
2911 // Todo: the specialized subobjects must override this.
2912 function retrieve($packed) {
2913 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2914 $packed = unserialize($packed);
2915 if (!is_array($packed)) return false;
2917 foreach ($packed as $name => $packed_pref) {
2918 if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2919 //legacy: check if it's an old array of objects
2920 // Looks like a serialized object.
2921 // This might fail if the object definition does not exist anymore.
2922 // object with ->$name and ->default_value vars.
2923 $pref = @unserialize($packed_pref);
2925 $pref = @unserialize(base64_decode($packed_pref));
2926 $prefs[$name] = $pref->get($name);
2927 // fix old-style prefs
2928 } elseif (is_numeric($name) and is_array($packed_pref)) {
2929 if (count($packed_pref) == 1) {
2930 list($name,$value) = each($packed_pref);
2931 $prefs[$name] = $value;
2934 $prefs[$name] = @unserialize($packed_pref);
2935 if (empty($prefs[$name]))
2936 $prefs[$name] = @unserialize(base64_decode($packed_pref));
2937 // patched by frederik@pandora.be
2938 if (empty($prefs[$name]))
2939 $prefs[$name] = $packed_pref;
2946 * Check if the given prefs object is different from the current prefs object
2948 function isChanged($other) {
2949 foreach ($this->_prefs as $type => $obj) {
2950 if ($obj->get($type) !== $other->get($type))
2956 function defaultPreferences() {
2958 foreach ($this->_prefs as $key => $obj) {
2959 $prefs[$key] = $obj->default_value;
2966 return $this->_prefs;
2969 function pack($nonpacked) {
2970 return serialize($nonpacked);
2973 function unpack($packed) {
2976 //$packed = base64_decode($packed);
2977 if (substr($packed, 0, 2) == "O:") {
2978 // Looks like a serialized object
2979 return unserialize($packed);
2981 if (substr($packed, 0, 2) == "a:") {
2982 return unserialize($packed);
2984 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2990 return hash($this->_prefs);
2994 /** TODO: new pref storage classes
2995 * These are currently user specific and should be rewritten to be pref specific.
2996 * i.e. $this == $user->_prefs
2998 class CookieUserPreferences
2999 extends UserPreferences
3001 function CookieUserPreferences ($saved_prefs = false) {
3002 //_AnonUser::_AnonUser('',$saved_prefs);
3003 UserPreferences::UserPreferences($saved_prefs);
3007 class PageUserPreferences
3008 extends UserPreferences
3010 function PageUserPreferences ($saved_prefs = false) {
3011 UserPreferences::UserPreferences($saved_prefs);
3015 class PearDbUserPreferences
3016 extends UserPreferences
3018 function PearDbUserPreferences ($saved_prefs = false) {
3019 UserPreferences::UserPreferences($saved_prefs);
3023 class AdoDbUserPreferences
3024 extends UserPreferences
3026 function AdoDbUserPreferences ($saved_prefs = false) {
3027 UserPreferences::UserPreferences($saved_prefs);
3029 function getPreferences() {
3030 // override the generic slow method here for efficiency
3031 _AnonUser::getPreferences();
3032 $this->getAuthDbh();
3033 if (isset($this->_select)) {
3034 $dbh = & $this->_auth_dbi;
3035 $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
3039 $prefs_blob = $rs->fields['pref_blob'];
3041 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
3042 $updated = $this->_prefs->updatePrefs($restored_from_db);
3043 //$this->_prefs = new UserPreferences($restored_from_db);
3044 return $this->_prefs;
3048 if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
3049 if ($restored_from_page = $this->_prefs->retrieve
3050 ($this->_HomePagehandle->get('pref'))) {
3051 $updated = $this->_prefs->updatePrefs($restored_from_page);
3052 //$this->_prefs = new UserPreferences($restored_from_page);
3053 return $this->_prefs;
3056 return $this->_prefs;
3061 // $Log: not supported by cvs2svn $
3062 // Revision 1.109 2004/10/07 16:08:58 rurban
3063 // fixed broken FileUser session handling.
3064 // thanks to Arnaud Fontaine for detecting this.
3065 // enable file user Administrator membership.
3067 // Revision 1.108 2004/10/05 17:00:04 rurban
3068 // support paging for simple lists
3069 // fix RatingDb sql backend.
3070 // remove pages from AllPages (this is ListPages then)
3072 // Revision 1.107 2004/10/04 23:42:15 rurban
3073 // HttpAuth admin group logic. removed old logs
3075 // Revision 1.106 2004/07/01 08:49:38 rurban
3076 // obsolete php5-patch.php: minor php5 login problem though
3078 // Revision 1.105 2004/06/29 06:48:03 rurban
3079 // Improve LDAP auth and GROUP_LDAP membership:
3080 // no error message on false password,
3081 // added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
3082 // fixed two group queries (this -> user)
3083 // stdlib: ConvertOldMarkup still flawed
3085 // Revision 1.104 2004/06/28 15:39:37 rurban
3086 // fixed endless recursion in WikiGroup: isAdmin()
3088 // Revision 1.103 2004/06/28 15:01:07 rurban
3089 // fixed LDAP_SET_OPTION handling, LDAP error on connection problem
3091 // Revision 1.102 2004/06/27 10:23:48 rurban
3092 // typo detected by Philippe Vanhaesendonck
3094 // Revision 1.101 2004/06/25 14:29:19 rurban
3095 // WikiGroup refactoring:
3096 // global group attached to user, code for not_current user.
3097 // improved helpers for special groups (avoid double invocations)
3098 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
3099 // fixed a XHTML validation error on userprefs.tmpl
3101 // Revision 1.100 2004/06/21 06:29:35 rurban
3102 // formatting: linewrap only
3104 // Revision 1.99 2004/06/20 15:30:05 rurban
3105 // get_class case-sensitivity issues
3107 // Revision 1.98 2004/06/16 21:24:31 rurban
3108 // do not display no-connect warning: #2662
3110 // Revision 1.97 2004/06/16 13:21:16 rurban
3111 // stabilize on failing ldap queries or bind
3113 // Revision 1.96 2004/06/16 12:42:06 rurban
3114 // fix homepage prefs
3116 // Revision 1.95 2004/06/16 10:38:58 rurban
3117 // Disallow refernces in calls if the declaration is a reference
3118 // ("allow_call_time_pass_reference clean").
3119 // PhpWiki is now allow_call_time_pass_reference = Off clean,
3120 // but several external libraries may not.
3121 // In detail these libs look to be affected (not tested):
3125 // Revision 1.94 2004/06/15 10:40:35 rurban
3126 // minor WikiGroup cleanup: no request param, start of current user independency
3128 // Revision 1.93 2004/06/15 09:15:52 rurban
3129 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
3130 // fix encrypted usage, actually store and retrieve them from db
3131 // fix bogologin with passwd set.
3132 // fix php crashes with call-time pass-by-reference (references wrongly used
3133 // in declaration AND call). This affected mainly Apache2 and IIS.
3134 // (Thanks to John Cole to detect this!)
3136 // Revision 1.92 2004/06/14 11:31:36 rurban
3137 // renamed global $Theme to $WikiTheme (gforge nameclash)
3138 // inherit PageList default options from PageList
3139 // default sortby=pagename
3140 // use options in PageList_Selectable (limit, sortby, ...)
3141 // added action revert, with button at action=diff
3142 // added option regex to WikiAdminSearchReplace
3144 // Revision 1.91 2004/06/08 14:57:43 rurban
3145 // stupid ldap bug detected by John Cole
3147 // Revision 1.90 2004/06/08 09:31:15 rurban
3148 // fixed typo detected by lucidcarbon (line 1663 assertion)
3150 // Revision 1.89 2004/06/06 16:58:51 rurban
3151 // added more required ActionPages for foreign languages
3152 // install now english ActionPages if no localized are found. (again)
3153 // fixed default anon user level to be 0, instead of -1
3154 // (wrong "required administrator to view this page"...)
3156 // Revision 1.88 2004/06/04 20:32:53 rurban
3157 // Several locale related improvements suggested by Pierrick Meignen
3158 // LDAP fix by John Cole
3159 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
3161 // Revision 1.87 2004/06/04 12:40:21 rurban
3162 // Restrict valid usernames to prevent from attacks against external auth or compromise
3164 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
3165 // Fxied more warnings
3167 // Revision 1.86 2004/06/03 18:06:29 rurban
3168 // fix file locking issues (only needed on write)
3169 // fixed immediate LANG and THEME in-session updates if not stored in prefs
3170 // advanced editpage toolbars (search & replace broken)
3172 // Revision 1.85 2004/06/03 12:46:03 rurban
3173 // fix signout, level must be 0 not -1
3175 // Revision 1.84 2004/06/03 12:36:03 rurban
3176 // fix eval warning on signin
3178 // Revision 1.83 2004/06/03 10:18:19 rurban
3179 // fix User locking issues, new config ENABLE_PAGEPERM
3181 // Revision 1.82 2004/06/03 09:39:51 rurban
3182 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
3184 // Revision 1.81 2004/06/02 18:01:45 rurban
3185 // init global FileFinder to add proper include paths at startup
3186 // adds PHPWIKI_DIR if started from another dir, lib/pear also
3187 // fix slashify for Windows
3188 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
3190 // Revision 1.80 2004/06/02 14:20:27 rurban
3191 // fix adodb DbPassUser login
3193 // Revision 1.79 2004/06/01 15:27:59 rurban
3194 // AdminUser only ADMIN_USER not member of Administrators
3195 // some RateIt improvements by dfrankow
3196 // edit_toolbar buttons
3198 // Revision 1.78 2004/05/27 17:49:06 rurban
3199 // renamed DB_Session to DbSession (in CVS also)
3200 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
3201 // remove leading slash in error message
3202 // added force_unlock parameter to File_Passwd (no return on stale locks)
3203 // fixed adodb session AffectedRows
3204 // added FileFinder helpers to unify local filenames and DATA_PATH names
3205 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
3207 // Revision 1.77 2004/05/18 14:49:51 rurban
3208 // Simplified strings for easier translation
3210 // Revision 1.76 2004/05/18 13:30:04 rurban
3211 // prevent from endless loop with oldstyle warnings
3213 // Revision 1.75 2004/05/16 22:07:35 rurban
3214 // check more config-default and predefined constants
3215 // various PagePerm fixes:
3216 // fix default PagePerms, esp. edit and view for Bogo and Password users
3217 // implemented Creator and Owner
3218 // BOGOUSERS renamed to BOGOUSER
3219 // fixed syntax errors in signin.tmpl
3221 // Revision 1.74 2004/05/15 19:48:33 rurban
3222 // fix some too loose PagePerms for signed, but not authenticated users
3223 // (admin, owner, creator)
3224 // no double login page header, better login msg.
3225 // moved action_pdf to lib/pdf.php
3227 // Revision 1.73 2004/05/15 18:31:01 rurban
3228 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
3230 // Revision 1.72 2004/05/12 10:49:55 rurban
3231 // require_once fix for those libs which are loaded before FileFinder and
3232 // its automatic include_path fix, and where require_once doesn't grok
3233 // dirname(__FILE__) != './lib'
3234 // upgrade fix with PearDB
3235 // navbar.tmpl: remove spaces for IE button alignment
3237 // Revision 1.71 2004/05/10 12:34:47 rurban
3238 // stabilize DbAuthParam statement pre-prozessor:
3239 // try old-style and new-style (double-)quoting
3240 // reject unknown $variables
3241 // use ->prepare() for all calls (again)
3243 // Revision 1.70 2004/05/06 19:26:16 rurban
3244 // improve stability, trying to find the InlineParser endless loop on sf.net
3246 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
3248 // Revision 1.69 2004/05/06 13:56:40 rurban
3249 // Enable the Administrators group, and add the WIKIPAGE group default root page.
3251 // Revision 1.68 2004/05/05 13:37:54 rurban
3252 // Support to remove all UserPreferences
3254 // Revision 1.66 2004/05/03 21:44:24 rurban
3255 // fixed sf,net bug #947264: LDAP options are constants, not strings!
3257 // Revision 1.65 2004/05/03 13:16:47 rurban
3258 // fixed UserPreferences update, esp for boolean and int
3260 // Revision 1.64 2004/05/02 15:10:06 rurban
3261 // new finally reliable way to detect if /index.php is called directly
3262 // and if to include lib/main.php
3263 // new global AllActionPages
3264 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
3265 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
3266 // PageGroupTestOne => subpages
3267 // renamed PhpWikiRss to PhpWikiRecentChanges
3268 // more docs, default configs, ...
3270 // Revision 1.63 2004/05/01 15:59:29 rurban
3271 // more php-4.0.6 compatibility: superglobals
3273 // Revision 1.62 2004/04/29 18:31:24 rurban
3274 // Prevent from warning where no db pref was previously stored.
3276 // Revision 1.61 2004/04/29 17:18:19 zorloc
3277 // 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.
3279 // Revision 1.60 2004/04/27 18:20:54 rurban
3280 // sf.net patch #940359 by rassie
3282 // Revision 1.59 2004/04/26 12:35:21 rurban
3283 // POP3_AUTH_PORT deprecated, use "host:port" similar to IMAP
3284 // File_Passwd is already loaded
3286 // Revision 1.58 2004/04/20 17:08:28 rurban
3287 // Some IniConfig fixes: prepend our private lib/pear dir
3288 // switch from " to ' in the auth statements
3289 // use error handling.
3290 // WikiUserNew changes for the new "'$variable'" syntax
3291 // in the statements
3292 // TODO: optimization to put config vars into the session.
3294 // Revision 1.57 2004/04/19 18:27:45 rurban
3295 // Prevent from some PHP5 warnings (ref args, no :: object init)
3296 // php5 runs now through, just one wrong XmlElement object init missing
3297 // Removed unneccesary UpgradeUser lines
3298 // Changed WikiLink to omit version if current (RecentChanges)
3300 // Revision 1.56 2004/04/19 09:13:24 rurban
3301 // new pref: googleLink
3303 // Revision 1.54 2004/04/18 00:24:45 rurban
3304 // re-use our simple prepare: just for table prefix warnings
3306 // Revision 1.53 2004/04/12 18:29:15 rurban
3307 // exp. Session auth for already authenticated users from another app
3309 // Revision 1.52 2004/04/12 13:04:50 rurban
3310 // added auth_create: self-registering Db users
3312 // removed rating recommendations
3313 // ziplib reformatting
3315 // Revision 1.51 2004/04/11 10:42:02 rurban
3316 // pgsrc/CreatePagePlugin
3318 // Revision 1.50 2004/04/10 05:34:35 rurban
3321 // Revision 1.49 2004/04/07 23:13:18 rurban
3322 // fixed pear/File_Passwd for Windows
3323 // fixed FilePassUser sessions (filehandle revive) and password update
3325 // Revision 1.48 2004/04/06 20:00:10 rurban
3326 // Cleanup of special PageList column types
3327 // Added support of plugin and theme specific Pagelist Types
3328 // Added support for theme specific UserPreferences
3329 // Added session support for ip-based throttling
3330 // sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
3331 // Enhanced postgres schema
3332 // Added DB_Session_dba support
3334 // Revision 1.47 2004/04/02 15:06:55 rurban
3335 // fixed a nasty ADODB_mysql session update bug
3336 // improved UserPreferences layout (tabled hints)
3337 // fixed UserPreferences auth handling
3338 // improved auth stability
3339 // improved old cookie handling: fixed deletion of old cookies with paths
3341 // Revision 1.46 2004/04/01 06:29:51 rurban
3343 // RateIt also for ADODB
3349 // c-basic-offset: 4
3350 // c-hanging-comment-ender-p: nil
3351 // indent-tabs-mode: nil