2 rcs_id('$Id: WikiUser.php,v 1.37 2003-02-22 20:49:55 dairiki Exp $');
4 // It is anticipated that when userid support is added to phpwiki,
5 // this object will hold much more information (e-mail,
6 // home(wiki)page, etc.) about the user.
8 // There seems to be no clean way to "log out" a user when using HTTP
9 // authentication. So we'll hack around this by storing the currently
10 // logged in username and other state information in a cookie.
12 // 2002-09-08 11:44:04 rurban
13 // Todo: Fix prefs cookie/session handling:
14 // _userid and _homepage cookie/session vars still hold the
16 // If no homepage, fallback to prefs in cookie as in 1.3.3.
18 define('WIKIAUTH_ANON', 0);
19 define('WIKIAUTH_BOGO', 1); // any valid WikiWord is enough
20 define('WIKIAUTH_USER', 2); // real auth from a database/file/server.
22 define('WIKIAUTH_ADMIN', 10);
23 define('WIKIAUTH_FORBIDDEN', 11); // Completely not allowed.
25 $UserPreferences = array(
26 'userid' => new _UserPreference(''), // really store this also?
27 'passwd' => new _UserPreference(''),
28 'email' => new _UserPreference(''),
29 'emailVerified' => new _UserPreference_bool(),
30 'notifyPages' => new _UserPreference(''),
31 'theme' => new _UserPreference_theme(THEME),
32 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
33 'editWidth' => new _UserPreference_int(80, 30, 150),
34 'editHeight' => new _UserPreference_int(22, 5, 80),
35 'timeOffset' => new _UserPreference_numeric(0, -26, 26),
36 'relativeDates' => new _UserPreference_bool()
45 var $_request, $_dbi, $_authdbi, $_homepage;
46 var $_authmethod = '', $_authhow = '';
51 * Populates the instance variables and calls $this->_ok()
52 * to ensure that the parameters are valid.
53 * @param mixed $userid String of username or WikiUser object.
54 * @param integer $authlevel Authorization level.
56 function WikiUser (&$request, $userid = false, $authlevel = false) {
57 $this->_request = &$request;
58 $this->_dbi = &$this->_request->getDbh();
60 if (isa($userid, 'WikiUser')) {
61 $this->_userid = $userid->_userid;
62 $this->_level = $userid->_level;
65 $this->_userid = $userid;
66 $this->_level = $authlevel;
69 // Paranoia: if state is at all inconsistent, log out...
70 $this->_userid = false;
71 $this->_level = false;
72 $this->_homepage = false;
73 $this->_authhow .= ' paranoia logout';
76 $this->_homepage = $this->_dbi->getPage($this->_userid);
81 * Get the string indicating how the user was authenticated.
83 * Get the string indicating how the user was authenticated.
84 * Does not seem to be set - jbw
85 * @return string The method of authentication.
88 return $this->_authhow;
94 * If the WikiUser object has a valid authorization level and the
95 * userid is a string returns true, else false.
96 * @return boolean If valid level and username string true, else false
99 if ((in_array($this->_level, array(WIKIAUTH_BOGO,
103 (is_string($this->_userid)))) {
110 return ( $this->isSignedIn()
112 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
115 function getAuthenticatedId() {
116 return ( $this->isAuthenticated()
118 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
121 function isSignedIn () {
122 return $this->_level >= WIKIAUTH_BOGO;
125 function isAuthenticated () {
126 return $this->_level >= WIKIAUTH_USER;
129 function isAdmin () {
130 return $this->_level == WIKIAUTH_ADMIN;
133 function hasAuthority ($require_level) {
134 return $this->_level >= $require_level;
137 function AuthCheck ($postargs) {
138 // Normalize args, and extract.
139 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
141 foreach ($keys as $key)
142 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
144 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
147 return new WikiUser($this->_request); // Log out
149 return false; // User hit cancel button.
150 elseif (!$login && !$userid)
151 return false; // Nothing to do?
153 $authlevel = $this->_pwcheck($userid, $passwd);
155 return _("Invalid password or userid.");
156 elseif ($authlevel < $require_level)
157 return _("Insufficient permissions.");
160 $user = new WikiUser($this->_request);
161 $user->_userid = $userid;
162 $user->_level = $authlevel;
166 function PrintLoginForm (&$request, $args, $fail_message = false,
167 $seperate_page = true) {
168 include_once('lib/Template.php');
172 extract($args); // fixme
174 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
176 $pagename = $request->getArg('pagename');
177 $login = new Template('login', $request,
178 compact('pagename', 'userid', 'require_level',
179 'fail_message', 'pass_required'));
180 if ($seperate_page) {
181 $top = new Template('html', $request,
182 array('TITLE' => _("Sign In")));
183 return $top->printExpansion($login);
192 function _pwcheck ($userid, $passwd) {
193 global $WikiNameRegexp;
195 if (!empty($userid) && $userid == ADMIN_USER) {
196 // $this->_authmethod = 'pagedata';
197 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
199 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
200 return WIKIAUTH_ADMIN;
201 if (!empty($passwd)) {
202 if ($passwd == ADMIN_PASSWD)
203 return WIKIAUTH_ADMIN;
205 // maybe we forgot to enable ENCRYPTED_PASSWD?
206 if ( function_exists('crypt')
207 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
208 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"),
210 return WIKIAUTH_ADMIN;
216 // HTTP Authentication
217 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
218 // if he ignored the password field, because he is already
219 // authenticated try the previously given password.
221 $passwd = $PHP_AUTH_PW;
224 // WikiDB_User DB/File Authentication from $DBAuthParams
225 // Check if we have the user. If not try other methods.
226 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
227 $request = $this->_request;
228 // first check if the user is known
229 if ($this->exists($userid)) {
230 $this->_authmethod = 'pagedata';
231 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
233 // else try others such as LDAP authentication:
234 if (ALLOW_LDAP_LOGIN && !empty($passwd)) {
235 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
236 $r = @ldap_bind($ldap); // this is an anonymous bind
237 $st_search = "uid=$userid";
238 // Need to set the right root search information. see ../index.php
239 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
241 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
242 for ($i = 0; $i < $info["count"]; $i++) {
243 $dn = $info[$i]["dn"];
244 // The password is still plain text.
245 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
246 // ldap_bind will return TRUE if everything matches
248 $this->_authmethod = 'LDAP';
249 return WIKIAUTH_USER;
253 trigger_error("Unable to connect to LDAP server "
254 . LDAP_AUTH_HOST, E_USER_WARNING);
257 // imap authentication. added by limako
258 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
259 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}",
260 $userid, $passwd, OP_HALFOPEN );
263 $this->_authmethod = 'IMAP';
264 return WIKIAUTH_USER;
269 if ( ALLOW_BOGO_LOGIN
270 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
271 $this->_authmethod = 'BOGO';
272 return WIKIAUTH_BOGO;
277 // Todo: try our WikiDB backends.
278 function getPreferences() {
279 // Restore saved preferences.
281 // I'd rather prefer only to store the UserId in the cookie or
282 // session, and get the preferences from the db or page.
283 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
284 $prefs = $this->_request->getSessionVar('wiki_prefs');
286 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
287 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
290 // before we get his prefs we should check if he is signed in
291 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
292 if ($pref = $this->_homepage->get('pref')) {
293 //trigger_error("pref=".$pref);//debugging
294 $prefs = unserialize($pref);
297 return new UserPreferences($prefs);
300 // No cookies anymore for all prefs, only the userid. PHP creates
301 // a session cookie in memory, which is much more efficient.
303 // Return the number of changed entries?
304 function setPreferences($prefs, $id_only = false) {
306 $this->_request->setSessionVar('wiki_prefs', $prefs);
307 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
308 // simple unpacked cookie
309 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
311 // We must ensure that any password is encrypted.
312 // We don't need any plaintext password.
314 if ($this->isSignedIn()) {
315 if ($this->isAdmin())
316 $prefs->set('passwd', '');
317 // already stored in index.php, and it might be
318 // plaintext! well oh well
319 if ($homepage = $this->homePage()) {
320 $homepage->set('pref', serialize($prefs->_prefs));
321 return sizeof($prefs->_prefs);
323 trigger_error("No homepage for user found. Creating one...",
325 $this->createHomepage($prefs);
326 //$homepage->set('pref', serialize($prefs->_prefs));
327 return sizeof($prefs->_prefs);
330 trigger_error("you must be signed in", E_USER_WARNING);
336 // check for homepage with user flag.
337 // can be overriden from the auth backends
339 $homepage = $this->homePage();
340 return ($this->_userid && $homepage && $homepage->get('pref'));
343 // doesn't check for existance!!! hmm.
344 // how to store metadata in not existing pages? how about versions?
345 function homePage() {
348 if (!empty($this->_homepage)) {
349 return $this->_homepage;
351 $this->_homepage = $this->_dbi->getPage($this->_userid);
352 return $this->_homepage;
356 // create user by checking his homepage
357 function createUser ($pref, $createDefaultHomepage = true) {
360 if ($createDefaultHomepage) {
361 $this->createHomepage($pref);
364 include "lib/loadsave.php";
365 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
366 'versiondata' => array('author' => $this->_userid),
367 'pagename' => $this->_userid,
368 'content' => _('CategoryHomepage'));
369 SavePage ($this->_request, $pageinfo, false, false);
371 $this->setPreferences($pref);
374 // create user and default user homepage
375 function createHomepage ($pref) {
376 $pagename = $this->_userid;
377 include "lib/loadsave.php";
379 // create default homepage:
380 // properly expanded template and the pref metadata
381 $template = Template('homepage.tmpl', $this->_request);
382 $text = $template->getExpansion();
383 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
384 'versiondata' => array('author' => $this->_userid),
385 'pagename' => $pagename,
387 SavePage ($this->_request, $pageinfo, false, false);
390 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
391 if (! isWikiPage($pagename)) {
392 $pageinfo = array('pagedata' => array(),
393 'versiondata' => array('author' => $this->_userid),
394 'pagename' => $pagename,
395 'content' => "<?plugin Calender ?>\n");
396 SavePage ($this->_request, $pageinfo, false, false);
399 // create Preferences
400 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
401 if (! isWikiPage($pagename)) {
402 $pageinfo = array('pagedata' => array(),
403 'versiondata' => array('author' => $this->_userid),
404 'pagename' => $pagename,
405 'content' => "<?plugin UserPreferences ?>\n");
406 SavePage ($this->_request, $pageinfo, false, false);
410 function tryAuthBackends() {
411 return ''; // crypt('') will never be ''
414 // Auth backends must store the crypted password where?
415 // Not in the preferences.
416 function checkPassword($passwd) {
417 $prefs = $this->getPreferences();
418 $stored_passwd = $prefs->get('passwd'); // crypted
419 if (empty($prefs->_prefs['passwd'])) // not stored in the page
420 // allow empty passwords? At least store a '*' then.
421 // try other backend. hmm.
422 $stored_passwd = $this->tryAuthBackends($this->_userid);
423 if (empty($stored_passwd)) {
424 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
425 $this->_userid), E_USER_NOTICE);
426 $prefs->set('passwd','*');
429 if ($stored_passwd == '*')
432 && crypt($passwd, $stored_passwd) == $stored_passwd )
438 function changePassword($newpasswd, $passwd2 = false) {
439 if (! $this->mayChangePassword() ) {
440 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
441 $this->_userid), E_USER_ERROR);
444 if ($passwd2 && $passwd2 != $newpasswd) {
445 trigger_error("The second password must be the same as the first to change it",
449 $prefs = $this->getPreferences();
450 //$oldpasswd = $prefs->get('passwd');
451 $prefs->set('passwd', crypt($newpasswd));
452 $this->setPreferences($prefs);
455 function mayChangePassword() {
456 // on external DBAuth maybe. on IMAP or LDAP not
457 // on internal DBAuth yes
458 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
460 if ($this->isAdmin())
462 if ($this->_authmethod == 'pagedata')
464 if ($this->_authmethod == 'authdb')
469 // create user and default user homepage
470 // FIXME: delete this, not used?
472 function createUser ($userid, $pref) {
474 $user = new WikiUser ($request, $userid);
475 $user->createUser($pref);
479 class _UserPreference
481 function _UserPreference ($default_value) {
482 $this->default_value = $default_value;
485 function sanify ($value) {
486 return (string)$value;
489 function update ($value) {
493 class _UserPreference_numeric
494 extends _UserPreference
496 function _UserPreference_numeric ($default, $minval = false,
498 $this->_UserPreference((double)$default);
499 $this->_minval = (double)$minval;
500 $this->_maxval = (double)$maxval;
503 function sanify ($value) {
504 $value = (double)$value;
505 if ($this->_minval !== false && $value < $this->_minval)
506 $value = $this->_minval;
507 if ($this->_maxval !== false && $value > $this->_maxval)
508 $value = $this->_maxval;
513 class _UserPreference_int
514 extends _UserPreference_numeric
516 function _UserPreference_int ($default, $minval = false, $maxval = false) {
517 $this->_UserPreference_numeric((int)$default, (int)$minval,
521 function sanify ($value) {
522 return (int)parent::sanify((int)$value);
526 class _UserPreference_bool
527 extends _UserPreference
529 function _UserPreference_bool ($default = false) {
530 $this->_UserPreference((bool)$default);
533 function sanify ($value) {
534 if (is_array($value)) {
535 /* This allows for constructs like:
537 * <input type="hidden" name="pref[boolPref][]" value="0" />
538 * <input type="checkbox" name="pref[boolPref][]" value="1" />
540 * (If the checkbox is not checked, only the hidden input
541 * gets sent. If the checkbox is sent, both inputs get
544 foreach ($value as $val) {
550 return (bool) $value;
554 class _UserPreference_language
555 extends _UserPreference
557 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
558 $this->_UserPreference($default);
561 function sanify ($value) {
562 // FIXME: check for valid locale
563 return (string) $value;
567 class _UserPreference_theme
568 extends _UserPreference
570 function _UserPreference_theme ($default = THEME) {
571 $this->_UserPreference($default);
574 function sanify ($value) {
575 if (file_exists($this->_themefile($value)))
577 return $this->default_value;
580 function update ($newvalue) {
582 include_once($this->_themefile($newvalue));
584 include_once($this->_themefile(THEME));
587 function _themefile ($theme) {
588 return "themes/$theme/themeinfo.php";
592 // don't save default preferences for efficiency.
593 class UserPreferences {
594 function UserPreferences ($saved_prefs = false) {
595 $this->_prefs = array();
597 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
598 foreach ($saved_prefs->_prefs as $name => $value)
599 $this->set($name, $value);
600 } elseif (is_array($saved_prefs)) {
601 foreach ($saved_prefs as $name => $value)
602 $this->set($name, $value);
606 function _getPref ($name) {
607 global $UserPreferences;
608 if (!isset($UserPreferences[$name])) {
609 if ($name == 'passwd2') return false;
610 trigger_error("$name: unknown preference", E_USER_NOTICE);
613 return $UserPreferences[$name];
616 function get ($name) {
617 if (isset($this->_prefs[$name]))
618 return $this->_prefs[$name];
619 if (!($pref = $this->_getPref($name)))
621 return $pref->default_value;
624 function set ($name, $value) {
625 if (!($pref = $this->_getPref($name)))
628 $newvalue = $pref->sanify($value);
629 $oldvalue = $this->get($name);
632 if ($newvalue != $oldvalue)
633 $pref->update($newvalue);
635 // don't set default values to save space (in cookies, db and
637 if ($value == $pref->default_value)
638 unset($this->_prefs[$name]);
640 $this->_prefs[$name] = $newvalue;
644 return hash($this->_prefs);
648 // $Log: not supported by cvs2svn $
649 // Revision 1.36 2003/02/21 22:50:51 dairiki
650 // Ensure that language preference is a string.
652 // Revision 1.35 2003/02/16 20:04:47 dairiki
653 // Refactor the HTTP validator generation/checking code.
655 // This also fixes a number of bugs with yesterdays validator mods.
657 // Revision 1.34 2003/02/15 02:21:54 dairiki
658 // API Change! Explicit $request argument added to contructor for WikiUser.
660 // This seemed the best way to fix a problem whereby the WikiDB
661 // was being opened twice. (Which while being merely inefficient
662 // when using an SQL backend causes hangage when using a dba backend.)
664 // Revision 1.33 2003/01/22 03:21:40 zorloc
665 // Modified WikiUser constructor to move the DB request for the homepage to
666 // the end of the logic to prevent it from being requested and then dropped.
667 // Added more phpdoc comments.
669 // Revision 1.32 2003/01/21 07:40:50 zorloc
670 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
671 // false and to return true only in the desired condition. Added phpdoc
674 // Revision 1.31 2003/01/15 05:37:20 carstenklapp
677 // Revision 1.30 2003/01/15 04:59:27 carstenklapp
678 // Bugfix: Previously stored preferences were not loading when user
679 // signed in. (Fixed... I hope.)
686 // c-hanging-comment-ender-p: nil
687 // indent-tabs-mode: nil