2 rcs_id('$Id: WikiUser.php,v 1.38 2003-09-13 22:25:38 carstenklapp 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 'noLinkIcons' => new _UserPreference_bool(),
35 'editHeight' => new _UserPreference_int(22, 5, 80),
36 'timeOffset' => new _UserPreference_numeric(0, -26, 26),
37 'relativeDates' => new _UserPreference_bool()
46 var $_request, $_dbi, $_authdbi, $_homepage;
47 var $_authmethod = '', $_authhow = '';
52 * Populates the instance variables and calls $this->_ok()
53 * to ensure that the parameters are valid.
54 * @param mixed $userid String of username or WikiUser object.
55 * @param integer $authlevel Authorization level.
57 function WikiUser (&$request, $userid = false, $authlevel = false) {
58 $this->_request = &$request;
59 $this->_dbi = &$this->_request->getDbh();
61 if (isa($userid, 'WikiUser')) {
62 $this->_userid = $userid->_userid;
63 $this->_level = $userid->_level;
66 $this->_userid = $userid;
67 $this->_level = $authlevel;
70 // Paranoia: if state is at all inconsistent, log out...
71 $this->_userid = false;
72 $this->_level = false;
73 $this->_homepage = false;
74 $this->_authhow .= ' paranoia logout';
77 $this->_homepage = $this->_dbi->getPage($this->_userid);
82 * Get the string indicating how the user was authenticated.
84 * Get the string indicating how the user was authenticated.
85 * Does not seem to be set - jbw
86 * @return string The method of authentication.
89 return $this->_authhow;
95 * If the WikiUser object has a valid authorization level and the
96 * userid is a string returns true, else false.
97 * @return boolean If valid level and username string true, else false
100 if ((in_array($this->_level, array(WIKIAUTH_BOGO,
104 (is_string($this->_userid)))) {
111 return ( $this->isSignedIn()
113 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
116 function getAuthenticatedId() {
117 return ( $this->isAuthenticated()
119 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
122 function isSignedIn () {
123 return $this->_level >= WIKIAUTH_BOGO;
126 function isAuthenticated () {
127 return $this->_level >= WIKIAUTH_USER;
130 function isAdmin () {
131 return $this->_level == WIKIAUTH_ADMIN;
134 function hasAuthority ($require_level) {
135 return $this->_level >= $require_level;
138 function AuthCheck ($postargs) {
139 // Normalize args, and extract.
140 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
142 foreach ($keys as $key)
143 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
145 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
148 return new WikiUser($this->_request); // Log out
150 return false; // User hit cancel button.
151 elseif (!$login && !$userid)
152 return false; // Nothing to do?
154 $authlevel = $this->_pwcheck($userid, $passwd);
156 return _("Invalid password or userid.");
157 elseif ($authlevel < $require_level)
158 return _("Insufficient permissions.");
161 $user = new WikiUser($this->_request);
162 $user->_userid = $userid;
163 $user->_level = $authlevel;
167 function PrintLoginForm (&$request, $args, $fail_message = false,
168 $seperate_page = true) {
169 include_once('lib/Template.php');
173 extract($args); // fixme
175 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
177 $pagename = $request->getArg('pagename');
178 $login = new Template('login', $request,
179 compact('pagename', 'userid', 'require_level',
180 'fail_message', 'pass_required'));
181 if ($seperate_page) {
182 $top = new Template('html', $request,
183 array('TITLE' => _("Sign In")));
184 return $top->printExpansion($login);
193 function _pwcheck ($userid, $passwd) {
194 global $WikiNameRegexp;
196 if (!empty($userid) && $userid == ADMIN_USER) {
197 // $this->_authmethod = 'pagedata';
198 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
200 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
201 return WIKIAUTH_ADMIN;
202 if (!empty($passwd)) {
203 if ($passwd == ADMIN_PASSWD)
204 return WIKIAUTH_ADMIN;
206 // maybe we forgot to enable ENCRYPTED_PASSWD?
207 if ( function_exists('crypt')
208 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
209 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"),
211 return WIKIAUTH_ADMIN;
217 // HTTP Authentication
218 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
219 // if he ignored the password field, because he is already
220 // authenticated try the previously given password.
222 $passwd = $PHP_AUTH_PW;
225 // WikiDB_User DB/File Authentication from $DBAuthParams
226 // Check if we have the user. If not try other methods.
227 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
228 $request = $this->_request;
229 // first check if the user is known
230 if ($this->exists($userid)) {
231 $this->_authmethod = 'pagedata';
232 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
234 // else try others such as LDAP authentication:
235 if (ALLOW_LDAP_LOGIN && !empty($passwd)) {
236 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
237 $r = @ldap_bind($ldap); // this is an anonymous bind
238 $st_search = "uid=$userid";
239 // Need to set the right root search information. see ../index.php
240 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
242 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
243 for ($i = 0; $i < $info["count"]; $i++) {
244 $dn = $info[$i]["dn"];
245 // The password is still plain text.
246 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
247 // ldap_bind will return TRUE if everything matches
249 $this->_authmethod = 'LDAP';
250 return WIKIAUTH_USER;
254 trigger_error("Unable to connect to LDAP server "
255 . LDAP_AUTH_HOST, E_USER_WARNING);
258 // imap authentication. added by limako
259 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
260 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}",
261 $userid, $passwd, OP_HALFOPEN );
264 $this->_authmethod = 'IMAP';
265 return WIKIAUTH_USER;
270 if ( ALLOW_BOGO_LOGIN
271 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
272 $this->_authmethod = 'BOGO';
273 return WIKIAUTH_BOGO;
278 // Todo: try our WikiDB backends.
279 function getPreferences() {
280 // Restore saved preferences.
282 // I'd rather prefer only to store the UserId in the cookie or
283 // session, and get the preferences from the db or page.
284 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
285 $prefs = $this->_request->getSessionVar('wiki_prefs');
287 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
288 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
291 // before we get his prefs we should check if he is signed in
292 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
293 if ($pref = $this->_homepage->get('pref')) {
294 //trigger_error("pref=".$pref);//debugging
295 $prefs = unserialize($pref);
298 return new UserPreferences($prefs);
301 // No cookies anymore for all prefs, only the userid. PHP creates
302 // a session cookie in memory, which is much more efficient.
304 // Return the number of changed entries?
305 function setPreferences($prefs, $id_only = false) {
307 $this->_request->setSessionVar('wiki_prefs', $prefs);
308 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
309 // simple unpacked cookie
310 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
312 // We must ensure that any password is encrypted.
313 // We don't need any plaintext password.
315 if ($this->isSignedIn()) {
316 if ($this->isAdmin())
317 $prefs->set('passwd', '');
318 // already stored in index.php, and it might be
319 // plaintext! well oh well
320 if ($homepage = $this->homePage()) {
321 $homepage->set('pref', serialize($prefs->_prefs));
322 return sizeof($prefs->_prefs);
324 trigger_error("No homepage for user found. Creating one...",
326 $this->createHomepage($prefs);
327 //$homepage->set('pref', serialize($prefs->_prefs));
328 return sizeof($prefs->_prefs);
331 trigger_error("you must be signed in", E_USER_WARNING);
337 // check for homepage with user flag.
338 // can be overriden from the auth backends
340 $homepage = $this->homePage();
341 return ($this->_userid && $homepage && $homepage->get('pref'));
344 // doesn't check for existance!!! hmm.
345 // how to store metadata in not existing pages? how about versions?
346 function homePage() {
349 if (!empty($this->_homepage)) {
350 return $this->_homepage;
352 $this->_homepage = $this->_dbi->getPage($this->_userid);
353 return $this->_homepage;
357 // create user by checking his homepage
358 function createUser ($pref, $createDefaultHomepage = true) {
361 if ($createDefaultHomepage) {
362 $this->createHomepage($pref);
365 include "lib/loadsave.php";
366 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
367 'versiondata' => array('author' => $this->_userid),
368 'pagename' => $this->_userid,
369 'content' => _('CategoryHomepage'));
370 SavePage ($this->_request, $pageinfo, false, false);
372 $this->setPreferences($pref);
375 // create user and default user homepage
376 function createHomepage ($pref) {
377 $pagename = $this->_userid;
378 include "lib/loadsave.php";
380 // create default homepage:
381 // properly expanded template and the pref metadata
382 $template = Template('homepage.tmpl', $this->_request);
383 $text = $template->getExpansion();
384 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
385 'versiondata' => array('author' => $this->_userid),
386 'pagename' => $pagename,
388 SavePage ($this->_request, $pageinfo, false, false);
391 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
392 if (! isWikiPage($pagename)) {
393 $pageinfo = array('pagedata' => array(),
394 'versiondata' => array('author' => $this->_userid),
395 'pagename' => $pagename,
396 'content' => "<?plugin Calender ?>\n");
397 SavePage ($this->_request, $pageinfo, false, false);
400 // create Preferences
401 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
402 if (! isWikiPage($pagename)) {
403 $pageinfo = array('pagedata' => array(),
404 'versiondata' => array('author' => $this->_userid),
405 'pagename' => $pagename,
406 'content' => "<?plugin UserPreferences ?>\n");
407 SavePage ($this->_request, $pageinfo, false, false);
411 function tryAuthBackends() {
412 return ''; // crypt('') will never be ''
415 // Auth backends must store the crypted password where?
416 // Not in the preferences.
417 function checkPassword($passwd) {
418 $prefs = $this->getPreferences();
419 $stored_passwd = $prefs->get('passwd'); // crypted
420 if (empty($prefs->_prefs['passwd'])) // not stored in the page
421 // allow empty passwords? At least store a '*' then.
422 // try other backend. hmm.
423 $stored_passwd = $this->tryAuthBackends($this->_userid);
424 if (empty($stored_passwd)) {
425 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
426 $this->_userid), E_USER_NOTICE);
427 $prefs->set('passwd','*');
430 if ($stored_passwd == '*')
433 && crypt($passwd, $stored_passwd) == $stored_passwd )
439 function changePassword($newpasswd, $passwd2 = false) {
440 if (! $this->mayChangePassword() ) {
441 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
442 $this->_userid), E_USER_ERROR);
445 if ($passwd2 && $passwd2 != $newpasswd) {
446 trigger_error("The second password must be the same as the first to change it",
450 $prefs = $this->getPreferences();
451 //$oldpasswd = $prefs->get('passwd');
452 $prefs->set('passwd', crypt($newpasswd));
453 $this->setPreferences($prefs);
456 function mayChangePassword() {
457 // on external DBAuth maybe. on IMAP or LDAP not
458 // on internal DBAuth yes
459 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
461 if ($this->isAdmin())
463 if ($this->_authmethod == 'pagedata')
465 if ($this->_authmethod == 'authdb')
470 // create user and default user homepage
471 // FIXME: delete this, not used?
473 function createUser ($userid, $pref) {
475 $user = new WikiUser ($request, $userid);
476 $user->createUser($pref);
480 class _UserPreference
482 function _UserPreference ($default_value) {
483 $this->default_value = $default_value;
486 function sanify ($value) {
487 return (string)$value;
490 function update ($value) {
494 class _UserPreference_numeric
495 extends _UserPreference
497 function _UserPreference_numeric ($default, $minval = false,
499 $this->_UserPreference((double)$default);
500 $this->_minval = (double)$minval;
501 $this->_maxval = (double)$maxval;
504 function sanify ($value) {
505 $value = (double)$value;
506 if ($this->_minval !== false && $value < $this->_minval)
507 $value = $this->_minval;
508 if ($this->_maxval !== false && $value > $this->_maxval)
509 $value = $this->_maxval;
514 class _UserPreference_int
515 extends _UserPreference_numeric
517 function _UserPreference_int ($default, $minval = false, $maxval = false) {
518 $this->_UserPreference_numeric((int)$default, (int)$minval,
522 function sanify ($value) {
523 return (int)parent::sanify((int)$value);
527 class _UserPreference_bool
528 extends _UserPreference
530 function _UserPreference_bool ($default = false) {
531 $this->_UserPreference((bool)$default);
534 function sanify ($value) {
535 if (is_array($value)) {
536 /* This allows for constructs like:
538 * <input type="hidden" name="pref[boolPref][]" value="0" />
539 * <input type="checkbox" name="pref[boolPref][]" value="1" />
541 * (If the checkbox is not checked, only the hidden input
542 * gets sent. If the checkbox is sent, both inputs get
545 foreach ($value as $val) {
551 return (bool) $value;
555 class _UserPreference_language
556 extends _UserPreference
558 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
559 $this->_UserPreference($default);
562 function sanify ($value) {
563 // FIXME: check for valid locale
564 return (string) $value;
568 class _UserPreference_theme
569 extends _UserPreference
571 function _UserPreference_theme ($default = THEME) {
572 $this->_UserPreference($default);
575 function sanify ($value) {
576 if (file_exists($this->_themefile($value)))
578 return $this->default_value;
581 function update ($newvalue) {
583 include_once($this->_themefile($newvalue));
585 include_once($this->_themefile(THEME));
588 function _themefile ($theme) {
589 return "themes/$theme/themeinfo.php";
593 // don't save default preferences for efficiency.
594 class UserPreferences {
595 function UserPreferences ($saved_prefs = false) {
596 $this->_prefs = array();
598 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
599 foreach ($saved_prefs->_prefs as $name => $value)
600 $this->set($name, $value);
601 } elseif (is_array($saved_prefs)) {
602 foreach ($saved_prefs as $name => $value)
603 $this->set($name, $value);
607 function _getPref ($name) {
608 global $UserPreferences;
609 if (!isset($UserPreferences[$name])) {
610 if ($name == 'passwd2') return false;
611 trigger_error("$name: unknown preference", E_USER_NOTICE);
614 return $UserPreferences[$name];
617 function get ($name) {
618 if (isset($this->_prefs[$name]))
619 return $this->_prefs[$name];
620 if (!($pref = $this->_getPref($name)))
622 return $pref->default_value;
625 function set ($name, $value) {
626 if (!($pref = $this->_getPref($name)))
629 $newvalue = $pref->sanify($value);
630 $oldvalue = $this->get($name);
633 if ($newvalue != $oldvalue)
634 $pref->update($newvalue);
636 // don't set default values to save space (in cookies, db and
638 if ($value == $pref->default_value)
639 unset($this->_prefs[$name]);
641 $this->_prefs[$name] = $newvalue;
645 return hash($this->_prefs);
649 // $Log: not supported by cvs2svn $
650 // Revision 1.37 2003/02/22 20:49:55 dairiki
651 // Fixes for "Call-time pass by reference has been deprecated" errors.
653 // Revision 1.36 2003/02/21 22:50:51 dairiki
654 // Ensure that language preference is a string.
656 // Revision 1.35 2003/02/16 20:04:47 dairiki
657 // Refactor the HTTP validator generation/checking code.
659 // This also fixes a number of bugs with yesterdays validator mods.
661 // Revision 1.34 2003/02/15 02:21:54 dairiki
662 // API Change! Explicit $request argument added to contructor for WikiUser.
664 // This seemed the best way to fix a problem whereby the WikiDB
665 // was being opened twice. (Which while being merely inefficient
666 // when using an SQL backend causes hangage when using a dba backend.)
668 // Revision 1.33 2003/01/22 03:21:40 zorloc
669 // Modified WikiUser constructor to move the DB request for the homepage to
670 // the end of the logic to prevent it from being requested and then dropped.
671 // Added more phpdoc comments.
673 // Revision 1.32 2003/01/21 07:40:50 zorloc
674 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
675 // false and to return true only in the desired condition. Added phpdoc
678 // Revision 1.31 2003/01/15 05:37:20 carstenklapp
681 // Revision 1.30 2003/01/15 04:59:27 carstenklapp
682 // Bugfix: Previously stored preferences were not loading when user
683 // signed in. (Fixed... I hope.)
690 // c-hanging-comment-ender-p: nil
691 // indent-tabs-mode: nil