2 rcs_id('$Id: WikiUserNew.php,v 1.22 2004-02-27 05:15:40 rurban Exp $');
5 * This is a complete OOP rewrite of the old WikiUser code with various
6 * configurable external authentification methods.
8 * There's only one entry point, the function WikiUser which returns
9 * a WikiUser object, which contains the user's preferences.
10 * This object might get upgraded during the login step and later also.
11 * There exist three preferences storage methods: cookie, homepage and db,
12 * and multiple password checking methods.
13 * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if
14 * ALLOW_USER_PASSWORDS is defined.
16 * Each user object must define the two preferences methods
17 * getPreferences(), setPreferences(),
18 * and the following 1-4 auth methods
19 * checkPass() must be defined by all classes,
20 * userExists() only if USER_AUTH_POLICY'=='strict'
21 * mayChangePass() only if the password is storable.
22 * storePass() only if the password is storable.
24 * WikiUser() given no name, returns an _AnonUser (anonymous user)
25 * object, who may or may not have a cookie.
26 * However, if the there's a cookie with the userid or a session,
27 * the user is upgraded to the matching user object.
28 * Given a user name, returns a _BogoUser object, who may or may not
29 * have a cookie and/or PersonalPage, one of the various _PassUser objects
30 * or an _AdminUser object.
32 * Takes care of passwords, all preference loading/storing in the
33 * user's page and any cookies. lib/main.php will query the user object to
34 * verify the password as appropriate.
36 * Notes by 2004-01-25 03:43:45 rurban
37 * Test it by defining ENABLE_USER_NEW in index.php
38 * 1) Now a ForbiddenUser is returned instead of false.
39 * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
40 * but may browse. Now with ALLOW_ANON_USER = false he may not browse,
41 * which is needed to disable browse PagePermissions. Hmm...
42 * I added now ALLOW_ANON_EDIT = true to makes things clear.
43 * (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
45 * Authors: Reini Urban (the tricky parts),
46 * Carsten Klapp (started rolling the ball)
49 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
50 define('WIKIAUTH_ANON', 0); // Not signed in.
51 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
52 define('WIKIAUTH_USER', 2); // Bogo user with a password.
53 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
55 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
56 if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
58 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
59 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
60 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
62 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
63 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
64 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
66 define('TIMEOFFSET_MIN_HOURS', -26);
67 define('TIMEOFFSET_MAX_HOURS', 26);
68 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
71 * There are be the following constants in index.php to
72 * establish login parameters:
74 * ALLOW_ANON_USER default true
75 * ALLOW_ANON_EDIT default true
76 * ALLOW_BOGO_LOGIN default true
77 * ALLOW_USER_PASSWORDS default true
78 * PASSWORD_LENGTH_MINIMUM default 6?
80 * To require user passwords for editing:
81 * ALLOW_ANON_USER = true
82 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
83 * ALLOW_BOGO_LOGIN = false
84 * ALLOW_USER_PASSWORDS = true
86 * To establish a COMPLETELY private wiki, such as an internal
88 * ALLOW_ANON_USER = false
89 * (and probably require user passwords as described above). In this
90 * case the user will be prompted to login immediately upon accessing
93 * There are other possible combinations, but the typical wiki (such
94 * as PhpWiki.sf.net) would usually just leave all four enabled.
98 // The last object in the row is the bad guy...
99 if (!is_array($USER_AUTH_ORDER))
100 $USER_AUTH_ORDER = array("Forbidden");
102 $USER_AUTH_ORDER[] = "Forbidden";
104 // Local convenience functions.
105 function _isAnonUserAllowed() {
106 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
108 function _isBogoUserAllowed() {
109 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
111 function _isUserPasswordsAllowed() {
112 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
116 // Possibly upgrade userobject functions.
117 function _determineAdminUserOrOtherUser($UserName) {
118 // Sanity check. User name is a condition of the definition of the
119 // _AdminUser, _BogoUser and _passuser.
121 return $GLOBALS['ForbiddenUser'];
123 if ($UserName == ADMIN_USER)
124 return new _AdminUser($UserName);
126 return _determineBogoUserOrPassUser($UserName);
129 function _determineBogoUserOrPassUser($UserName) {
130 global $ForbiddenUser;
132 // Sanity check. User name is a condition of the definition of
133 // _BogoUser and _PassUser.
135 return $ForbiddenUser;
137 // Check for password and possibly upgrade user object.
138 $_BogoUser = new _BogoUser($UserName);
139 if (_isUserPasswordsAllowed()) {
140 if (/*$has_password =*/ $_BogoUser->_prefs->get('passwd'))
141 return new _PassUser($UserName);
142 else { // PassUsers override BogoUsers if they exist
143 $_PassUser = new _PassUser($UserName);
144 if ($_PassUser->userExists())
148 // User has no password.
149 if (_isBogoUserAllowed())
152 // Passwords are not allowed, and Bogo is disallowed too. (Only
153 // the admin can sign in).
154 return $ForbiddenUser;
158 * Primary WikiUser function, called by main.php.
160 * This determines the user's type and returns an appropriate user
161 * object. lib/main.php then querys the resultant object for password
162 * validity as necessary.
164 * If an _AnonUser object is returned, the user may only browse pages
165 * (and save prefs in a cookie).
167 * To disable access but provide prefs the global $ForbiddenUser class
168 * is returned. (was previously false)
171 function WikiUser ($UserName = '') {
172 global $ForbiddenUser;
174 //Maybe: Check sessionvar for username & save username into
175 //sessionvar (may be more appropriate to do this in lib/main.php).
177 $ForbiddenUser = new _ForbiddenUser($UserName);
178 // Found a user name.
179 return _determineAdminUserOrOtherUser($UserName);
181 elseif (!empty($_SESSION['userid'])) {
182 // Found a user name.
183 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
184 return _determineAdminUserOrOtherUser($_SESSION['userid']);
187 // Check for autologin pref in cookie and possibly upgrade
188 // user object to another type.
189 $_AnonUser = new _AnonUser();
190 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
191 // Found a user name.
192 $ForbiddenUser = new _ForbiddenUser($UserName);
193 return _determineAdminUserOrOtherUser($UserName);
196 $ForbiddenUser = new _ForbiddenUser();
197 if (_isAnonUserAllowed())
199 return $ForbiddenUser; // User must sign in to browse pages.
201 return $ForbiddenUser; // User must sign in with a password.
204 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
205 . "Unexpectedly, an appropriate user class could not be determined.");
206 return $ForbiddenUser; // Failsafe.
210 function WikiUserClassname() {
214 function UpgradeUser ($olduser, $user) {
215 if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
216 // populate the upgraded class $olduser with the values from the new user object
217 foreach (get_object_vars($user) as $k => $v) {
218 if (!empty($v)) $olduser->$k = $v;
220 $GLOBALS['request']->_user = $olduser;
227 function UserExists ($UserName) {
229 if (!($user = $request->getUser()))
230 $user = WikiUser($UserName);
233 if ($user->userExists($UserName)) {
234 $request->_user = $user;
237 if (isa($user,'_BogoUser'))
238 $user = new _PassUser($UserName);
239 while ($user = $user->nextClass()) {
240 return $user->userExists($UserName);
241 $this = $user; // does this work on all PHP version?
243 $request->_user = $GLOBALS['ForbiddenUser'];
247 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
249 // Base WikiUser class.
254 var $_level = WIKIAUTH_FORBIDDEN;
256 var $_HomePagehandle = false;
259 function _WikiUser($UserName = '') {
261 $this->_userid = $UserName;
263 $this->_HomePagehandle = $this->hasHomePage();
265 $this->getPreferences();
268 function UserName() {
269 if (!empty($this->_userid))
270 return $this->_userid;
273 function getPreferences() {
274 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
275 . "New subclasses of _WikiUser must override this function.");
279 function setPreferences($prefs, $id_only) {
280 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
281 . "New subclasses of _WikiUser must override this function.");
285 function userExists() {
286 return $this->hasHomePage();
289 function checkPass($submitted_password) {
290 // By definition, an undefined user class cannot sign in.
291 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
292 . "New subclasses of _WikiUser must override this function.");
296 // returns page_handle to user's home page or false if none
297 function hasHomePage() {
298 if ($this->_userid) {
299 if ($this->_HomePagehandle) {
300 return $this->_HomePagehandle->exists();
303 // check db again (maybe someone else created it since
306 $this->_HomePagehandle = $request->getPage($this->_userid);
307 return $this->_HomePagehandle->exists();
314 // innocent helper: case-insensitive position in _auth_methods
315 function array_position ($string, $array) {
316 $string = strtolower($string);
317 for ($found = 0; $found < count($array); $found++) {
318 if (strtolower($array[$found]) == $string)
324 function nextAuthMethodIndex() {
325 if (empty($this->_auth_methods))
326 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
327 if (empty($this->_current_index)) {
328 if (get_class($this) != '_passuser') {
329 $this->_current_method = substr(get_class($this),1,-8);
330 $this->_current_index = $this->array_position($this->_current_method,
331 $this->_auth_methods);
333 $this->_current_index = -1;
336 $this->_current_index++;
337 if ($this->_current_index >= count($this->_auth_methods))
339 $this->_current_method = $this->_auth_methods[$this->_current_index];
340 return $this->_current_index;
343 function AuthMethod($index = false) {
344 return $this->_auth_methods[ $index === false ? 0 : $index];
347 // upgrade the user object
348 function nextClass() {
349 if (($next = $this->nextAuthMethodIndex()) !== false) {
350 $method = $this->AuthMethod($next);
351 $class = "_".$method."PassUser";
352 if ($user = new $class($this->_userid)) {
353 // prevent from endless recursion.
354 //$user->_current_method = $this->_current_method;
355 //$user->_current_index = $this->_current_index;
356 $user = UpgradeUser($user, $this);
362 //Fixme: for _HttpAuthPassUser
363 function PrintLoginForm (&$request, $args, $fail_message = false,
364 $seperate_page = true) {
365 include_once('lib/Template.php');
366 // Call update_locale in case the system's default language is not 'en'.
367 // (We have no user pref for lang at this point yet, no one is logged in.)
368 update_locale(DEFAULT_LANGUAGE);
369 $userid = $this->_userid;
371 extract($args); // fixme
373 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
375 $pagename = $request->getArg('pagename');
377 $login = new Template('login', $request,
378 compact('pagename', 'userid', 'require_level',
379 'fail_message', 'pass_required', 'nocache'));
380 if ($seperate_page) {
381 $top = new Template('html', $request,
382 array('TITLE' => _("Sign In")));
383 return $top->printExpansion($login);
389 // signed in but probably not password checked
390 function isSignedIn() {
391 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
394 function isAuthenticated () {
395 //return isa($this,'_PassUser');
396 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
397 return $this->_level >= WIKIAUTH_BOGO; // hmm.
400 function isAdmin () {
401 return $this->_level == WIKIAUTH_ADMIN;
405 return ( $this->UserName()
407 : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
410 function getAuthenticatedId() {
411 return ( $this->isAuthenticated()
413 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
416 function hasAuthority ($require_level) {
417 return $this->_level >= $require_level;
420 function AuthCheck ($postargs) {
421 // Normalize args, and extract.
422 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
424 foreach ($keys as $key)
425 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
427 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
429 if ($logout) { // Log out
430 $GLOBALS['request']->_user = new _AnonUser();
431 return $GLOBALS['request']->_user;
433 return false; // User hit cancel button.
434 elseif (!$login && !$userid)
435 return false; // Nothing to do?
437 $authlevel = $this->checkPass($passwd);
439 return _("Invalid password or userid.");
440 elseif ($authlevel < $require_level)
441 return _("Insufficient permissions.");
444 $user = $GLOBALS['request']->_user;
445 $user->_userid = $userid;
446 $user->_level = $authlevel;
455 var $_level = WIKIAUTH_ANON;
457 // Anon only gets to load and save prefs in a cookie, that's it.
458 function getPreferences() {
461 if (empty($this->_prefs))
462 $this->_prefs = new UserPreferences;
463 $UserName = $this->UserName();
464 if ($cookie = $request->getCookieVar(WIKI_NAME)) {
465 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
466 trigger_error(_("Format of UserPreferences cookie not recognised.") . " "
467 . _("Default preferences will be used."),
470 // TODO: try reading userid from old PhpWiki cookie
471 // formats, then delete old cookie from browser!
474 // try old cookie format.
475 //$cookie = $request->getCookieVar('WIKI_ID');
479 * Only keep the cookie if it matches the UserName who is
480 * signing in or if this really is an Anon login (no
481 * username). (Remember, _BogoUser and higher inherit this
484 if (! $UserName || $UserName == $unboxedcookie['userid']) {
485 $this->_prefs = new UserPreferences($unboxedcookie);
486 $this->_userid = $unboxedcookie['userid'];
489 // initializeTheme() needs at least an empty object
490 if (! $this->_prefs )
491 $this->_prefs = new UserPreferences;
492 return $this->_prefs;
495 function setPreferences($prefs, $id_only=false) {
496 // Allow for multiple wikis in same domain. Encode only the
497 // _prefs array of the UserPreference object. Ideally the
498 // prefs array should just be imploded into a single string or
499 // something so it is completely human readable by the end
500 // user. In that case stricter error checking will be needed
501 // when loading the cookie.
502 if (!is_object($prefs)) {
503 $prefs = new UserPreferences($prefs);
505 $packed = $prefs->store();
506 $unpacked = $prefs->unpack($packed);
507 if (!empty($unpacked)) { // check how many are different from the default_value
508 setcookie(WIKI_NAME, $packed,
509 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
511 if (count($unpacked)) {
513 $this->_prefs = $prefs;
514 $request->_prefs =& $this->_prefs;
515 $request->_user->_prefs =& $this->_prefs;
516 //$request->setSessionVar('wiki_prefs', $this->_prefs);
517 $request->setSessionVar('wiki_user', $request->_user);
519 return count($unpacked);
522 function userExists() {
526 function checkPass($submitted_password) {
527 // By definition, the _AnonUser does not HAVE a password
528 // (compared to _BogoUser, who has an EMPTY password).
529 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
530 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
531 . "New subclasses of _WikiUser must override this function.");
540 var $_level = WIKIAUTH_FORBIDDEN;
542 function checkPass($submitted_password) {
543 return WIKIAUTH_FORBIDDEN;
546 function userExists() {
547 if ($this->_HomePagehandle) return true;
551 class _ForbiddenPassUser
552 extends _ForbiddenUser
560 * Do NOT extend _BogoUser to other classes, for checkPass()
561 * security. (In case of defects in code logic of the new class!)
566 function userExists() {
567 if (isWikiWord($this->_userid)) {
568 $this->_level = WIKIAUTH_BOGO;
571 $this->_level = WIKIAUTH_ANON;
576 function checkPass($submitted_password) {
577 // By definition, BogoUser has an empty password.
579 return $this->_level;
586 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
588 * The classes for all subsequent auth methods extend from
590 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
591 * the three auth method policies first-only, strict and stacked
592 * and the two methods for prefs: homepage or database,
593 * if $DBAuthParams['pref_select'] is defined.
595 * Default is PersonalPage auth and prefs.
597 * TODO: password changing
598 * TODO: email verification
601 var $_auth_dbi, $_prefmethod, $_prefselect, $_prefupdate;
602 var $_current_method, $_current_index;
604 // check and prepare the auth and pref methods only once
605 function _PassUser($UserName = '') {
606 global $DBAuthParams, $DBParams;
609 $this->_userid = $UserName;
610 if ($this->hasHomePage())
611 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
613 // Check the configured Prefs methods
614 if ( !empty($DBAuthParams['pref_select']) ) {
615 if ( $DBParams['dbtype'] == 'SQL' and !@is_int($this->_prefselect)) {
616 $this->_prefmethod = 'SQL'; // really pear db
618 // preparate the SELECT statement
619 $this->_prefselect = $this->_auth_dbi->prepare(
620 str_replace('"$userid"','?',$DBAuthParams['pref_select'])
623 if ( $DBParams['dbtype'] == 'ADODB' and !isset($this->_prefselect)) {
624 $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
626 // preparate the SELECT statement
627 $this->_prefselect = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
630 unset($this->_prefselect);
632 if ( !empty($DBAuthParams['pref_update']) and
633 $DBParams['dbtype'] == 'SQL' and
634 !@is_int($this->_prefupdate)) {
635 $this->_prefmethod = 'SQL';
637 $this->_prefupdate = $this->_auth_dbi->prepare(
638 str_replace(array('"$userid"','"$pref_blob"'),array('?','?'),$DBAuthParams['pref_update'])
641 if ( !empty($DBAuthParams['pref_update']) and
642 $DBParams['dbtype'] == 'ADODB' and
643 !isset($this->_prefupdate)) {
644 $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
646 // preparate the SELECT statement
647 $this->_prefupdate = str_replace(array('"$userid"','"$pref_blob"'),array('%s','%s'),
648 $DBAuthParams['pref_update']);
650 $this->getPreferences();
652 // Upgrade to the next parent _PassUser class. Avoid recursion.
653 if ( get_class($this) === '_passuser' ) { // hopefully PHP will keep this lowercase
654 //auth policy: Check the order of the configured auth methods
655 // 1. first-only: Upgrade the class here in the constructor
656 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as in the previous PhpWiki releases (slow)
657 // 3. strict: upgrade the class after checking the user existance in userExists()
658 // 4. stacked: upgrade the class after the password verification in checkPass()
659 // Methods: PersonalPage, HTTP_AUTH, DB, LDAP, IMAP, File
660 if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
661 if (defined('USER_AUTH_POLICY')) {
662 // policy 1: only pre-define one method for all users
663 if (USER_AUTH_POLICY === 'first-only') {
664 if ($user = $this->nextClass())
667 return $GLOBALS['ForbiddenUser'];
669 // use the default behaviour from the previous versions:
670 elseif (USER_AUTH_POLICY === 'old') {
671 // default: try to be smart
672 if (!empty($GLOBALS['PHP_AUTH_USER'])) {
673 return new _HttpAuthPassUser($UserName);
674 } elseif (!empty($DBAuthParams['auth_check']) and
675 (!empty($DBAuthParams['auth_dsn']) or !empty($GLOBALS ['DBParams']['dsn']))) {
676 return new _DbPassUser($UserName);
677 } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
678 return new _LDAPPassUser($UserName);
679 } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
680 return new _IMAPPassUser($UserName);
681 } elseif (defined('AUTH_USER_FILE')) {
682 return new _FilePassUser($UserName);
684 return new _PersonalPagePassUser($UserName);
688 // else use the page methods defined in _PassUser.
694 function getAuthDbh () {
695 global $request, $DBParams, $DBAuthParams;
697 // session restauration doesn't re-connect to the database automatically, so dirty it here.
698 if (($DBParams['dbtype'] == 'SQL') and isset($this->_auth_dbi) and empty($this->_auth_dbi->connection))
699 unset($this->_auth_dbi);
700 if (($DBParams['dbtype'] == 'ADODB') and isset($this->_auth_dbi) and empty($this->_auth_dbi->_connectionID))
701 unset($this->_auth_dbi);
703 if (empty($this->_auth_dbi)) {
704 if (empty($DBAuthParams['auth_dsn'])) {
705 if ($DBParams['dbtype'] == 'SQL')
706 $dbh = $request->getDbh(); // use phpwiki database
710 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
711 $dbh = $request->getDbh(); // same phpwiki database
712 else // use another external database handle. needs PHP >= 4.1
713 $dbh = WikiDB::open($DBAuthParams);
715 $this->_auth_dbi =& $dbh->_backend->_dbh;
717 return $this->_auth_dbi;
720 function prepare ($stmt, $variables) {
721 global $DBParams, $request;
722 // preparate the SELECT statement, for ADODB and PearDB (MDB not)
724 $place = ($DBParams['dbtype'] == 'ADODB') ? '%s' : '?';
725 if (is_array($variables)) {
727 foreach ($variables as $v) { $new[] = $place; }
731 // probably prefix table names if in same database
732 if (!empty($DBParams['prefix']) and
733 $this->_auth_dbi === $request->_dbi->_backend->_dbh) {
734 if (!stristr($DBParams['prefix'],$stmt)) {
735 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
736 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php: $stmt",
738 $stmt = str_replace(array(" user "," pref "," member "),
739 array(" ".$prefix."user ",
740 " ".$prefix."prefs ",
741 " ".$prefix."member "),$stmt);
744 return $this->_auth_dbi->prepare(str_replace($variables,$new,$stmt));
747 function getPreferences() {
748 if (!empty($this->_prefmethod)) {
749 if ($this->_prefmethod == 'ADODB') {
750 _AdoDbPassUser::_AdoDbPassUser();
751 return _AdoDbPassUser::getPreferences();
752 } elseif ($this->_prefmethod == 'SQL') {
753 _PearDbPassUser::_PearDbPassUser();
754 return _PearDbPassUser::getPreferences();
758 // We don't necessarily have to read the cookie first. Since
759 // the user has a password, the prefs stored in the homepage
760 // cannot be arbitrarily altered by other Bogo users.
761 _AnonUser::getPreferences();
762 // User may have deleted cookie, retrieve from his
763 // PersonalPage if there is one.
764 if (! $this->_prefs && $this->_HomePagehandle) {
765 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
766 $this->_prefs = new UserPreferences($restored_from_page);
767 return $this->_prefs;
770 return $this->_prefs;
773 function setPreferences($prefs, $id_only=false) {
774 if (!empty($this->_prefmethod)) {
775 if ($this->_prefmethod == 'ADODB') {
776 _AdoDbPassUser::_AdoDbPassUser();
777 return _AdoDbPassUser::setPreferences($prefs, $id_only);
779 elseif ($this->_prefmethod == 'SQL') {
780 _PearDbPassUser::_PearDbPassUser();
781 return _PearDbPassUser::setPreferences($prefs, $id_only);
785 _AnonUser::setPreferences($prefs, $id_only);
786 // Encode only the _prefs array of the UserPreference object
787 if (!is_object($prefs)) {
788 $prefs = new UserPreferences($prefs);
790 $packed = $prefs->store();
791 $unpacked = $prefs->unpack($packed);
792 if (count($unpacked)) {
794 $this->_prefs = $prefs;
795 $request->_prefs =& $this->_prefs;
796 $request->_user->_prefs =& $this->_prefs;
797 //$request->setSessionVar('wiki_prefs', $this->_prefs);
798 $request->setSessionVar('wiki_user', $request->_user);
800 if ($this->_HomePagehandle)
801 $this->_HomePagehandle->set('pref', $packed);
802 return count($unpacked);
805 function mayChangePass() {
809 //The default method is getting the password from prefs.
810 // child methods obtain $stored_password from external auth.
811 function userExists() {
812 //if ($this->_HomePagehandle) return true;
813 while ($user = $this->nextClass()) {
814 if ($user->userExists()) {
818 $this = $user; // prevent endless loop. does this work on all PHP's?
819 // it just has to set the classname, what it correctly does.
824 //The default method is getting the password from prefs.
825 // child methods obtain $stored_password from external auth.
826 function checkPass($submitted_password) {
827 $stored_password = $this->_prefs->get('passwd');
828 $result = $this->_checkPass($submitted_password, $stored_password);
829 if ($result) $this->_level = WIKIAUTH_USER;
832 if (USER_AUTH_POLICY === 'strict') {
833 if ($user = $this->nextClass()) {
834 if ($user = $user->userExists())
835 return $user->checkPass($submitted_password);
838 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
839 if ($user = $this->nextClass())
840 return $user->checkPass($submitted_password);
843 return $this->_level;
846 //TODO: remove crypt() function check from config.php:396 ??
847 function _checkPass($submitted_password, $stored_password) {
848 if(!empty($submitted_password)) {
849 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
850 // Verify against encrypted password.
851 if (function_exists('crypt')) {
852 if (crypt($submitted_password, $stored_password) == $stored_password )
853 return true; // matches encrypted password
858 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
859 . _("Please set ENCRYPTED_PASSWD to false in index.php and change ADMIN_PASSWD."),
865 // Verify against cleartext password.
866 if ($submitted_password == $stored_password)
869 // Check whether we forgot to enable ENCRYPTED_PASSWD
870 if (function_exists('crypt')) {
871 if (crypt($submitted_password, $stored_password) == $stored_password) {
872 trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
883 //The default method is storing the password in prefs.
884 // Child methods (DB,File) may store in external auth also, but this
885 // must be explicitly enabled.
886 // This may be called by plugin/UserPreferences or by ->SetPreferences()
887 function changePass($submitted_password) {
888 $stored_password = $this->_prefs->get('passwd');
889 // check if authenticated
890 if ($this->isAuthenticated() and $stored_password != $submitted_password) {
891 $this->_prefs->set('passwd',$submitted_password);
892 //update the storage (session, homepage, ...)
893 $this->SetPreferences($this->_prefs);
896 //Todo: return an error msg to the caller what failed?
897 // same password or no privilege
906 function userExists() {
907 if (isWikiWord($this->_userid)) {
908 $this->_level = WIKIAUTH_BOGO;
911 $this->_level = WIKIAUTH_ANON;
916 function checkPass($submitted_password) {
917 // A BogoLoginUser requires PASSWORD_LENGTH_MINIMUM. hmm..
919 return $this->_level;
924 class _PersonalPagePassUser
927 * This class is only to simplify the auth method dispatcher.
928 * It inherits almost all all methods from _PassUser.
931 function userExists() {
932 return $this->_HomePagehandle and $this->_HomePagehandle->exists();
935 function checkPass($submitted_password) {
936 if ($this->userExists()) {
937 // A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
938 // BUT if the user already has a homepage with en empty password
939 // stored allow login but warn him to change it.
940 $stored_password = $this->_prefs->get('passwd');
941 if (empty($stored_password)) {
942 trigger_error(sprintf(
943 _("\nYou stored an empty password in your %s page.\n").
944 _("Your access permissions are only for a BogoUser.\n").
945 _("Please set your password in UserPreferences."),
946 $this->_userid), E_USER_NOTICE);
947 $this->_level = WIKIAUTH_BOGO;
948 return $this->_level;
950 if ($this->_checkPass($submitted_password, $stored_password))
951 return ($this->_level = WIKIAUTH_USER);
952 return _PassUser::checkPass($submitted_password);
954 return WIKIAUTH_ANON;
958 class _HttpAuthPassUser
962 function _HttpAuthPassUser($UserName='') {
964 _PassUser::_PassUser($UserName);
965 $this->_authmethod = 'HttpAuth';
966 if ($this->userExists())
969 return $GLOBALS['ForbiddenUser'];
972 //force http auth authorization
973 function userExists() {
975 if (empty($_SERVER['PHP_AUTH_USER']) or
976 $_SERVER['PHP_AUTH_USER'] != $this->_userid) {
977 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
978 header('HTTP/1.0 401 Unauthorized');
981 $this->_userid = $_SERVER['PHP_AUTH_USER'];
982 $this->_level = WIKIAUTH_USER;
986 function checkPass($submitted_password) {
987 return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
990 function mayChangePass() {
994 // hmm... either the server dialog or our own.
995 function PrintLoginForm (&$request, $args, $fail_message = false,
996 $seperate_page = true) {
997 header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
998 header('HTTP/1.0 401 Unauthorized');
1001 include_once('lib/Template.php');
1002 // Call update_locale in case the system's default language is not 'en'.
1003 // (We have no user pref for lang at this point yet, no one is logged in.)
1004 update_locale(DEFAULT_LANGUAGE);
1005 $userid = $this->_userid;
1007 extract($args); // fixme
1009 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
1011 $pagename = $request->getArg('pagename');
1013 $login = new Template('login', $request,
1014 compact('pagename', 'userid', 'require_level',
1015 'fail_message', 'pass_required', 'nocache'));
1016 if ($seperate_page) {
1017 $top = new Template('html', $request,
1018 array('TITLE' => _("Sign In")));
1019 return $top->printExpansion($login);
1030 * Authenticate against a database, to be able to use shared users.
1031 * internal: no different $DbAuthParams['dsn'] defined, or
1032 * external: different $DbAuthParams['dsn']
1033 * The magic is done in the symbolic SQL statements in index.php
1035 * We support only the SQL and ADODB backends.
1036 * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages,
1037 * not for auth stuff. If one would like to use e.g. dba for auth, he should
1038 * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
1039 * Flat files for auth use is handled by the auth method "File".
1041 * Preferences are handled in the parent class.
1044 var $_authselect, $_authupdate;
1046 // This can only be called from _PassUser, because the parent class
1047 // sets the auth_dbi and pref methods, before this class is initialized.
1048 function _DbPassUser($UserName='') {
1050 _PassUser::_PassUser($UserName);
1051 $this->_authmethod = 'DB';
1052 $this->getAuthDbh();
1053 $this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1055 if ($GLOBALS['DBParams']['dbtype'] == 'ADODB')
1056 return new _AdoDbPassUser($UserName);
1058 return new _PearDbPassUser($UserName);
1061 function mayChangePass() {
1062 return !isset($this->_authupdate);
1067 class _PearDbPassUser
1073 function _PearDbPassUser($UserName='') {
1074 global $DBAuthParams;
1075 if (!$this->_prefs and isa($this,"_PearDbPassUser"))
1076 _PassUser::_PassUser($UserName);
1077 $this->getAuthDbh();
1078 $this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1079 // Prepare the configured auth statements
1080 if (!empty($DBAuthParams['auth_check']) and !@is_int($this->_authselect)) {
1081 $this->_authselect = $this->_auth_dbi->prepare (
1082 str_replace(array('"$userid"','"$password"'),array('?','?'),
1083 $DBAuthParams['auth_check'])
1086 if (!empty($DBAuthParams['auth_update']) and !@is_int($this->_authupdate)) {
1087 $this->_authupdate = $this->_auth_dbi->prepare(
1088 str_replace(array('"$userid"','"$password"'),array('?','?'),
1089 $DBAuthParams['auth_update'])
1095 function getPreferences() {
1096 // override the generic slow method here for efficiency and not to
1097 // clutter the homepage metadata with prefs.
1098 _AnonUser::getPreferences();
1099 $this->getAuthDbh();
1100 if ((! $this->_prefs) && @is_int($this->_prefselect)) {
1101 $db_result = $this->_auth_dbi->execute($this->_prefselect,$this->_userid);
1102 list($prefs_blob) = $db_result->fetchRow();
1103 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1104 $this->_prefs = new UserPreferences($restored_from_db);
1105 return $this->_prefs;
1108 if ((! $this->_prefs) && $this->_HomePagehandle) {
1109 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1110 $this->_prefs = new UserPreferences($restored_from_page);
1111 return $this->_prefs;
1114 return $this->_prefs;
1117 function setPreferences($prefs, $id_only=false) {
1118 // Encode only the _prefs array of the UserPreference object
1119 $this->getAuthDbh();
1120 if (!is_object($prefs)) {
1121 $prefs = new UserPreferences($prefs);
1123 $packed = $prefs->store();
1124 $unpacked = $prefs->unpack($packed);
1125 if (count($unpacked)) {
1127 $this->_prefs = $prefs;
1128 $request->_prefs =& $this->_prefs;
1129 $request->_user->_prefs =& $this->_prefs;
1130 //$request->setSessionVar('wiki_prefs', $this->_prefs);
1131 $request->setSessionVar('wiki_user', $request->_user);
1133 if (@is_int($this->_prefupdate)) {
1134 $db_result = $this->_auth_dbi->execute($this->_prefupdate,
1135 array($packed,$this->_userid));
1137 _AnonUser::setPreferences($prefs, $id_only);
1138 $this->_HomePagehandle->set('pref', $packed);
1140 return count($unpacked);
1143 function userExists() {
1144 if (!$this->_authselect)
1145 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1147 $this->getAuthDbh();
1148 $dbh = &$this->_auth_dbi;
1149 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1150 if ($this->_auth_crypt_method == 'crypt') {
1151 $rs = $dbh->Execute($this->_authselect,$this->_userid) ;
1156 if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1157 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1159 $this->_authcheck = str_replace('"$userid"','?',
1160 $GLOBALS['DBAuthParams']['auth_user_exists']);
1161 $rs = $dbh->Execute($this->_authcheck,$this->_userid) ;
1166 if (USER_AUTH_POLICY === 'strict') {
1167 if ($user = $this->nextClass()) {
1168 return $user->userExists();
1173 function checkPass($submitted_password) {
1174 if (!@is_int($this->_authselect))
1175 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1178 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1179 $this->getAuthDbh();
1180 if ($this->_auth_crypt_method == 'crypt') {
1181 $db_result = $this->_auth_dbi->execute($this->_authselect,$this->_userid);
1182 list($stored_password) = $db_result->fetchRow();
1183 $result = $this->_checkPass($submitted_password, $stored_password);
1185 //Fixme: The prepared params get reversed somehow!
1186 //cannot find the pear bug for now
1187 $db_result = $this->_auth_dbi->execute($this->_authselect,
1188 array($submitted_password,$this->_userid));
1189 list($okay) = $db_result->fetchRow();
1190 $result = !empty($okay);
1194 $this->_level = WIKIAUTH_USER;
1196 if (USER_AUTH_POLICY === 'strict') {
1197 if ($user = $this->nextClass()) {
1198 if ($user = $user->userExists())
1199 return $user->checkPass($submitted_password);
1202 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1203 if ($user = $this->nextClass())
1204 return $user->checkPass($submitted_password);
1207 return $this->_level;
1210 function storePass($submitted_password) {
1211 if (!@is_int($this->_authupdate)) {
1213 trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1218 if ($this->_auth_crypt_method == 'crypt') {
1219 if (function_exists('crypt'))
1220 $submitted_password = crypt($submitted_password);
1222 //Fixme: The prepared params get reversed somehow!
1223 //cannot find the pear bug for now
1224 $db_result = $this->_auth_dbi->execute($this->_authupdate,
1225 array($submitted_password,$this->_userid));
1230 class _AdoDbPassUser
1236 function _AdoDbPassUser($UserName='') {
1237 global $DBAuthParams;
1238 if (!$this->_prefs and isa($this,"_AdoDbPassUser"))
1239 _PassUser::_PassUser($UserName);
1240 $this->getAuthDbh();
1241 $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1242 // Prepare the configured auth statements
1243 if (!empty($DBAuthParams['auth_check'])) {
1244 $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1245 $DBAuthParams['auth_check']);
1247 if (!empty($DBAuthParams['auth_update'])) {
1248 $this->_authupdate = str_replace(array('"$userid"','"$password"'),array("%s","%s"),
1249 $DBAuthParams['auth_update']);
1254 function getPreferences() {
1255 // override the generic slow method here for efficiency
1256 _AnonUser::getPreferences();
1257 $this->getAuthDbh();
1258 if ((! $this->_prefs) and isset($this->_prefselect)) {
1259 $dbh = & $this->_auth_dbi;
1260 $rs = $dbh->Execute(sprintf($this->_prefselect,$dbh->qstr($this->_userid)));
1264 $prefs_blob = $rs->fields['pref_blob'];
1266 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1267 $this->_prefs = new UserPreferences($restored_from_db);
1268 return $this->_prefs;
1272 if ((! $this->_prefs) && $this->_HomePagehandle) {
1273 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1274 $this->_prefs = new UserPreferences($restored_from_page);
1275 return $this->_prefs;
1278 return $this->_prefs;
1281 function setPreferences($prefs, $id_only=false) {
1282 if (!is_object($prefs)) {
1283 $prefs = new UserPreferences($prefs);
1285 $this->getAuthDbh();
1286 $packed = $prefs->store();
1287 $unpacked = $prefs->unpack($packed);
1288 if (count($unpacked)) {
1290 $this->_prefs = $prefs;
1291 $request->_prefs =& $this->_prefs;
1292 $request->_user->_prefs =& $this->_prefs;
1293 //$request->setSessionVar('wiki_prefs', $this->_prefs);
1294 $request->setSessionVar('wiki_user', $request->_user);
1296 if (isset($this->_prefupdate)) {
1297 $dbh = & $this->_auth_dbi;
1298 $db_result = $dbh->Execute(sprintf($this->_prefupdate,
1299 $dbh->qstr($packed),$dbh->qstr($this->_userid)));
1300 $db_result->Close();
1302 _AnonUser::setPreferences($prefs, $id_only);
1303 $this->_HomePagehandle->set('pref', $serialized);
1305 return count($unpacked);
1308 function userExists() {
1309 if (!$this->_authselect)
1310 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1312 $this->getAuthDbh();
1313 $dbh = &$this->_auth_dbi;
1314 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1315 if ($this->_auth_crypt_method == 'crypt') {
1316 $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1325 if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1326 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1328 $this->_authcheck = str_replace('"$userid"','%s',
1329 $GLOBALS['DBAuthParams']['auth_user_exists']);
1330 $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1339 if (USER_AUTH_POLICY === 'strict') {
1340 if ($user = $this->nextClass())
1341 return $user->userExists();
1346 function checkPass($submitted_password) {
1347 if (!isset($this->_authselect))
1348 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1350 $this->getAuthDbh();
1351 $dbh = &$this->_auth_dbi;
1352 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1353 if ($this->_auth_crypt_method == 'crypt') {
1354 $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1356 $stored_password = $rs->fields['password'];
1358 $result = $this->_checkPass($submitted_password, $stored_password);
1365 $rs = $dbh->Execute(sprintf($this->_authselect,
1366 $dbh->qstr($submitted_password),
1367 $dbh->qstr($this->_userid)));
1368 $okay = $rs->fields['ok'];
1370 $result = !empty($okay);
1374 $this->_level = WIKIAUTH_USER;
1376 if (USER_AUTH_POLICY === 'strict') {
1377 if ($user = $this->nextClass()) {
1378 if ($user = $user->userExists())
1379 return $user->checkPass($submitted_password);
1382 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1383 if ($user = $this->nextClass())
1384 return $user->checkPass($submitted_password);
1387 return $this->_level;
1390 function storePass($submitted_password) {
1391 if (!isset($this->_authupdate)) {
1393 trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1398 if ($this->_auth_crypt_method == 'crypt') {
1399 if (function_exists('crypt'))
1400 $submitted_password = crypt($submitted_password);
1402 $this->getAuthDbh();
1403 $dbh = &$this->_auth_dbi;
1404 $rs = $dbh->Execute(sprintf($this->_authupdate,
1405 $dbh->qstr($submitted_password),
1406 $dbh->qstr($this->_userid)));
1415 * Define the vars LDAP_HOST and LDAP_BASE_DN in index.php
1417 * Preferences are handled in _PassUser
1420 function checkPass($submitted_password) {
1421 $this->_authmethod = 'LDAP';
1422 $userid = $this->_userid;
1423 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1424 $r = @ldap_bind($ldap); // this is an anonymous bind
1425 // Need to set the right root search information. see ../index.php
1426 $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1427 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1428 for ($i = 0; $i < $info["count"]; $i++) {
1429 $dn = $info[$i]["dn"];
1430 // The password is still plain text.
1431 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
1432 // ldap_bind will return TRUE if everything matches
1434 $this->_level = WIKIAUTH_USER;
1435 return $this->_level;
1439 trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST),
1444 if (USER_AUTH_POLICY === 'strict') {
1445 if ($user = $this->nextClass()) {
1446 if ($user = $user->userExists())
1447 return $user->checkPass($submitted_password);
1450 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1451 if ($user = $this->nextClass())
1452 return $user->checkPass($submitted_password);
1457 function userExists() {
1458 $userid = $this->_userid;
1459 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1460 $r = @ldap_bind($ldap); // this is an anonymous bind
1461 $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1462 $info = ldap_get_entries($ldap, $sr);
1463 if ($info["count"] > 0) {
1468 trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1471 if (USER_AUTH_POLICY === 'strict') {
1472 if ($user = $this->nextClass())
1473 return $user->userExists();
1478 function mayChangePass() {
1487 * Define the var IMAP_HOST in index.php
1489 * Preferences are handled in _PassUser
1492 function checkPass($submitted_password) {
1493 $userid = $this->_userid;
1494 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1495 $userid, $submitted_password, OP_HALFOPEN );
1498 $this->_authmethod = 'IMAP';
1499 $this->_level = WIKIAUTH_USER;
1500 return $this->_level;
1502 trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1504 if (USER_AUTH_POLICY === 'strict') {
1505 if ($user = $this->nextClass()) {
1506 if ($user = $user->userExists())
1507 return $user->checkPass($submitted_password);
1510 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1511 if ($user = $this->nextClass())
1512 return $user->checkPass($submitted_password);
1517 //CHECKME: this will not be okay for the auth policy strict
1518 function userExists() {
1519 if (checkPass($this->_prefs->get('passwd')))
1522 if (USER_AUTH_POLICY === 'strict') {
1523 if ($user = $this->nextClass())
1524 return $user->userExists();
1528 function mayChangePass() {
1537 * Check users defined in a .htaccess style file
1538 * username:crypt\n...
1540 * Preferences are handled in _PassUser
1543 var $_file, $_may_change;
1545 // This can only be called from _PassUser, because the parent class
1546 // sets the pref methods, before this class is initialized.
1547 function _FilePassUser($UserName='',$file='') {
1549 _PassUser::_PassUser($UserName);
1551 // read the .htaccess style file. We use our own copy of the standard pear class.
1552 require 'lib/pear/File_Passwd.php';
1553 // if passwords may be changed we have to lock them:
1554 $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1555 if (empty($file) and defined('AUTH_USER_FILE'))
1556 $this->_file = File_Passwd(AUTH_USER_FILE, !empty($this->_may_change));
1557 elseif (!empty($file))
1558 $this->_file = File_Passwd($file, !empty($this->_may_change));
1564 function mayChangePass() {
1565 return $this->_may_change;
1568 function userExists() {
1569 if (isset($this->_file->users[$this->_userid]))
1572 if (USER_AUTH_POLICY === 'strict') {
1573 if ($user = $this->nextClass())
1574 return $user->userExists();
1578 function checkPass($submitted_password) {
1579 if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1580 $this->_authmethod = 'File';
1581 $this->_level = WIKIAUTH_USER;
1582 return $this->_level;
1585 if (USER_AUTH_POLICY === 'strict') {
1586 if ($user = $this->nextClass()) {
1587 if ($user = $user->userExists())
1588 return $user->checkPass($submitted_password);
1591 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1592 if ($user = $this->nextClass())
1593 return $user->checkPass($submitted_password);
1598 function storePass($submitted_password) {
1599 if ($this->_may_change)
1600 return $this->_file->modUser($this->_userid,$submitted_password);
1608 * Insert more auth classes here...
1614 * For security, this class should not be extended. Instead, extend
1615 * from _PassUser (think of this as unix "root").
1620 //var $_level = WIKIAUTH_ADMIN;
1622 function checkPass($submitted_password) {
1623 $stored_password = ADMIN_PASSWD;
1624 if ($this->_checkPass($submitted_password, $stored_password)) {
1625 $this->_level = WIKIAUTH_ADMIN;
1626 return $this->_level;
1628 $this->_level = WIKIAUTH_ANON;
1635 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1637 * Various data classes for the preference types,
1638 * to support get, set, sanify (range checking, ...)
1639 * update() will do the neccessary side-effects if a
1640 * setting gets changed (theme, language, ...)
1643 class _UserPreference
1647 function _UserPreference ($default_value) {
1648 $this->default_value = $default_value;
1651 function sanify ($value) {
1652 return (string)$value;
1655 function get ($name) {
1656 if (isset($this->{$name}))
1657 return $this->{$name};
1659 return $this->default_value;
1662 function getraw ($name) {
1663 if (!empty($this->{$name}))
1664 return $this->{$name};
1667 // stores the value as $this->$name, and not as $this->value (clever?)
1668 function set ($name, $value) {
1669 if ($this->get($name) != $value) {
1670 $this->update($value);
1672 if ($value != $this->default_value) {
1673 $this->{$name} = $value;
1676 unset($this->{$name});
1679 // default: no side-effects
1680 function update ($value) {
1685 class _UserPreference_numeric
1686 extends _UserPreference
1688 function _UserPreference_numeric ($default, $minval = false,
1690 $this->_UserPreference((double)$default);
1691 $this->_minval = (double)$minval;
1692 $this->_maxval = (double)$maxval;
1695 function sanify ($value) {
1696 $value = (double)$value;
1697 if ($this->_minval !== false && $value < $this->_minval)
1698 $value = $this->_minval;
1699 if ($this->_maxval !== false && $value > $this->_maxval)
1700 $value = $this->_maxval;
1705 class _UserPreference_int
1706 extends _UserPreference_numeric
1708 function _UserPreference_int ($default, $minval = false, $maxval = false) {
1709 $this->_UserPreference_numeric((int)$default, (int)$minval,
1713 function sanify ($value) {
1714 return (int)parent::sanify((int)$value);
1718 class _UserPreference_bool
1719 extends _UserPreference
1721 function _UserPreference_bool ($default = false) {
1722 $this->_UserPreference((bool)$default);
1725 function sanify ($value) {
1726 if (is_array($value)) {
1727 /* This allows for constructs like:
1729 * <input type="hidden" name="pref[boolPref][]" value="0" />
1730 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1732 * (If the checkbox is not checked, only the hidden input
1733 * gets sent. If the checkbox is sent, both inputs get
1736 foreach ($value as $val) {
1742 return (bool) $value;
1746 class _UserPreference_language
1747 extends _UserPreference
1749 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1750 $this->_UserPreference($default);
1753 // FIXME: check for valid locale
1754 function sanify ($value) {
1755 // Revert to DEFAULT_LANGUAGE if user does not specify
1756 // language in UserPreferences or chooses <system language>.
1757 if ($value == '' or empty($value))
1758 $value = DEFAULT_LANGUAGE;
1760 return (string) $value;
1764 class _UserPreference_theme
1765 extends _UserPreference
1767 function _UserPreference_theme ($default = THEME) {
1768 $this->_UserPreference($default);
1771 function sanify ($value) {
1772 if (file_exists($this->_themefile($value)))
1774 return $this->default_value;
1777 function update ($newvalue) {
1779 include_once($this->_themefile($newvalue));
1781 include_once($this->_themefile(THEME));
1784 function _themefile ($theme) {
1785 return "themes/$theme/themeinfo.php";
1789 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1794 * This object holds the $request->_prefs subobjects.
1795 * A simple packed array of non-default values get's stored as cookie,
1796 * homepage, or database, which are converted to the array of
1798 * We don't store the objects, because otherwise we will
1799 * not be able to upgrade any subobject. And it's a waste of space also.
1801 class UserPreferences
1803 function UserPreferences ($saved_prefs = false) {
1804 // userid stored too, to ensure the prefs are being loaded for
1805 // the correct (currently signing in) userid if stored in a
1809 'userid' => new _UserPreference(''),
1810 'passwd' => new _UserPreference(''),
1811 'autologin' => new _UserPreference_bool(),
1812 'email' => new _UserPreference(''),
1813 'emailVerified' => new _UserPreference_bool(),
1814 'notifyPages' => new _UserPreference(''),
1815 'theme' => new _UserPreference_theme(THEME),
1816 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1817 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1819 EDITWIDTH_MAX_COLS),
1820 'noLinkIcons' => new _UserPreference_bool(),
1821 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1822 EDITHEIGHT_MIN_ROWS,
1823 EDITHEIGHT_DEFAULT_ROWS),
1824 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1825 TIMEOFFSET_MIN_HOURS,
1826 TIMEOFFSET_MAX_HOURS),
1827 'relativeDates' => new _UserPreference_bool()
1830 if (is_array($saved_prefs)) {
1831 foreach ($saved_prefs as $name => $value)
1832 $this->set($name, $value);
1836 function _getPref ($name) {
1837 if (!isset($this->_prefs[$name])) {
1838 if ($name == 'passwd2') return false;
1839 trigger_error("$name: unknown preference", E_USER_NOTICE);
1842 return $this->_prefs[$name];
1845 // get the value or default_value of the subobject
1846 function get ($name) {
1847 if ($_pref = $this->_getPref($name))
1848 return $_pref->get($name);
1852 if (is_object($this->_prefs[$name]))
1853 return $this->_prefs[$name]->get($name);
1854 elseif (($value = $this->_getPref($name)) === false)
1856 elseif (!isset($value))
1857 return $this->_prefs[$name]->default_value;
1862 // check and set the new value in the subobject
1863 function set ($name, $value) {
1864 $pref = $this->_getPref($name);
1865 if ($pref === false)
1868 /* do it here or outside? */
1869 if ($name == 'passwd' and
1870 defined('PASSWORD_LENGTH_MINIMUM') and
1871 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1872 //TODO: How to notify the user?
1876 $newvalue = $pref->sanify($value);
1877 $pref->set($name,$newvalue);
1878 $this->_prefs[$name] = $pref;
1881 // don't set default values to save space (in cookies, db and
1884 if ($value == $pref->default_value)
1885 unset($this->_prefs[$name]);
1887 $this->_prefs[$name] = $pref;
1891 // array of objects => array of values
1894 foreach ($this->_prefs as $name => $object) {
1895 if ($value = $object->getraw($name))
1896 $prefs[] = array($name => $value);
1898 return $this->pack($prefs);
1901 // packed string or array of values => array of values
1902 function retrieve($packed) {
1903 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1904 $packed = unserialize($packed);
1905 if (!is_array($packed)) return false;
1907 foreach ($packed as $name => $packed_pref) {
1908 if (substr($packed_pref, 0, 2) == "O:") {
1909 //legacy: check if it's an old array of objects
1910 // Looks like a serialized object.
1911 // This might fail if the object definition does not exist anymore.
1912 // object with ->$name and ->default_value vars.
1913 $pref = unserialize($packed_pref);
1914 $prefs[$name] = $pref->get($name);
1916 $prefs[$name] = unserialize($packed_pref);
1924 return $this->_prefs;
1927 function pack($nonpacked) {
1928 return serialize($nonpacked);
1931 function unpack($packed) {
1934 if (substr($packed, 0, 2) == "O:") {
1935 // Looks like a serialized object
1936 return unserialize($packed);
1938 if (substr($packed, 0, 2) == "a:") {
1939 return unserialize($packed);
1941 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1947 return hash($this->_prefs);
1951 class CookieUserPreferences
1952 extends UserPreferences
1954 function CookieUserPreferences ($saved_prefs = false) {
1955 UserPreferences::UserPreferences($saved_prefs);
1959 class PageUserPreferences
1960 extends UserPreferences
1962 function PageUserPreferences ($saved_prefs = false) {
1963 UserPreferences::UserPreferences($saved_prefs);
1967 class PearDbUserPreferences
1968 extends UserPreferences
1970 function PearDbUserPreferences ($saved_prefs = false) {
1971 UserPreferences::UserPreferences($saved_prefs);
1975 class AdoDbUserPreferences
1976 extends UserPreferences
1978 function AdoDbUserPreferences ($saved_prefs = false) {
1979 UserPreferences::UserPreferences($saved_prefs);
1981 function getPreferences() {
1982 // override the generic slow method here for efficiency
1983 _AnonUser::getPreferences();
1984 $this->getAuthDbh();
1985 if ((! $this->_prefs) and isset($this->_prefselect)) {
1986 $dbh = & $this->_auth_dbi;
1987 $rs = $dbh->Execute(sprintf($this->_prefselect,$dbh->qstr($this->_userid)));
1991 $prefs_blob = $rs->fields['pref_blob'];
1993 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1994 $this->_prefs = new UserPreferences($restored_from_db);
1995 return $this->_prefs;
1999 if ((! $this->_prefs) && $this->_HomePagehandle) {
2000 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2001 $this->_prefs = new UserPreferences($restored_from_page);
2002 return $this->_prefs;
2005 return $this->_prefs;
2010 // $Log: not supported by cvs2svn $
2011 // Revision 1.21 2004/02/26 20:43:49 rurban
2012 // new HttpAuthPassUser class (forces http auth if in the auth loop)
2013 // fixed user upgrade: don't return _PassUser in the first hand.
2015 // Revision 1.20 2004/02/26 01:29:11 rurban
2016 // important fixes: endless loops in certain cases. minor rewrite
2018 // Revision 1.19 2004/02/25 17:15:17 rurban
2019 // improve stability
2021 // Revision 1.18 2004/02/24 15:20:05 rurban
2022 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
2024 // Revision 1.17 2004/02/17 12:16:42 rurban
2025 // started with changePass support. not yet used.
2027 // Revision 1.16 2004/02/15 22:23:45 rurban
2028 // oops, fixed showstopper (endless recursion)
2030 // Revision 1.15 2004/02/15 21:34:37 rurban
2031 // PageList enhanced and improved.
2032 // fixed new WikiAdmin... plugins
2033 // editpage, Theme with exp. htmlarea framework
2034 // (htmlarea yet committed, this is really questionable)
2035 // WikiUser... code with better session handling for prefs
2036 // enhanced UserPreferences (again)
2037 // RecentChanges for show_deleted: how should pages be deleted then?
2039 // Revision 1.14 2004/02/15 17:30:13 rurban
2040 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
2041 // fixed getPreferences() (esp. from sessions)
2042 // fixed setPreferences() (update and set),
2043 // fixed AdoDb DB statements,
2044 // update prefs only at UserPreferences POST (for testing)
2045 // unified db prefs methods (but in external pref classes yet)
2047 // Revision 1.13 2004/02/09 03:58:12 rurban
2048 // for now default DB_SESSION to false
2050 // * not existing perms will now query the parent, and not
2051 // return the default perm
2052 // * added pagePermissions func which returns the object per page
2053 // * added getAccessDescription
2055 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
2056 // * force init of authdbh in the 2 db classes
2058 // * fixed session handling (not triple auth request anymore)
2059 // * don't store cookie prefs with sessions
2060 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
2062 // Revision 1.12 2004/02/07 10:41:25 rurban
2063 // fixed auth from session (still double code but works)
2065 // fixed DbPassUser upgrade and policy=old
2068 // Revision 1.11 2004/02/03 09:45:39 rurban
2069 // LDAP cleanup, start of new Pref classes
2071 // Revision 1.10 2004/02/01 09:14:11 rurban
2072 // Started with Group_Ldap (not yet ready)
2073 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
2074 // fixed some configurator vars
2075 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
2076 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
2077 // USE_DB_SESSION defaults to true on SQL
2078 // changed GROUP_METHOD definition to string, not constants
2079 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
2080 // create users. (Not to be used with external databases generally, but
2081 // with the default internal user table)
2083 // fixed the IndexAsConfigProblem logic. this was flawed:
2084 // scripts which are the same virtual path defined their own lib/main call
2085 // (hmm, have to test this better, phpwiki.sf.net/demo works again)
2087 // Revision 1.9 2004/01/30 19:57:58 rurban
2088 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
2090 // Revision 1.8 2004/01/30 18:46:15 rurban
2091 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
2093 // Revision 1.7 2004/01/27 23:23:39 rurban
2094 // renamed ->Username => _userid for consistency
2095 // renamed mayCheckPassword => mayCheckPass
2096 // fixed recursion problem in WikiUserNew
2097 // fixed bogo login (but not quite 100% ready yet, password storage)
2099 // Revision 1.6 2004/01/26 09:17:49 rurban
2100 // * changed stored pref representation as before.
2101 // the array of objects is 1) bigger and 2)
2102 // less portable. If we would import packed pref
2103 // objects and the object definition was changed, PHP would fail.
2104 // This doesn't happen with an simple array of non-default values.
2105 // * use $prefs->retrieve and $prefs->store methods, where retrieve
2106 // understands the interim format of array of objects also.
2107 // * simplified $prefs->get() and fixed $prefs->set()
2108 // * added $user->_userid and class '_WikiUser' portability functions
2109 // * fixed $user object ->_level upgrading, mostly using sessions.
2110 // this fixes yesterdays problems with loosing authorization level.
2111 // * fixed WikiUserNew::checkPass to return the _level
2112 // * fixed WikiUserNew::isSignedIn
2113 // * added explodePageList to class PageList, support sortby arg
2114 // * fixed UserPreferences for WikiUserNew
2115 // * fixed WikiPlugin for empty defaults array
2116 // * UnfoldSubpages: added pagename arg, renamed pages arg,
2117 // removed sort arg, support sortby arg
2119 // Revision 1.5 2004/01/25 03:05:00 rurban
2120 // First working version, but has some problems with the current main loop.
2121 // Implemented new auth method dispatcher and policies, all the external
2122 // _PassUser classes (also for ADODB and Pear DB).
2123 // The two global funcs UserExists() and CheckPass() are probably not needed,
2124 // since the auth loop is done recursively inside the class code, upgrading
2125 // the user class within itself.
2126 // Note: When a higher user class is returned, this doesn't mean that the user
2127 // is authorized, $user->_level is still low, and only upgraded on successful
2130 // Revision 1.4 2003/12/07 19:29:48 carstenklapp
2131 // Code Housecleaning: fixed syntax errors. (php -l *.php)
2133 // Revision 1.3 2003/12/06 19:10:46 carstenklapp
2134 // Finished off logic for determining user class, including
2135 // PassUser. Removed ability of BogoUser to save prefs into a page.
2137 // Revision 1.2 2003/12/03 21:45:48 carstenklapp
2138 // Added admin user, password user, and preference classes. Added
2139 // password checking functions for users and the admin. (Now the easy
2140 // parts are nearly done).
2142 // Revision 1.1 2003/12/02 05:46:36 carstenklapp
2143 // Complete rewrite of WikiUser.php.
2145 // This should make it easier to hook in user permission groups etc. some
2146 // time in the future. Most importantly, to finally get UserPreferences
2147 // fully working properly for all classes of users: AnonUser, BogoUser,
2148 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
2149 // want a cookie or not, and to bring back optional AutoLogin with the
2150 // UserName stored in a cookie--something that was lost after PhpWiki had
2151 // dropped the default http auth login method.
2153 // Added WikiUser classes which will (almost) work together with existing
2154 // UserPreferences class. Other parts of PhpWiki need to be updated yet
2155 // before this code can be hooked up.
2161 // c-basic-offset: 4
2162 // c-hanging-comment-ender-p: nil
2163 // indent-tabs-mode: nil