2 rcs_id('$Id: WikiUserNew.php,v 1.18 2004-02-24 15:20:05 rurban Exp $');
4 // This is a complete OOP rewrite of the old WikiUser code with various
5 // configurable external authentification methods.
7 // There's only one entry point, the function WikiUser which returns
8 // a WikiUser object, which contains the user's preferences.
9 // This object might get upgraded during the login step and later also.
10 // There exist three preferences storage methods: cookie, homepage and db,
11 // and multiple password checking methods.
12 // See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if
13 // ALLOW_USER_PASSWORDS is defined.
15 // Each user object must define the two preferences methods
16 // getPreferences(), setPreferences(),
17 // and the following 1-3 auth methods
18 // checkPass() must be defined by all classes,
19 // userExists() only if USER_AUTH_POLICY'=='strict'
20 // mayChangePass() only if the password is storable.
21 // storePass() only if the password is storable.
23 // WikiUser() given no name, returns an _AnonUser (anonymous user)
24 // object, who may or may not have a cookie.
25 // However, if the there's a cookie with the userid or a session,
26 // the user is upgraded to the matching user object.
27 // Given a user name, returns a _BogoUser object, who may or may not
28 // have a cookie and/or PersonalPage, a _PassUser object or an
31 // Takes care of passwords, all preference loading/storing in the
32 // user's page and any cookies. lib/main.php will query the user object to
33 // verify the password as appropriate.
35 // Notes by 2004-01-25 03:43:45 rurban
36 // Currently this library doesn't look good enough with
37 // the current configuration options.
38 // Test it by defining ENABLE_USER_NEW in index.php
39 // The problem is that the previous code was written to do auth checks
40 // only on action != browse, and this code requires a good enough
41 // user object even for browse. I don't think that this is a good idea.
42 // 1) Now a ForbiddenUser is returned instead of false.
43 // 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
44 // but may browse. Now with ALLOW_ANON_USER = false he may not browse,
45 // which is needed to disable browse PagePermissions. Hmm...
46 // I added now ALLOW_ANON_EDIT = true to makes things clear.
47 // (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
49 * Fixme: 2004-02-06 15:42:24 rurban
50 * dbprefs edit with anonuser fails.
53 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
54 define('WIKIAUTH_ANON', 0); // Not signed in.
55 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
56 define('WIKIAUTH_USER', 2); // Bogo user with a password.
57 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
59 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
60 if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
62 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
63 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
64 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
66 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
67 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
68 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
70 define('TIMEOFFSET_MIN_HOURS', -26);
71 define('TIMEOFFSET_MAX_HOURS', 26);
72 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
75 * There are be the following constants in index.php to
76 * establish login parameters:
78 * ALLOW_ANON_USER default true
79 * ALLOW_ANON_EDIT default true
80 * ALLOW_BOGO_LOGIN default true
81 * ALLOW_USER_PASSWORDS default true
82 * PASSWORD_LENGTH_MINIMUM default 6?
84 * To require user passwords for editing:
85 * ALLOW_ANON_USER = true
86 * ALLOW_ANON_EDIT = false (before named REQUIRE_SIGNIN_BEFORE_EDIT)
87 * ALLOW_BOGO_LOGIN = false
88 * ALLOW_USER_PASSWORDS = true
90 * To establish a COMPLETELY private wiki, such as an internal
92 * ALLOW_ANON_USER = false
93 * (and probably require user passwords as described above). In this
94 * case the user will be prompted to login immediately upon accessing
97 * There are other possible combinations, but the typical wiki (such
98 * as PhpWiki.sf.net) would usually just leave all four enabled.
102 // The last object in the row is the bad guy...
103 if (!is_array($USER_AUTH_ORDER))
104 $USER_AUTH_ORDER = array("Forbidden");
106 $USER_AUTH_ORDER[] = "Forbidden";
108 // Local convenience functions.
109 function _isAnonUserAllowed() {
110 return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
112 function _isBogoUserAllowed() {
113 return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
115 function _isUserPasswordsAllowed() {
116 return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
120 // Possibly upgrade userobject functions.
121 function _determineAdminUserOrOtherUser($UserName) {
122 // Sanity check. User name is a condition of the definition of the
123 // _AdminUser, _BogoUser and _passuser.
125 return $GLOBALS['ForbiddenUser'];
127 if ($UserName == ADMIN_USER)
128 return new _AdminUser($UserName);
130 return _determineBogoUserOrPassUser($UserName);
133 function _determineBogoUserOrPassUser($UserName) {
134 global $ForbiddenUser;
136 // Sanity check. User name is a condition of the definition of
137 // _BogoUser and _PassUser.
139 return $ForbiddenUser;
141 // Check for password and possibly upgrade user object.
142 $_BogoUser = new _BogoUser($UserName);
143 if (_isUserPasswordsAllowed()) {
144 if (/*$has_password =*/ $_BogoUser->_prefs->get('passwd'))
145 return new _PassUser($UserName);
146 else { // PassUsers override BogoUsers if they exist
147 $_PassUser = new _PassUser($UserName);
148 if ($_PassUser->userExists())
152 // User has no password.
153 if (_isBogoUserAllowed())
156 // Passwords are not allowed, and Bogo is disallowed too. (Only
157 // the admin can sign in).
158 return $ForbiddenUser;
162 * Primary WikiUser function, called by main.php.
164 * This determines the user's type and returns an appropriate user
165 * object. main.php then querys the resultant object for password
166 * validity as necessary.
168 * If an _AnonUser object is returned, the user may only browse pages
169 * (and save prefs in a cookie).
171 * To disable access but provide prefs the global $ForbiddenUser class
172 * is returned. (was previously false)
175 function WikiUser ($UserName = '') {
176 global $ForbiddenUser;
178 //TODO: Check sessionvar for username & save username into
179 //sessionvar (may be more appropriate to do this in main.php).
181 $ForbiddenUser = new _ForbiddenUser($UserName);
182 // Found a user name.
183 return _determineAdminUserOrOtherUser($UserName);
185 elseif (!empty($_SESSION['userid'])) {
186 // Found a user name.
187 $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
188 return _determineAdminUserOrOtherUser($_SESSION['userid']);
191 // Check for autologin pref in cookie and possibly upgrade
192 // user object to another type.
193 $_AnonUser = new _AnonUser();
194 if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
195 // Found a user name.
196 $ForbiddenUser = new _ForbiddenUser($UserName);
197 return _determineAdminUserOrOtherUser($UserName);
200 $ForbiddenUser = new _ForbiddenUser();
201 if (_isAnonUserAllowed())
203 return $ForbiddenUser; // User must sign in to browse pages.
205 return $ForbiddenUser; // User must sign in with a password.
208 trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
209 . "Unexpectedly, an appropriate user class could not be determined.");
210 return $ForbiddenUser; // Failsafe.
214 function WikiUserClassname() {
218 function UpgradeUser ($olduser, $user) {
219 if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
220 // populate the upgraded class $olduser with the values from the new user object
221 foreach (get_object_vars($user) as $k => $v) {
222 if (!empty($v)) $olduser->$k = $v;
224 $GLOBALS['request']->_user = $olduser;
231 function UserExists ($UserName) {
233 if (!($user = $request->getUser()))
234 $user = WikiUser($UserName);
237 if ($user->userExists($UserName)) {
238 $request->_user = $user;
241 if (isa($user,'_BogoUser'))
242 $user = new _PassUser($UserName);
243 while ($user = $user->nextClass()) {
244 return $user->userExists($UserName);
246 $request->_user = $GLOBALS['ForbiddenUser'];
250 function CheckPass ($UserName, $Password) {
252 if (!($user = $request->getUser()))
253 $user = WikiUser($UserName);
256 if ($user->checkPass($Password)) {
257 $request->_user = $user;
260 if (isa($user,'_BogoUser'))
261 $user = new _PassUser($UserName);
262 while ($user = $user->nextClass()) {
263 return $user->checkPass($Password);
265 $request->_user = $GLOBALS['ForbiddenUser'];
270 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
272 // Base WikiUser class.
277 var $_level = WIKIAUTH_FORBIDDEN;
279 var $_HomePagehandle = false;
282 function _WikiUser($UserName = '') {
284 $this->_userid = $UserName;
286 $this->_HomePagehandle = $this->hasHomePage();
288 $this->getPreferences();
291 function UserName() {
292 if (!empty($this->_userid))
293 return $this->_userid;
296 function getPreferences() {
297 trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
298 . "New subclasses of _WikiUser must override this function.");
302 function setPreferences($prefs, $id_only) {
303 trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
304 . "New subclasses of _WikiUser must override this function.");
308 function userExists() {
309 return $this->hasHomePage();
312 function checkPass($submitted_password) {
313 // By definition, an undefined user class cannot sign in.
314 trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
315 . "New subclasses of _WikiUser must override this function.");
319 // returns page_handle to user's home page or false if none
320 function hasHomePage() {
321 if ($this->_userid) {
322 if ($this->_HomePagehandle) {
323 return $this->_HomePagehandle;
326 // check db again (maybe someone else created it since
329 $this->_HomePagehandle = $request->getPage($this->_userid);
330 return $this->_HomePagehandle;
337 function nextAuthMethod() {
338 if (! $this->_current_method) {
339 if (get_class($this) != '_passuser') {
340 $this->_current_method = substr(get_class($this),1,-8);
342 $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
343 $this->_current_index = -1;
345 $this->_current_index++;
346 if ($this->_current_index >= count($this->_auth_methods))
348 $this->_current_method = $this->_auth_methods[$this->_current_index];
349 return $this->_current_method;
352 // upgrade the user object
353 function nextClass() {
354 if ($method = $this->nextAuthMethod()) {
355 $class = "_".$method."PassUser";
356 if ($user = new $class($this->_userid)) {
357 // prevent from endless recursion.
358 //$user->_current_method = $this->_current_method;
359 //$user->_current_index = $this->_current_index;
360 $user = UpgradeUser($user, $this);
366 function PrintLoginForm (&$request, $args, $fail_message = false,
367 $seperate_page = true) {
368 include_once('lib/Template.php');
369 // Call update_locale in case the system's default language is not 'en'.
370 // (We have no user pref for lang at this point yet, no one is logged in.)
371 update_locale(DEFAULT_LANGUAGE);
372 $userid = $this->_userid;
374 extract($args); // fixme
376 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
378 $pagename = $request->getArg('pagename');
380 $login = new Template('login', $request,
381 compact('pagename', 'userid', 'require_level',
382 'fail_message', 'pass_required', 'nocache'));
383 if ($seperate_page) {
384 $top = new Template('html', $request,
385 array('TITLE' => _("Sign In")));
386 return $top->printExpansion($login);
392 // signed in but probably not password checked
393 function isSignedIn() {
394 return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
397 function isAuthenticated () {
398 //return isa($this,'_PassUser');
399 //return isa($this,'_BogoUser') || isa($this,'_PassUser');
400 return $this->_level >= WIKIAUTH_BOGO; // hmm.
403 function isAdmin () {
404 return $this->_level == WIKIAUTH_ADMIN;
408 return ( $this->UserName()
410 : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
413 function getAuthenticatedId() {
414 return ( $this->isAuthenticated()
416 : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
419 function hasAuthority ($require_level) {
420 return $this->_level >= $require_level;
423 function AuthCheck ($postargs) {
424 // Normalize args, and extract.
425 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
427 foreach ($keys as $key)
428 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
430 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
432 if ($logout) { // Log out
433 $GLOBALS['request']->_user = new _AnonUser();
434 return $GLOBALS['request']->_user;
436 return false; // User hit cancel button.
437 elseif (!$login && !$userid)
438 return false; // Nothing to do?
440 $authlevel = checkPass($userid,$passwd);
442 return _("Invalid password or userid.");
443 elseif ($authlevel < $require_level)
444 return _("Insufficient permissions.");
447 $user = $GLOBALS['request']->_user;
448 $user->_userid = $userid;
449 $user->_level = $authlevel;
458 var $_level = WIKIAUTH_ANON;
460 // Anon only gets to load and save prefs in a cookie, that's it.
461 function getPreferences() {
464 if (empty($this->_prefs))
465 $this->_prefs = new UserPreferences;
466 $UserName = $this->UserName();
467 if ($cookie = $request->getCookieVar(WIKI_NAME)) {
468 if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
469 trigger_error(_("Format of UserPreferences cookie not recognised.") . " "
470 . _("Default preferences will be used."),
473 // TODO: try reading userid from old PhpWiki cookie
474 // formats, then delete old cookie from browser!
477 // try old cookie format.
478 //$cookie = $request->getCookieVar('WIKI_ID');
482 * Only keep the cookie if it matches the UserName who is
483 * signing in or if this really is an Anon login (no
484 * username). (Remember, _BogoUser and higher inherit this
487 if (! $UserName || $UserName == $unboxedcookie['userid']) {
488 $this->_prefs = new UserPreferences($unboxedcookie);
489 $this->_userid = $unboxedcookie['userid'];
492 // initializeTheme() needs at least an empty object
493 if (! $this->_prefs )
494 $this->_prefs = new UserPreferences;
495 return $this->_prefs;
498 function setPreferences($prefs, $id_only=false) {
499 // Allow for multiple wikis in same domain. Encode only the
500 // _prefs array of the UserPreference object. Ideally the
501 // prefs array should just be imploded into a single string or
502 // something so it is completely human readable by the end
503 // user. In that case stricter error checking will be needed
504 // when loading the cookie.
505 if (!is_object($prefs)) {
506 $prefs = new UserPreferences($prefs);
508 $packed = $prefs->store();
509 $unpacked = $prefs->unpack($packed);
510 if (!empty($unpacked)) { // check how many are different from the default_value
511 setcookie(WIKI_NAME, $packed,
512 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
514 if (count($unpacked)) {
516 $this->_prefs = $prefs;
517 $request->_prefs =& $this->_prefs;
518 $request->_user->_prefs =& $this->_prefs;
519 //$request->setSessionVar('wiki_prefs', $this->_prefs);
520 $request->setSessionVar('wiki_user', $request->_user);
522 return count($unpacked);
525 function userExists() {
529 function checkPass($submitted_password) {
530 // By definition, the _AnonUser does not HAVE a password
531 // (compared to _BogoUser, who has an EMPTY password).
532 trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
533 . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
534 . "New subclasses of _WikiUser must override this function.");
543 var $_level = WIKIAUTH_FORBIDDEN;
545 function checkPass($submitted_password) {
549 function userExists() {
550 if ($this->_HomePagehandle) return true;
554 class _ForbiddenPassUser
555 extends _ForbiddenUser
563 * Do NOT extend _BogoUser to other classes, for checkPass()
564 * security. (In case of defects in code logic of the new class!)
569 function userExists() {
570 if (isWikiWord($this->_userid)) {
571 $this->_level = WIKIAUTH_BOGO;
574 $this->_level = WIKIAUTH_ANON;
579 function checkPass($submitted_password) {
580 // By definition, BogoUser has an empty password.
582 return $this->_level;
589 * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
591 * The classes for all subsequent auth methods extend from
593 * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
594 * the three auth method policies first-only, strict and stacked
595 * and the two methods for prefs: homepage or database,
596 * if $DBAuthParams['pref_select'] is defined.
598 * Default is PersonalPage auth and prefs.
600 * TODO: password changing
601 * TODO: email verification
604 var $_auth_dbi, $_prefmethod, $_prefselect, $_prefupdate;
605 var $_current_method, $_current_index;
607 // check and prepare the auth and pref methods only once
608 function _PassUser($UserName = '') {
609 global $DBAuthParams, $DBParams;
612 $this->_userid = $UserName;
613 $this->_HomePagehandle = $this->hasHomePage();
615 // Check the configured Prefs methods
616 if ( !empty($DBAuthParams['pref_select']) ) {
617 if ( $DBParams['dbtype'] == 'SQL' and !@is_int($this->_prefselect)) {
618 $this->_prefmethod = 'SQL'; // really pear db
620 // preparate the SELECT statement
621 $this->_prefselect = $this->_auth_dbi->prepare(
622 str_replace('"$userid"','?',$DBAuthParams['pref_select'])
625 if ( $DBParams['dbtype'] == 'ADODB' and !isset($this->_prefselect)) {
626 $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
628 // preparate the SELECT statement
629 $this->_prefselect = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
632 unset($this->_prefselect);
634 if ( !empty($DBAuthParams['pref_update']) and
635 $DBParams['dbtype'] == 'SQL' and
636 !@is_int($this->_prefupdate)) {
637 $this->_prefmethod = 'SQL';
639 $this->_prefupdate = $this->_auth_dbi->prepare(
640 str_replace(array('"$userid"','"$pref_blob"'),array('?','?'),$DBAuthParams['pref_update'])
643 if ( !empty($DBAuthParams['pref_update']) and
644 $DBParams['dbtype'] == 'ADODB' and
645 !isset($this->_prefupdate)) {
646 $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
648 // preparate the SELECT statement
649 $this->_prefupdate = str_replace(array('"$userid"','"$pref_blob"'),array('%s','%s'),
650 $DBAuthParams['pref_update']);
652 $this->getPreferences();
654 // Upgrade to the next parent _PassUser class. Avoid recursion.
655 if ( get_class($this) === '_passuser' ) { // hopefully PHP will keep this lowercase
656 //auth policy: Check the order of the configured auth methods
657 // 1. first-only: Upgrade the class here in the constructor
658 // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as in the previous PhpWiki releases (slow)
659 // 3. strict: upgrade the class after checking the user existance in userExists()
660 // 4. stacked: upgrade the class after the password verification in checkPass()
661 // Methods: PersonalPage, HTTP_AUTH, DB, LDAP, IMAP, File
662 if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
663 if (defined('USER_AUTH_POLICY')) {
664 // policy 1: only pre-define one method for all users
665 if (USER_AUTH_POLICY === 'first-only') {
666 if ($user = $this->nextClass())
669 return $GLOBALS['ForbiddenUser'];
671 // use the default behaviour from the previous versions:
672 elseif (USER_AUTH_POLICY === 'old') {
673 // default: try to be smart
674 if (!empty($GLOBALS['PHP_AUTH_USER'])) {
675 return new _HttpAuthPassUser($UserName);
676 } elseif (!empty($DBAuthParams['auth_check']) and ($DBAuthParams['auth_dsn'] or $GLOBALS ['DBParams']['dsn'])) {
677 return new _DbPassUser($UserName);
678 } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
679 return new _LDAPPassUser($UserName);
680 } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
681 return new _IMAPPassUser($UserName);
682 } elseif (defined('AUTH_USER_FILE')) {
683 return new _FilePassUser($UserName);
685 return new _PersonalPagePassUser($UserName);
689 // else use the page methods defined in _PassUser.
695 function getAuthDbh () {
696 global $request, $DBParams, $DBAuthParams;
698 // session restauration doesn't re-connect to the database automatically, so dirty it here.
699 if (($DBParams['dbtype'] == 'SQL') and isset($this->_auth_dbi) and empty($this->_auth_dbi->connection))
700 unset($this->_auth_dbi);
701 if (($DBParams['dbtype'] == 'ADODB') and isset($this->_auth_dbi) and empty($this->_auth_dbi->_connectionID))
702 unset($this->_auth_dbi);
704 if (empty($this->_auth_dbi)) {
705 if (empty($DBAuthParams['auth_dsn'])) {
706 if ($DBParams['dbtype'] == 'SQL')
707 $dbh = $request->getDbh(); // use phpwiki database
711 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
712 $dbh = $request->getDbh(); // same phpwiki database
713 else // use another external database handle. needs PHP >= 4.1
714 $dbh = WikiDB::open($DBAuthParams);
716 $this->_auth_dbi =& $dbh->_backend->_dbh;
718 return $this->_auth_dbi;
721 function prepare ($stmt, $variables) {
722 global $DBParams, $request;
723 // preparate the SELECT statement, for ADODB and PearDB (MDB not)
725 $place = ($DBParams['dbtype'] == 'ADODB') ? '%s' : '?';
726 if (is_array($variables)) {
728 foreach ($variables as $v) { $new[] = $place; }
732 // probably prefix table names if in same database
733 if (!empty($DBParams['prefix']) and
734 $this->_auth_dbi === $request->_dbi->_backend->_dbh) {
735 if (!stristr($DBParams['prefix'],$stmt)) {
736 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
737 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php: $stmt",
739 $stmt = str_replace(array(" user "," pref "," member "),
740 array(" ".$prefix."user ",
741 " ".$prefix."prefs ",
742 " ".$prefix."member "),$stmt);
745 return $this->_auth_dbi->prepare(str_replace($variables,$new,$stmt));
748 function getPreferences() {
749 if ($this->_prefmethod == 'ADODB') {
750 _AdoDbPassUser::_AdoDbPassUser();
751 return _AdoDbPassUser::getPreferences();
752 } elseif ($this->_prefmethod == 'SQL') {
753 _PearDbPassUser::_PearDbPassUser();
754 return _PearDbPassUser::getPreferences();
757 // We don't necessarily have to read the cookie first. Since
758 // the user has a password, the prefs stored in the homepage
759 // cannot be arbitrarily altered by other Bogo users.
760 _AnonUser::getPreferences();
761 // User may have deleted cookie, retrieve from his
762 // PersonalPage if there is one.
763 if (! $this->_prefs && $this->_HomePagehandle) {
764 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
765 $this->_prefs = new UserPreferences($restored_from_page);
766 return $this->_prefs;
769 return $this->_prefs;
772 function setPreferences($prefs, $id_only=false) {
773 if ($this->_prefmethod == 'ADODB') {
774 _AdoDbPassUser::_AdoDbPassUser();
775 return _AdoDbPassUser::setPreferences($prefs, $id_only);
777 elseif ($this->_prefmethod == 'SQL') {
778 _PearDbPassUser::_PearDbPassUser();
779 return _PearDbPassUser::setPreferences($prefs, $id_only);
782 _AnonUser::setPreferences($prefs, $id_only);
783 // Encode only the _prefs array of the UserPreference object
784 if (!is_object($prefs)) {
785 $prefs = new UserPreferences($prefs);
787 $packed = $prefs->store();
788 $unpacked = $prefs->unpack($packed);
789 if (count($unpacked)) {
791 $this->_prefs = $prefs;
792 $request->_prefs =& $this->_prefs;
793 $request->_user->_prefs =& $this->_prefs;
794 //$request->setSessionVar('wiki_prefs', $this->_prefs);
795 $request->setSessionVar('wiki_user', $request->_user);
797 $this->_HomePagehandle->set('pref', $packed);
798 return count($unpacked);
801 function mayChangePass() {
805 //The default method is getting the password from prefs.
806 // child methods obtain $stored_password from external auth.
807 function userExists() {
808 //if ($this->_HomePagehandle) return true;
809 while ($user = $this->nextClass()) {
810 if ($user->userExists())
816 //The default method is getting the password from prefs.
817 // child methods obtain $stored_password from external auth.
818 function checkPass($submitted_password) {
819 $stored_password = $this->_prefs->get('passwd');
820 $result = $this->_checkPass($submitted_password, $stored_password);
821 if ($result) $this->_level = WIKIAUTH_USER;
824 if (USER_AUTH_POLICY === 'strict') {
825 if ($user = $this->nextClass()) {
826 if ($user = $user->userExists())
827 return $user->checkPass($submitted_password);
830 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
831 if ($user = $this->nextClass())
832 return $user->checkPass($submitted_password);
835 return $this->_level;
838 //TODO: remove crypt() function check from config.php:396 ??
839 function _checkPass($submitted_password, $stored_password) {
840 if(!empty($submitted_password)) {
841 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
842 // Verify against encrypted password.
843 if (function_exists('crypt')) {
844 if (crypt($submitted_password, $stored_password) == $stored_password )
845 return true; // matches encrypted password
850 trigger_error(_("The crypt function is not available in this version of PHP.") . " "
851 . _("Please set ENCRYPTED_PASSWD to false in index.php and change ADMIN_PASSWD."),
857 // Verify against cleartext password.
858 if ($submitted_password == $stored_password)
861 // Check whether we forgot to enable ENCRYPTED_PASSWD
862 if (function_exists('crypt')) {
863 if (crypt($submitted_password, $stored_password) == $stored_password) {
864 trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
875 //The default method is storing the password in prefs.
876 // Child methods (DB,File) may store in external auth also, but this
877 // must be explicitly enabled.
878 // This may be called by plugin/UserPreferences or by ->SetPreferences()
879 function changePass($submitted_password) {
880 $stored_password = $this->_prefs->get('passwd');
881 // check if authenticated
882 if ($this->isAuthenticated() and $stored_password != $submitted_password) {
883 $this->_prefs->set('passwd',$submitted_password);
884 //update the storage (session, homepage, ...)
885 $this->SetPreferences($this->_prefs);
888 //Todo: return an error msg to the caller what failed?
889 // same password or no privilege
898 function userExists() {
899 if (isWikiWord($this->_userid)) {
900 $this->_level = WIKIAUTH_BOGO;
903 $this->_level = WIKIAUTH_ANON;
908 function checkPass($submitted_password) {
909 // A BogoLoginUser requires PASSWORD_LENGTH_MINIMUM. hmm..
910 if ($this->userExists())
911 return $this->_level;
916 class _PersonalPagePassUser
919 * This class is only to simplify the auth method dispatcher.
920 * It inherits all methods from _PassUser.
929 * Authenticate against a database, to be able to use shared users.
930 * internal: no different $DbAuthParams['dsn'] defined, or
931 * external: different $DbAuthParams['dsn']
932 * The magic is done in the symbolic SQL statements in index.php
934 * We support only the SQL and ADODB backends.
935 * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages,
936 * not for auth stuff. If one would like to use e.g. dba for auth, he should
937 * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
938 * Flat files for auth use is handled by the auth method "File".
940 * Preferences are handled in the parent class.
943 var $_authselect, $_authupdate;
945 // This can only be called from _PassUser, because the parent class
946 // sets the auth_dbi and pref methods, before this class is initialized.
947 function _DbPassUser($UserName='') {
949 _PassUser::_PassUser($UserName);
950 $this->_authmethod = 'DB';
952 $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
954 if ($GLOBALS['DBParams']['dbtype'] == 'ADODB')
955 return new _AdoDbPassUser($UserName);
957 return new _PearDbPassUser($UserName);
960 function mayChangePass() {
961 return !isset($this->_authupdate);
966 class _PearDbPassUser
972 function _PearDbPassUser($UserName='') {
973 global $DBAuthParams;
974 if (!$this->_prefs and isa($this,"_PearDbPassUser"))
975 _PassUser::_PassUser($UserName);
977 $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
978 // Prepare the configured auth statements
979 if (!empty($DBAuthParams['auth_check']) and !@is_int($this->_authselect)) {
980 $this->_authselect = $this->_auth_dbi->prepare (
981 str_replace(array('"$userid"','"$password"'),array('?','?'),
982 $DBAuthParams['auth_check'])
985 if (!empty($DBAuthParams['auth_update']) and !@is_int($this->_authupdate)) {
986 $this->_authupdate = $this->_auth_dbi->prepare(
987 str_replace(array('"$userid"','"$password"'),array('?','?'),
988 $DBAuthParams['auth_update'])
994 function getPreferences() {
995 // override the generic slow method here for efficiency and not to
996 // clutter the homepage metadata with prefs.
997 _AnonUser::getPreferences();
999 if ((! $this->_prefs) && @is_int($this->_prefselect)) {
1000 $db_result = $this->_auth_dbi->execute($this->_prefselect,$this->_userid);
1001 list($prefs_blob) = $db_result->fetchRow();
1002 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1003 $this->_prefs = new UserPreferences($restored_from_db);
1004 return $this->_prefs;
1007 if ((! $this->_prefs) && $this->_HomePagehandle) {
1008 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1009 $this->_prefs = new UserPreferences($restored_from_page);
1010 return $this->_prefs;
1013 return $this->_prefs;
1016 function setPreferences($prefs, $id_only=false) {
1017 // Encode only the _prefs array of the UserPreference object
1018 $this->getAuthDbh();
1019 if (!is_object($prefs)) {
1020 $prefs = new UserPreferences($prefs);
1022 $packed = $prefs->store();
1023 $unpacked = $prefs->unpack($packed);
1024 if (count($unpacked)) {
1026 $this->_prefs = $prefs;
1027 $request->_prefs =& $this->_prefs;
1028 $request->_user->_prefs =& $this->_prefs;
1029 //$request->setSessionVar('wiki_prefs', $this->_prefs);
1030 $request->setSessionVar('wiki_user', $request->_user);
1032 if (@is_int($this->_prefupdate)) {
1033 $db_result = $this->_auth_dbi->execute($this->_prefupdate,
1034 array($packed,$this->_userid));
1036 _AnonUser::setPreferences($prefs, $id_only);
1037 $this->_HomePagehandle->set('pref', $packed);
1039 return count($unpacked);
1042 function userExists() {
1043 if (!$this->_authselect)
1044 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1046 $this->getAuthDbh();
1047 $dbh = &$this->_auth_dbi;
1048 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1049 if ($this->_auth_crypt_method == 'crypt') {
1050 $rs = $dbh->Execute($this->_authselect,$this->_userid) ;
1055 if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1056 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1058 $this->_authcheck = str_replace('"$userid"','?',
1059 $GLOBALS['DBAuthParams']['auth_user_exists']);
1060 $rs = $dbh->Execute($this->_authcheck,$this->_userid) ;
1065 if (USER_AUTH_POLICY === 'strict') {
1066 if ($user = $this->nextClass()) {
1067 return $user->userExists();
1072 function checkPass($submitted_password) {
1073 if (!@is_int($this->_authselect))
1074 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1077 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1078 $this->getAuthDbh();
1079 if ($this->_auth_crypt_method == 'crypt') {
1080 $db_result = $this->_auth_dbi->execute($this->_authselect,$this->_userid);
1081 list($stored_password) = $db_result->fetchRow();
1082 $result = $this->_checkPass($submitted_password, $stored_password);
1084 //Fixme: The prepared params get reversed somehow!
1085 //cannot find the pear bug for now
1086 $db_result = $this->_auth_dbi->execute($this->_authselect,
1087 array($submitted_password,$this->_userid));
1088 list($okay) = $db_result->fetchRow();
1089 $result = !empty($okay);
1093 $this->_level = WIKIAUTH_USER;
1095 if (USER_AUTH_POLICY === 'strict') {
1096 if ($user = $this->nextClass()) {
1097 if ($user = $user->userExists())
1098 return $user->checkPass($submitted_password);
1101 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1102 if ($user = $this->nextClass())
1103 return $user->checkPass($submitted_password);
1106 return $this->_level;
1109 function storePass($submitted_password) {
1110 if (!@is_int($this->_authupdate)) {
1112 trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1117 if ($this->_auth_crypt_method == 'crypt') {
1118 if (function_exists('crypt'))
1119 $submitted_password = crypt($submitted_password);
1121 //Fixme: The prepared params get reversed somehow!
1122 //cannot find the pear bug for now
1123 $db_result = $this->_auth_dbi->execute($this->_authupdate,
1124 array($submitted_password,$this->_userid));
1129 class _AdoDbPassUser
1135 function _AdoDbPassUser($UserName='') {
1136 global $DBAuthParams;
1137 if (!$this->_prefs and isa($this,"_AdoDbPassUser"))
1138 _PassUser::_PassUser($UserName);
1139 $this->getAuthDbh();
1140 $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1141 // Prepare the configured auth statements
1142 if (!empty($DBAuthParams['auth_check'])) {
1143 $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1144 $DBAuthParams['auth_check']);
1146 if (!empty($DBAuthParams['auth_update'])) {
1147 $this->_authupdate = str_replace(array('"$userid"','"$password"'),array("%s","%s"),
1148 $DBAuthParams['auth_update']);
1153 function getPreferences() {
1154 // override the generic slow method here for efficiency
1155 _AnonUser::getPreferences();
1156 $this->getAuthDbh();
1157 if ((! $this->_prefs) and isset($this->_prefselect)) {
1158 $dbh = & $this->_auth_dbi;
1159 $rs = $dbh->Execute(sprintf($this->_prefselect,$dbh->qstr($this->_userid)));
1163 $prefs_blob = $rs->fields['pref_blob'];
1165 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1166 $this->_prefs = new UserPreferences($restored_from_db);
1167 return $this->_prefs;
1171 if ((! $this->_prefs) && $this->_HomePagehandle) {
1172 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1173 $this->_prefs = new UserPreferences($restored_from_page);
1174 return $this->_prefs;
1177 return $this->_prefs;
1180 function setPreferences($prefs, $id_only=false) {
1181 if (!is_object($prefs)) {
1182 $prefs = new UserPreferences($prefs);
1184 $this->getAuthDbh();
1185 $packed = $prefs->store();
1186 $unpacked = $prefs->unpack($packed);
1187 if (count($unpacked)) {
1189 $this->_prefs = $prefs;
1190 $request->_prefs =& $this->_prefs;
1191 $request->_user->_prefs =& $this->_prefs;
1192 //$request->setSessionVar('wiki_prefs', $this->_prefs);
1193 $request->setSessionVar('wiki_user', $request->_user);
1195 if (isset($this->_prefupdate)) {
1196 $dbh = & $this->_auth_dbi;
1197 $db_result = $dbh->Execute(sprintf($this->_prefupdate,
1198 $dbh->qstr($packed),$dbh->qstr($this->_userid)));
1199 $db_result->Close();
1201 _AnonUser::setPreferences($prefs, $id_only);
1202 $this->_HomePagehandle->set('pref', $serialized);
1204 return count($unpacked);
1207 function userExists() {
1208 if (!$this->_authselect)
1209 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1211 $this->getAuthDbh();
1212 $dbh = &$this->_auth_dbi;
1213 //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1214 if ($this->_auth_crypt_method == 'crypt') {
1215 $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1224 if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1225 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1227 $this->_authcheck = str_replace('"$userid"','%s',
1228 $GLOBALS['DBAuthParams']['auth_user_exists']);
1229 $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1238 if (USER_AUTH_POLICY === 'strict') {
1239 if ($user = $this->nextClass())
1240 return $user->userExists();
1245 function checkPass($submitted_password) {
1246 if (!isset($this->_authselect))
1247 trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1249 $this->getAuthDbh();
1250 $dbh = &$this->_auth_dbi;
1251 //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set
1252 if ($this->_auth_crypt_method == 'crypt') {
1253 $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1255 $stored_password = $rs->fields['password'];
1257 $result = $this->_checkPass($submitted_password, $stored_password);
1264 $rs = $dbh->Execute(sprintf($this->_authselect,
1265 $dbh->qstr($submitted_password),
1266 $dbh->qstr($this->_userid)));
1267 $okay = $rs->fields['ok'];
1269 $result = !empty($okay);
1273 $this->_level = WIKIAUTH_USER;
1275 if (USER_AUTH_POLICY === 'strict') {
1276 if ($user = $this->nextClass()) {
1277 if ($user = $user->userExists())
1278 return $user->checkPass($submitted_password);
1281 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1282 if ($user = $this->nextClass())
1283 return $user->checkPass($submitted_password);
1286 return $this->_level;
1289 function storePass($submitted_password) {
1290 if (!isset($this->_authupdate)) {
1292 trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1297 if ($this->_auth_crypt_method == 'crypt') {
1298 if (function_exists('crypt'))
1299 $submitted_password = crypt($submitted_password);
1301 $this->getAuthDbh();
1302 $dbh = &$this->_auth_dbi;
1303 $rs = $dbh->Execute(sprintf($this->_authupdate,
1304 $dbh->qstr($submitted_password),
1305 $dbh->qstr($this->_userid)));
1314 * Define the vars LDAP_HOST and LDAP_BASE_DN in index.php
1316 * Preferences are handled in _PassUser
1319 function checkPass($submitted_password) {
1320 $this->_authmethod = 'LDAP';
1321 $userid = $this->_userid;
1322 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1323 $r = @ldap_bind($ldap); // this is an anonymous bind
1324 // Need to set the right root search information. see ../index.php
1325 $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1326 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1327 for ($i = 0; $i < $info["count"]; $i++) {
1328 $dn = $info[$i]["dn"];
1329 // The password is still plain text.
1330 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
1331 // ldap_bind will return TRUE if everything matches
1333 $this->_level = WIKIAUTH_USER;
1334 return $this->_level;
1338 trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST),
1343 if (USER_AUTH_POLICY === 'strict') {
1344 if ($user = $this->nextClass()) {
1345 if ($user = $user->userExists())
1346 return $user->checkPass($submitted_password);
1349 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1350 if ($user = $this->nextClass())
1351 return $user->checkPass($submitted_password);
1356 function userExists() {
1357 $userid = $this->_userid;
1358 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1359 $r = @ldap_bind($ldap); // this is an anonymous bind
1360 $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1361 $info = ldap_get_entries($ldap, $sr);
1362 if ($info["count"] > 0) {
1367 trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1370 if (USER_AUTH_POLICY === 'strict') {
1371 if ($user = $this->nextClass())
1372 return $user->userExists();
1377 function mayChangePass() {
1386 * Define the var IMAP_HOST in index.php
1388 * Preferences are handled in _PassUser
1391 function checkPass($submitted_password) {
1392 $userid = $this->_userid;
1393 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1394 $userid, $submitted_password, OP_HALFOPEN );
1397 $this->_authmethod = 'IMAP';
1398 $this->_level = WIKIAUTH_USER;
1399 return $this->_level;
1401 trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1403 if (USER_AUTH_POLICY === 'strict') {
1404 if ($user = $this->nextClass()) {
1405 if ($user = $user->userExists())
1406 return $user->checkPass($submitted_password);
1409 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1410 if ($user = $this->nextClass())
1411 return $user->checkPass($submitted_password);
1416 //CHECKME: this will not be okay for the auth policy strict
1417 function userExists() {
1418 if (checkPass($this->_prefs->get('passwd')))
1421 if (USER_AUTH_POLICY === 'strict') {
1422 if ($user = $this->nextClass())
1423 return $user->userExists();
1427 function mayChangePass() {
1436 * Check users defined in a .htaccess style file
1437 * username:crypt\n...
1439 * Preferences are handled in _PassUser
1442 var $_file, $_may_change;
1444 // This can only be called from _PassUser, because the parent class
1445 // sets the pref methods, before this class is initialized.
1446 function _FilePassUser($UserName='',$file='') {
1448 _PassUser::_PassUser($UserName);
1450 // read the .htaccess style file. We use our own copy of the standard pear class.
1451 require 'lib/pear/File_Passwd.php';
1452 // if passwords may be changed we have to lock them:
1453 $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1454 if (empty($file) and defined('AUTH_USER_FILE'))
1455 $this->_file = File_Passwd(AUTH_USER_FILE, !empty($this->_may_change));
1456 elseif (!empty($file))
1457 $this->_file = File_Passwd($file, !empty($this->_may_change));
1463 function mayChangePass() {
1464 return $this->_may_change;
1467 function userExists() {
1468 if (isset($this->_file->users[$this->_userid]))
1471 if (USER_AUTH_POLICY === 'strict') {
1472 if ($user = $this->nextClass())
1473 return $user->userExists();
1477 function checkPass($submitted_password) {
1478 if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1479 $this->_authmethod = 'File';
1480 $this->_level = WIKIAUTH_USER;
1481 return $this->_level;
1484 if (USER_AUTH_POLICY === 'strict') {
1485 if ($user = $this->nextClass()) {
1486 if ($user = $user->userExists())
1487 return $user->checkPass($submitted_password);
1490 if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1491 if ($user = $this->nextClass())
1492 return $user->checkPass($submitted_password);
1497 function storePass($submitted_password) {
1498 if ($this->_may_change)
1499 return $this->_file->modUser($this->_userid,$submitted_password);
1507 * Insert more auth classes here...
1513 * For security, this class should not be extended. Instead, extend
1514 * from _PassUser (think of this as unix "root").
1519 //var $_level = WIKIAUTH_ADMIN;
1521 function checkPass($submitted_password) {
1522 $stored_password = ADMIN_PASSWD;
1523 if ($this->_checkPass($submitted_password, $stored_password)) {
1524 $this->_level = WIKIAUTH_ADMIN;
1525 return $this->_level;
1527 $this->_level = WIKIAUTH_ANON;
1534 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1536 * Various data classes for the preference types,
1537 * to support get, set, sanify (range checking, ...)
1538 * update() will do the neccessary side-effects if a
1539 * setting gets changed (theme, language, ...)
1542 class _UserPreference
1546 function _UserPreference ($default_value) {
1547 $this->default_value = $default_value;
1550 function sanify ($value) {
1551 return (string)$value;
1554 function get ($name) {
1555 if (isset($this->{$name}))
1556 return $this->{$name};
1558 return $this->default_value;
1561 function getraw ($name) {
1562 if (!empty($this->{$name}))
1563 return $this->{$name};
1566 // stores the value as $this->$name, and not as $this->value (clever?)
1567 function set ($name, $value) {
1568 if ($this->get($name) != $value) {
1569 $this->update($value);
1571 if ($value != $this->default_value) {
1572 $this->{$name} = $value;
1575 unset($this->{$name});
1578 // default: no side-effects
1579 function update ($value) {
1584 class _UserPreference_numeric
1585 extends _UserPreference
1587 function _UserPreference_numeric ($default, $minval = false,
1589 $this->_UserPreference((double)$default);
1590 $this->_minval = (double)$minval;
1591 $this->_maxval = (double)$maxval;
1594 function sanify ($value) {
1595 $value = (double)$value;
1596 if ($this->_minval !== false && $value < $this->_minval)
1597 $value = $this->_minval;
1598 if ($this->_maxval !== false && $value > $this->_maxval)
1599 $value = $this->_maxval;
1604 class _UserPreference_int
1605 extends _UserPreference_numeric
1607 function _UserPreference_int ($default, $minval = false, $maxval = false) {
1608 $this->_UserPreference_numeric((int)$default, (int)$minval,
1612 function sanify ($value) {
1613 return (int)parent::sanify((int)$value);
1617 class _UserPreference_bool
1618 extends _UserPreference
1620 function _UserPreference_bool ($default = false) {
1621 $this->_UserPreference((bool)$default);
1624 function sanify ($value) {
1625 if (is_array($value)) {
1626 /* This allows for constructs like:
1628 * <input type="hidden" name="pref[boolPref][]" value="0" />
1629 * <input type="checkbox" name="pref[boolPref][]" value="1" />
1631 * (If the checkbox is not checked, only the hidden input
1632 * gets sent. If the checkbox is sent, both inputs get
1635 foreach ($value as $val) {
1641 return (bool) $value;
1645 class _UserPreference_language
1646 extends _UserPreference
1648 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1649 $this->_UserPreference($default);
1652 // FIXME: check for valid locale
1653 function sanify ($value) {
1654 // Revert to DEFAULT_LANGUAGE if user does not specify
1655 // language in UserPreferences or chooses <system language>.
1656 if ($value == '' or empty($value))
1657 $value = DEFAULT_LANGUAGE;
1659 return (string) $value;
1663 class _UserPreference_theme
1664 extends _UserPreference
1666 function _UserPreference_theme ($default = THEME) {
1667 $this->_UserPreference($default);
1670 function sanify ($value) {
1671 if (file_exists($this->_themefile($value)))
1673 return $this->default_value;
1676 function update ($newvalue) {
1678 include_once($this->_themefile($newvalue));
1680 include_once($this->_themefile(THEME));
1683 function _themefile ($theme) {
1684 return "themes/$theme/themeinfo.php";
1688 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1693 * This object holds the $request->_prefs subobjects.
1694 * A simple packed array of non-default values get's stored as cookie,
1695 * homepage, or database, which are converted to the array of
1697 * We don't store the objects, because otherwise we will
1698 * not be able to upgrade any subobject. And it's a waste of space also.
1700 class UserPreferences
1702 function UserPreferences ($saved_prefs = false) {
1703 // userid stored too, to ensure the prefs are being loaded for
1704 // the correct (currently signing in) userid if stored in a
1708 'userid' => new _UserPreference(''),
1709 'passwd' => new _UserPreference(''),
1710 'autologin' => new _UserPreference_bool(),
1711 'email' => new _UserPreference(''),
1712 'emailVerified' => new _UserPreference_bool(),
1713 'notifyPages' => new _UserPreference(''),
1714 'theme' => new _UserPreference_theme(THEME),
1715 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1716 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1718 EDITWIDTH_MAX_COLS),
1719 'noLinkIcons' => new _UserPreference_bool(),
1720 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1721 EDITHEIGHT_MIN_ROWS,
1722 EDITHEIGHT_DEFAULT_ROWS),
1723 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1724 TIMEOFFSET_MIN_HOURS,
1725 TIMEOFFSET_MAX_HOURS),
1726 'relativeDates' => new _UserPreference_bool()
1729 if (is_array($saved_prefs)) {
1730 foreach ($saved_prefs as $name => $value)
1731 $this->set($name, $value);
1735 function _getPref ($name) {
1736 if (!isset($this->_prefs[$name])) {
1737 if ($name == 'passwd2') return false;
1738 trigger_error("$name: unknown preference", E_USER_NOTICE);
1741 return $this->_prefs[$name];
1744 // get the value or default_value of the subobject
1745 function get ($name) {
1746 if ($_pref = $this->_getPref($name))
1747 return $_pref->get($name);
1751 if (is_object($this->_prefs[$name]))
1752 return $this->_prefs[$name]->get($name);
1753 elseif (($value = $this->_getPref($name)) === false)
1755 elseif (!isset($value))
1756 return $this->_prefs[$name]->default_value;
1761 // check and set the new value in the subobject
1762 function set ($name, $value) {
1763 $pref = $this->_getPref($name);
1764 if ($pref === false)
1767 /* do it here or outside? */
1768 if ($name == 'passwd' and
1769 defined('PASSWORD_LENGTH_MINIMUM') and
1770 strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1771 //TODO: How to notify the user?
1775 $newvalue = $pref->sanify($value);
1776 $pref->set($name,$newvalue);
1777 $this->_prefs[$name] = $pref;
1780 // don't set default values to save space (in cookies, db and
1783 if ($value == $pref->default_value)
1784 unset($this->_prefs[$name]);
1786 $this->_prefs[$name] = $pref;
1790 // array of objects => array of values
1793 foreach ($this->_prefs as $name => $object) {
1794 if ($value = $object->getraw($name))
1795 $prefs[] = array($name => $value);
1797 return $this->pack($prefs);
1800 // packed string or array of values => array of values
1801 function retrieve($packed) {
1802 if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1803 $packed = unserialize($packed);
1804 if (!is_array($packed)) return false;
1806 foreach ($packed as $name => $packed_pref) {
1807 if (substr($packed_pref, 0, 2) == "O:") {
1808 //legacy: check if it's an old array of objects
1809 // Looks like a serialized object.
1810 // This might fail if the object definition does not exist anymore.
1811 // object with ->$name and ->default_value vars.
1812 $pref = unserialize($packed_pref);
1813 $prefs[$name] = $pref->get($name);
1815 $prefs[$name] = unserialize($packed_pref);
1823 return $this->_prefs;
1826 function pack($nonpacked) {
1827 return serialize($nonpacked);
1830 function unpack($packed) {
1833 if (substr($packed, 0, 2) == "O:") {
1834 // Looks like a serialized object
1835 return unserialize($packed);
1837 if (substr($packed, 0, 2) == "a:") {
1838 return unserialize($packed);
1840 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1846 return hash($this->_prefs);
1850 class CookieUserPreferences
1851 extends UserPreferences
1853 function CookieUserPreferences ($saved_prefs = false) {
1854 UserPreferences::UserPreferences($saved_prefs);
1858 class PageUserPreferences
1859 extends UserPreferences
1861 function PageUserPreferences ($saved_prefs = false) {
1862 UserPreferences::UserPreferences($saved_prefs);
1866 class PearDbUserPreferences
1867 extends UserPreferences
1869 function PearDbUserPreferences ($saved_prefs = false) {
1870 UserPreferences::UserPreferences($saved_prefs);
1874 class AdoDbUserPreferences
1875 extends UserPreferences
1877 function AdoDbUserPreferences ($saved_prefs = false) {
1878 UserPreferences::UserPreferences($saved_prefs);
1880 function getPreferences() {
1881 // override the generic slow method here for efficiency
1882 _AnonUser::getPreferences();
1883 $this->getAuthDbh();
1884 if ((! $this->_prefs) and isset($this->_prefselect)) {
1885 $dbh = & $this->_auth_dbi;
1886 $rs = $dbh->Execute(sprintf($this->_prefselect,$dbh->qstr($this->_userid)));
1890 $prefs_blob = $rs->fields['pref_blob'];
1892 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1893 $this->_prefs = new UserPreferences($restored_from_db);
1894 return $this->_prefs;
1898 if ((! $this->_prefs) && $this->_HomePagehandle) {
1899 if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1900 $this->_prefs = new UserPreferences($restored_from_page);
1901 return $this->_prefs;
1904 return $this->_prefs;
1909 // $Log: not supported by cvs2svn $
1910 // Revision 1.17 2004/02/17 12:16:42 rurban
1911 // started with changePass support. not yet used.
1913 // Revision 1.16 2004/02/15 22:23:45 rurban
1914 // oops, fixed showstopper (endless recursion)
1916 // Revision 1.15 2004/02/15 21:34:37 rurban
1917 // PageList enhanced and improved.
1918 // fixed new WikiAdmin... plugins
1919 // editpage, Theme with exp. htmlarea framework
1920 // (htmlarea yet committed, this is really questionable)
1921 // WikiUser... code with better session handling for prefs
1922 // enhanced UserPreferences (again)
1923 // RecentChanges for show_deleted: how should pages be deleted then?
1925 // Revision 1.14 2004/02/15 17:30:13 rurban
1926 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
1927 // fixed getPreferences() (esp. from sessions)
1928 // fixed setPreferences() (update and set),
1929 // fixed AdoDb DB statements,
1930 // update prefs only at UserPreferences POST (for testing)
1931 // unified db prefs methods (but in external pref classes yet)
1933 // Revision 1.13 2004/02/09 03:58:12 rurban
1934 // for now default DB_SESSION to false
1936 // * not existing perms will now query the parent, and not
1937 // return the default perm
1938 // * added pagePermissions func which returns the object per page
1939 // * added getAccessDescription
1941 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1942 // * force init of authdbh in the 2 db classes
1944 // * fixed session handling (not triple auth request anymore)
1945 // * don't store cookie prefs with sessions
1946 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1948 // Revision 1.12 2004/02/07 10:41:25 rurban
1949 // fixed auth from session (still double code but works)
1951 // fixed DbPassUser upgrade and policy=old
1954 // Revision 1.11 2004/02/03 09:45:39 rurban
1955 // LDAP cleanup, start of new Pref classes
1957 // Revision 1.10 2004/02/01 09:14:11 rurban
1958 // Started with Group_Ldap (not yet ready)
1959 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
1960 // fixed some configurator vars
1961 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
1962 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
1963 // USE_DB_SESSION defaults to true on SQL
1964 // changed GROUP_METHOD definition to string, not constants
1965 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
1966 // create users. (Not to be used with external databases generally, but
1967 // with the default internal user table)
1969 // fixed the IndexAsConfigProblem logic. this was flawed:
1970 // scripts which are the same virtual path defined their own lib/main call
1971 // (hmm, have to test this better, phpwiki.sf.net/demo works again)
1973 // Revision 1.9 2004/01/30 19:57:58 rurban
1974 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1976 // Revision 1.8 2004/01/30 18:46:15 rurban
1977 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
1979 // Revision 1.7 2004/01/27 23:23:39 rurban
1980 // renamed ->Username => _userid for consistency
1981 // renamed mayCheckPassword => mayCheckPass
1982 // fixed recursion problem in WikiUserNew
1983 // fixed bogo login (but not quite 100% ready yet, password storage)
1985 // Revision 1.6 2004/01/26 09:17:49 rurban
1986 // * changed stored pref representation as before.
1987 // the array of objects is 1) bigger and 2)
1988 // less portable. If we would import packed pref
1989 // objects and the object definition was changed, PHP would fail.
1990 // This doesn't happen with an simple array of non-default values.
1991 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1992 // understands the interim format of array of objects also.
1993 // * simplified $prefs->get() and fixed $prefs->set()
1994 // * added $user->_userid and class '_WikiUser' portability functions
1995 // * fixed $user object ->_level upgrading, mostly using sessions.
1996 // this fixes yesterdays problems with loosing authorization level.
1997 // * fixed WikiUserNew::checkPass to return the _level
1998 // * fixed WikiUserNew::isSignedIn
1999 // * added explodePageList to class PageList, support sortby arg
2000 // * fixed UserPreferences for WikiUserNew
2001 // * fixed WikiPlugin for empty defaults array
2002 // * UnfoldSubpages: added pagename arg, renamed pages arg,
2003 // removed sort arg, support sortby arg
2005 // Revision 1.5 2004/01/25 03:05:00 rurban
2006 // First working version, but has some problems with the current main loop.
2007 // Implemented new auth method dispatcher and policies, all the external
2008 // _PassUser classes (also for ADODB and Pear DB).
2009 // The two global funcs UserExists() and CheckPass() are probably not needed,
2010 // since the auth loop is done recursively inside the class code, upgrading
2011 // the user class within itself.
2012 // Note: When a higher user class is returned, this doesn't mean that the user
2013 // is authorized, $user->_level is still low, and only upgraded on successful
2016 // Revision 1.4 2003/12/07 19:29:48 carstenklapp
2017 // Code Housecleaning: fixed syntax errors. (php -l *.php)
2019 // Revision 1.3 2003/12/06 19:10:46 carstenklapp
2020 // Finished off logic for determining user class, including
2021 // PassUser. Removed ability of BogoUser to save prefs into a page.
2023 // Revision 1.2 2003/12/03 21:45:48 carstenklapp
2024 // Added admin user, password user, and preference classes. Added
2025 // password checking functions for users and the admin. (Now the easy
2026 // parts are nearly done).
2028 // Revision 1.1 2003/12/02 05:46:36 carstenklapp
2029 // Complete rewrite of WikiUser.php.
2031 // This should make it easier to hook in user permission groups etc. some
2032 // time in the future. Most importantly, to finally get UserPreferences
2033 // fully working properly for all classes of users: AnonUser, BogoUser,
2034 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
2035 // want a cookie or not, and to bring back optional AutoLogin with the
2036 // UserName stored in a cookie--something that was lost after PhpWiki had
2037 // dropped the default http auth login method.
2039 // Added WikiUser classes which will (almost) work together with existing
2040 // UserPreferences class. Other parts of PhpWiki need to be updated yet
2041 // before this code can be hooked up.
2047 // c-basic-offset: 4
2048 // c-hanging-comment-ender-p: nil
2049 // indent-tabs-mode: nil