2 rcs_id('$Id: WikiUser.php,v 1.39 2003-10-28 21:13:46 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;
204 if (!empty($passwd)) {
205 if ($passwd == ADMIN_PASSWD)
206 return WIKIAUTH_ADMIN;
208 // maybe we forgot to enable ENCRYPTED_PASSWD?
209 if ( function_exists('crypt')
210 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
211 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"),
213 return WIKIAUTH_ADMIN;
219 // HTTP Authentication
220 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
221 // if he ignored the password field, because he is already
222 // authenticated try the previously given password.
224 $passwd = $PHP_AUTH_PW;
227 // WikiDB_User DB/File Authentication from $DBAuthParams
228 // Check if we have the user. If not try other methods.
229 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
230 $request = $this->_request;
231 // first check if the user is known
232 if ($this->exists($userid)) {
233 $this->_authmethod = 'pagedata';
234 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
236 // else try others such as LDAP authentication:
237 if (ALLOW_LDAP_LOGIN && !empty($passwd)) {
238 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
239 $r = @ldap_bind($ldap); // this is an anonymous bind
240 $st_search = "uid=$userid";
241 // Need to set the right root search information. see ../index.php
242 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
244 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
245 for ($i = 0; $i < $info["count"]; $i++) {
246 $dn = $info[$i]["dn"];
247 // The password is still plain text.
248 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
249 // ldap_bind will return TRUE if everything matches
251 $this->_authmethod = 'LDAP';
252 return WIKIAUTH_USER;
256 trigger_error("Unable to connect to LDAP server "
257 . LDAP_AUTH_HOST, E_USER_WARNING);
260 // imap authentication. added by limako
261 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
262 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}",
263 $userid, $passwd, OP_HALFOPEN );
266 $this->_authmethod = 'IMAP';
267 return WIKIAUTH_USER;
272 if ( ALLOW_BOGO_LOGIN
273 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
274 $this->_authmethod = 'BOGO';
275 return WIKIAUTH_BOGO;
280 // Todo: try our WikiDB backends.
281 function getPreferences() {
282 // Restore saved preferences.
284 // I'd rather prefer only to store the UserId in the cookie or
285 // session, and get the preferences from the db or page.
286 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
287 $prefs = $this->_request->getSessionVar('wiki_prefs');
289 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
290 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
293 // before we get his prefs we should check if he is signed in
294 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
295 if ($pref = $this->_homepage->get('pref')) {
296 //trigger_error("pref=".$pref);//debugging
297 $prefs = unserialize($pref);
300 return new UserPreferences($prefs);
303 // No cookies anymore for all prefs, only the userid. PHP creates
304 // a session cookie in memory, which is much more efficient.
306 // Return the number of changed entries?
307 function setPreferences($prefs, $id_only = false) {
309 $this->_request->setSessionVar('wiki_prefs', $prefs);
310 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
311 // simple unpacked cookie
312 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
314 // We must ensure that any password is encrypted.
315 // We don't need any plaintext password.
317 if ($this->isSignedIn()) {
318 if ($this->isAdmin())
319 $prefs->set('passwd', '');
320 // already stored in index.php, and it might be
321 // plaintext! well oh well
322 if ($homepage = $this->homePage()) {
323 $homepage->set('pref', serialize($prefs->_prefs));
324 return sizeof($prefs->_prefs);
326 trigger_error("No homepage for user found. Creating one...",
328 $this->createHomepage($prefs);
329 //$homepage->set('pref', serialize($prefs->_prefs));
330 return sizeof($prefs->_prefs);
333 trigger_error("you must be signed in", E_USER_WARNING);
339 // check for homepage with user flag.
340 // can be overriden from the auth backends
342 $homepage = $this->homePage();
343 return ($this->_userid && $homepage && $homepage->get('pref'));
346 // doesn't check for existance!!! hmm.
347 // how to store metadata in not existing pages? how about versions?
348 function homePage() {
351 if (!empty($this->_homepage)) {
352 return $this->_homepage;
354 $this->_homepage = $this->_dbi->getPage($this->_userid);
355 return $this->_homepage;
359 // create user by checking his homepage
360 function createUser ($pref, $createDefaultHomepage = true) {
363 if ($createDefaultHomepage) {
364 $this->createHomepage($pref);
367 include "lib/loadsave.php";
368 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
369 'versiondata' => array('author' => $this->_userid),
370 'pagename' => $this->_userid,
371 'content' => _('CategoryHomepage'));
372 SavePage ($this->_request, $pageinfo, false, false);
374 $this->setPreferences($pref);
377 // create user and default user homepage
378 function createHomepage ($pref) {
379 $pagename = $this->_userid;
380 include "lib/loadsave.php";
382 // create default homepage:
383 // properly expanded template and the pref metadata
384 $template = Template('homepage.tmpl', $this->_request);
385 $text = $template->getExpansion();
386 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
387 'versiondata' => array('author' => $this->_userid),
388 'pagename' => $pagename,
390 SavePage ($this->_request, $pageinfo, false, false);
393 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
394 if (! isWikiPage($pagename)) {
395 $pageinfo = array('pagedata' => array(),
396 'versiondata' => array('author' => $this->_userid),
397 'pagename' => $pagename,
398 'content' => "<?plugin Calender ?>\n");
399 SavePage ($this->_request, $pageinfo, false, false);
402 // create Preferences
403 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
404 if (! isWikiPage($pagename)) {
405 $pageinfo = array('pagedata' => array(),
406 'versiondata' => array('author' => $this->_userid),
407 'pagename' => $pagename,
408 'content' => "<?plugin UserPreferences ?>\n");
409 SavePage ($this->_request, $pageinfo, false, false);
413 function tryAuthBackends() {
414 return ''; // crypt('') will never be ''
417 // Auth backends must store the crypted password where?
418 // Not in the preferences.
419 function checkPassword($passwd) {
420 $prefs = $this->getPreferences();
421 $stored_passwd = $prefs->get('passwd'); // crypted
422 if (empty($prefs->_prefs['passwd'])) // not stored in the page
423 // allow empty passwords? At least store a '*' then.
424 // try other backend. hmm.
425 $stored_passwd = $this->tryAuthBackends($this->_userid);
426 if (empty($stored_passwd)) {
427 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
428 $this->_userid), E_USER_NOTICE);
429 $prefs->set('passwd','*');
432 if ($stored_passwd == '*')
435 && crypt($passwd, $stored_passwd) == $stored_passwd )
441 function changePassword($newpasswd, $passwd2 = false) {
442 if (! $this->mayChangePassword() ) {
443 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
444 $this->_userid), E_USER_ERROR);
447 if ($passwd2 && $passwd2 != $newpasswd) {
448 trigger_error("The second password must be the same as the first to change it",
452 $prefs = $this->getPreferences();
453 //$oldpasswd = $prefs->get('passwd');
454 $prefs->set('passwd', crypt($newpasswd));
455 $this->setPreferences($prefs);
458 function mayChangePassword() {
459 // on external DBAuth maybe. on IMAP or LDAP not
460 // on internal DBAuth yes
461 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
463 if ($this->isAdmin())
465 if ($this->_authmethod == 'pagedata')
467 if ($this->_authmethod == 'authdb')
472 // create user and default user homepage
473 // FIXME: delete this, not used?
475 function createUser ($userid, $pref) {
477 $user = new WikiUser ($request, $userid);
478 $user->createUser($pref);
482 class _UserPreference
484 function _UserPreference ($default_value) {
485 $this->default_value = $default_value;
488 function sanify ($value) {
489 return (string)$value;
492 function update ($value) {
496 class _UserPreference_numeric
497 extends _UserPreference
499 function _UserPreference_numeric ($default, $minval = false,
501 $this->_UserPreference((double)$default);
502 $this->_minval = (double)$minval;
503 $this->_maxval = (double)$maxval;
506 function sanify ($value) {
507 $value = (double)$value;
508 if ($this->_minval !== false && $value < $this->_minval)
509 $value = $this->_minval;
510 if ($this->_maxval !== false && $value > $this->_maxval)
511 $value = $this->_maxval;
516 class _UserPreference_int
517 extends _UserPreference_numeric
519 function _UserPreference_int ($default, $minval = false, $maxval = false) {
520 $this->_UserPreference_numeric((int)$default, (int)$minval,
524 function sanify ($value) {
525 return (int)parent::sanify((int)$value);
529 class _UserPreference_bool
530 extends _UserPreference
532 function _UserPreference_bool ($default = false) {
533 $this->_UserPreference((bool)$default);
536 function sanify ($value) {
537 if (is_array($value)) {
538 /* This allows for constructs like:
540 * <input type="hidden" name="pref[boolPref][]" value="0" />
541 * <input type="checkbox" name="pref[boolPref][]" value="1" />
543 * (If the checkbox is not checked, only the hidden input
544 * gets sent. If the checkbox is sent, both inputs get
547 foreach ($value as $val) {
553 return (bool) $value;
557 class _UserPreference_language
558 extends _UserPreference
560 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
561 $this->_UserPreference($default);
564 function sanify ($value) {
565 // FIXME: check for valid locale
566 return (string) $value;
570 class _UserPreference_theme
571 extends _UserPreference
573 function _UserPreference_theme ($default = THEME) {
574 $this->_UserPreference($default);
577 function sanify ($value) {
578 if (file_exists($this->_themefile($value)))
580 return $this->default_value;
583 function update ($newvalue) {
585 include_once($this->_themefile($newvalue));
587 include_once($this->_themefile(THEME));
590 function _themefile ($theme) {
591 return "themes/$theme/themeinfo.php";
595 // don't save default preferences for efficiency.
596 class UserPreferences {
597 function UserPreferences ($saved_prefs = false) {
598 $this->_prefs = array();
600 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
601 foreach ($saved_prefs->_prefs as $name => $value)
602 $this->set($name, $value);
603 } elseif (is_array($saved_prefs)) {
604 foreach ($saved_prefs as $name => $value)
605 $this->set($name, $value);
609 function _getPref ($name) {
610 global $UserPreferences;
611 if (!isset($UserPreferences[$name])) {
612 if ($name == 'passwd2') return false;
613 trigger_error("$name: unknown preference", E_USER_NOTICE);
616 return $UserPreferences[$name];
619 function get ($name) {
620 if (isset($this->_prefs[$name]))
621 return $this->_prefs[$name];
622 if (!($pref = $this->_getPref($name)))
624 return $pref->default_value;
627 function set ($name, $value) {
628 if (!($pref = $this->_getPref($name)))
631 $newvalue = $pref->sanify($value);
632 $oldvalue = $this->get($name);
635 if ($newvalue != $oldvalue)
636 $pref->update($newvalue);
638 // don't set default values to save space (in cookies, db and
640 if ($value == $pref->default_value)
641 unset($this->_prefs[$name]);
643 $this->_prefs[$name] = $newvalue;
647 return hash($this->_prefs);
651 // $Log: not supported by cvs2svn $
652 // Revision 1.38 2003/09/13 22:25:38 carstenklapp
653 // Hook for new user preference 'noLinkIcons'.
655 // Revision 1.37 2003/02/22 20:49:55 dairiki
656 // Fixes for "Call-time pass by reference has been deprecated" errors.
658 // Revision 1.36 2003/02/21 22:50:51 dairiki
659 // Ensure that language preference is a string.
661 // Revision 1.35 2003/02/16 20:04:47 dairiki
662 // Refactor the HTTP validator generation/checking code.
664 // This also fixes a number of bugs with yesterdays validator mods.
666 // Revision 1.34 2003/02/15 02:21:54 dairiki
667 // API Change! Explicit $request argument added to contructor for WikiUser.
669 // This seemed the best way to fix a problem whereby the WikiDB
670 // was being opened twice. (Which while being merely inefficient
671 // when using an SQL backend causes hangage when using a dba backend.)
673 // Revision 1.33 2003/01/22 03:21:40 zorloc
674 // Modified WikiUser constructor to move the DB request for the homepage to
675 // the end of the logic to prevent it from being requested and then dropped.
676 // Added more phpdoc comments.
678 // Revision 1.32 2003/01/21 07:40:50 zorloc
679 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
680 // false and to return true only in the desired condition. Added phpdoc
683 // Revision 1.31 2003/01/15 05:37:20 carstenklapp
686 // Revision 1.30 2003/01/15 04:59:27 carstenklapp
687 // Bugfix: Previously stored preferences were not loading when user
688 // signed in. (Fixed... I hope.)
695 // c-hanging-comment-ender-p: nil
696 // indent-tabs-mode: nil