2 rcs_id('$Id: WikiUser.php,v 1.43 2003-12-04 19:33:30 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');
170 // Call update_locale in case the system's default language is not 'en'.
171 // (We have no user pref for lang at this point yet, no one is logged in.)
172 update_locale(DEFAULT_LANGUAGE);
175 extract($args); // fixme
177 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
179 $pagename = $request->getArg('pagename');
180 $login = new Template('login', $request,
181 compact('pagename', 'userid', 'require_level',
182 'fail_message', 'pass_required'));
183 if ($seperate_page) {
184 $top = new Template('html', $request,
185 array('TITLE' => _("Sign In")));
186 return $top->printExpansion($login);
195 function _pwcheck ($userid, $passwd) {
196 global $WikiNameRegexp;
198 if (!empty($userid) && $userid == ADMIN_USER) {
199 // $this->_authmethod = 'pagedata';
200 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
202 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
203 return WIKIAUTH_ADMIN;
206 if (!empty($passwd)) {
207 if ($passwd == ADMIN_PASSWD)
208 return WIKIAUTH_ADMIN;
210 // maybe we forgot to enable ENCRYPTED_PASSWD?
211 if ( function_exists('crypt')
212 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
213 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"),
215 return WIKIAUTH_ADMIN;
221 // HTTP Authentication
222 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
223 // if he ignored the password field, because he is already
224 // authenticated try the previously given password.
226 $passwd = $PHP_AUTH_PW;
229 // WikiDB_User DB/File Authentication from $DBAuthParams
230 // Check if we have the user. If not try other methods.
231 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
232 $request = $this->_request;
233 // first check if the user is known
234 if ($this->exists($userid)) {
235 $this->_authmethod = 'pagedata';
236 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
238 // else try others such as LDAP authentication:
239 if (ALLOW_LDAP_LOGIN && !empty($passwd)) {
240 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
241 $r = @ldap_bind($ldap); // this is an anonymous bind
242 $st_search = "uid=$userid";
243 // Need to set the right root search information. see ../index.php
244 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
246 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
247 for ($i = 0; $i < $info["count"]; $i++) {
248 $dn = $info[$i]["dn"];
249 // The password is still plain text.
250 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
251 // ldap_bind will return TRUE if everything matches
253 $this->_authmethod = 'LDAP';
254 return WIKIAUTH_USER;
258 trigger_error("Unable to connect to LDAP server "
259 . LDAP_AUTH_HOST, E_USER_WARNING);
262 // imap authentication. added by limako
263 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
264 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}",
265 $userid, $passwd, OP_HALFOPEN );
268 $this->_authmethod = 'IMAP';
269 return WIKIAUTH_USER;
274 if ( ALLOW_BOGO_LOGIN
275 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
276 $this->_authmethod = 'BOGO';
277 return WIKIAUTH_BOGO;
282 // Todo: try our WikiDB backends.
283 function getPreferences() {
284 // Restore saved preferences.
286 // I'd rather prefer only to store the UserId in the cookie or
287 // session, and get the preferences from the db or page.
288 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
289 $prefs = $this->_request->getSessionVar('wiki_prefs');
291 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
292 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
295 // before we get his prefs we should check if he is signed in
296 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
297 if ($pref = $this->_homepage->get('pref')) {
298 //trigger_error("pref=".$pref);//debugging
299 $prefs = unserialize($pref);
302 return new UserPreferences($prefs);
305 // No cookies anymore for all prefs, only the userid. PHP creates
306 // a session cookie in memory, which is much more efficient.
308 // Return the number of changed entries?
309 function setPreferences($prefs, $id_only = false) {
311 $this->_request->setSessionVar('wiki_prefs', $prefs);
312 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
313 // simple unpacked cookie
314 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
316 // We must ensure that any password is encrypted.
317 // We don't need any plaintext password.
319 if ($this->isSignedIn()) {
320 if ($this->isAdmin())
321 $prefs->set('passwd', '');
322 // already stored in index.php, and it might be
323 // plaintext! well oh well
324 if ($homepage = $this->homePage()) {
325 $homepage->set('pref', serialize($prefs->_prefs));
326 return sizeof($prefs->_prefs);
328 trigger_error("No homepage for user found. Creating one...",
330 $this->createHomepage($prefs);
331 //$homepage->set('pref', serialize($prefs->_prefs));
332 return sizeof($prefs->_prefs);
335 trigger_error("you must be signed in", E_USER_WARNING);
341 // check for homepage with user flag.
342 // can be overriden from the auth backends
344 $homepage = $this->homePage();
345 return ($this->_userid && $homepage && $homepage->get('pref'));
348 // doesn't check for existance!!! hmm.
349 // how to store metadata in not existing pages? how about versions?
350 function homePage() {
353 if (!empty($this->_homepage)) {
354 return $this->_homepage;
356 $this->_homepage = $this->_dbi->getPage($this->_userid);
357 return $this->_homepage;
361 // create user by checking his homepage
362 function createUser ($pref, $createDefaultHomepage = true) {
365 if ($createDefaultHomepage) {
366 $this->createHomepage($pref);
369 include "lib/loadsave.php";
370 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
371 'versiondata' => array('author' => $this->_userid),
372 'pagename' => $this->_userid,
373 'content' => _('CategoryHomepage'));
374 SavePage ($this->_request, $pageinfo, false, false);
376 $this->setPreferences($pref);
379 // create user and default user homepage
380 function createHomepage ($pref) {
381 $pagename = $this->_userid;
382 include "lib/loadsave.php";
384 // create default homepage:
385 // properly expanded template and the pref metadata
386 $template = Template('homepage.tmpl', $this->_request);
387 $text = $template->getExpansion();
388 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
389 'versiondata' => array('author' => $this->_userid),
390 'pagename' => $pagename,
392 SavePage ($this->_request, $pageinfo, false, false);
395 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
396 if (! isWikiPage($pagename)) {
397 $pageinfo = array('pagedata' => array(),
398 'versiondata' => array('author' => $this->_userid),
399 'pagename' => $pagename,
400 'content' => "<?plugin Calender ?>\n");
401 SavePage ($this->_request, $pageinfo, false, false);
404 // create Preferences
405 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
406 if (! isWikiPage($pagename)) {
407 $pageinfo = array('pagedata' => array(),
408 'versiondata' => array('author' => $this->_userid),
409 'pagename' => $pagename,
410 'content' => "<?plugin UserPreferences ?>\n");
411 SavePage ($this->_request, $pageinfo, false, false);
415 function tryAuthBackends() {
416 return ''; // crypt('') will never be ''
419 // Auth backends must store the crypted password where?
420 // Not in the preferences.
421 function checkPassword($passwd) {
422 $prefs = $this->getPreferences();
423 $stored_passwd = $prefs->get('passwd'); // crypted
424 if (empty($prefs->_prefs['passwd'])) // not stored in the page
425 // allow empty passwords? At least store a '*' then.
426 // try other backend. hmm.
427 $stored_passwd = $this->tryAuthBackends($this->_userid);
428 if (empty($stored_passwd)) {
429 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
430 $this->_userid), E_USER_NOTICE);
431 $prefs->set('passwd','*');
434 if ($stored_passwd == '*')
437 && crypt($passwd, $stored_passwd) == $stored_passwd )
443 function changePassword($newpasswd, $passwd2 = false) {
444 if (! $this->mayChangePassword() ) {
445 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
446 $this->_userid), E_USER_ERROR);
449 if ($passwd2 && $passwd2 != $newpasswd) {
450 trigger_error("The second password must be the same as the first to change it",
454 $prefs = $this->getPreferences();
455 //$oldpasswd = $prefs->get('passwd');
456 $prefs->set('passwd', crypt($newpasswd));
457 $this->setPreferences($prefs);
460 function mayChangePassword() {
461 // on external DBAuth maybe. on IMAP or LDAP not
462 // on internal DBAuth yes
463 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
465 if ($this->isAdmin())
467 if ($this->_authmethod == 'pagedata')
469 if ($this->_authmethod == 'authdb')
474 // create user and default user homepage
475 // FIXME: delete this, not used?
477 function createUser ($userid, $pref) {
479 $user = new WikiUser ($request, $userid);
480 $user->createUser($pref);
484 class _UserPreference
486 function _UserPreference ($default_value) {
487 $this->default_value = $default_value;
490 function sanify ($value) {
491 return (string)$value;
494 function update ($value) {
498 class _UserPreference_numeric
499 extends _UserPreference
501 function _UserPreference_numeric ($default, $minval = false,
503 $this->_UserPreference((double)$default);
504 $this->_minval = (double)$minval;
505 $this->_maxval = (double)$maxval;
508 function sanify ($value) {
509 $value = (double)$value;
510 if ($this->_minval !== false && $value < $this->_minval)
511 $value = $this->_minval;
512 if ($this->_maxval !== false && $value > $this->_maxval)
513 $value = $this->_maxval;
518 class _UserPreference_int
519 extends _UserPreference_numeric
521 function _UserPreference_int ($default, $minval = false, $maxval = false) {
522 $this->_UserPreference_numeric((int)$default, (int)$minval,
526 function sanify ($value) {
527 return (int)parent::sanify((int)$value);
531 class _UserPreference_bool
532 extends _UserPreference
534 function _UserPreference_bool ($default = false) {
535 $this->_UserPreference((bool)$default);
538 function sanify ($value) {
539 if (is_array($value)) {
540 /* This allows for constructs like:
542 * <input type="hidden" name="pref[boolPref][]" value="0" />
543 * <input type="checkbox" name="pref[boolPref][]" value="1" />
545 * (If the checkbox is not checked, only the hidden input
546 * gets sent. If the checkbox is sent, both inputs get
549 foreach ($value as $val) {
555 return (bool) $value;
559 class _UserPreference_language
560 extends _UserPreference
562 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
563 $this->_UserPreference($default);
566 // FIXME: check for valid locale
567 function sanify ($value) {
568 // Revert to DEFAULT_LANGUAGE if user does not specify
569 // language in UserPreferences or chooses <system language>.
570 if ($value == '' or empty($value))
571 $value = DEFAULT_LANGUAGE;
573 return (string) $value;
577 class _UserPreference_theme
578 extends _UserPreference
580 function _UserPreference_theme ($default = THEME) {
581 $this->_UserPreference($default);
584 function sanify ($value) {
585 if (findFile($this->_themefile($value), true))
587 return $this->default_value;
590 function update ($newvalue) {
592 include_once($this->_themefile($newvalue));
594 include_once($this->_themefile(THEME));
597 function _themefile ($theme) {
598 return "themes/$theme/themeinfo.php";
602 // don't save default preferences for efficiency.
603 class UserPreferences {
604 function UserPreferences ($saved_prefs = false) {
605 $this->_prefs = array();
607 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
608 foreach ($saved_prefs->_prefs as $name => $value)
609 $this->set($name, $value);
610 } elseif (is_array($saved_prefs)) {
611 foreach ($saved_prefs as $name => $value)
612 $this->set($name, $value);
616 function _getPref ($name) {
617 global $UserPreferences;
618 if (!isset($UserPreferences[$name])) {
619 if ($name == 'passwd2') return false;
620 trigger_error("$name: unknown preference", E_USER_NOTICE);
623 return $UserPreferences[$name];
626 function get ($name) {
627 if (isset($this->_prefs[$name]))
628 return $this->_prefs[$name];
629 if (!($pref = $this->_getPref($name)))
631 return $pref->default_value;
634 function set ($name, $value) {
635 if (!($pref = $this->_getPref($name)))
638 $newvalue = $pref->sanify($value);
639 $oldvalue = $this->get($name);
642 if ($newvalue != $oldvalue)
643 $pref->update($newvalue);
645 // don't set default values to save space (in cookies, db and
647 if ($value == $pref->default_value)
648 unset($this->_prefs[$name]);
650 $this->_prefs[$name] = $newvalue;
654 return hash($this->_prefs);
658 // $Log: not supported by cvs2svn $
659 // Revision 1.42 2003/11/30 18:18:13 carstenklapp
660 // Minor code optimization: use include_once instead of require_once
661 // inside functions that might not always called.
663 // Revision 1.41 2003/11/21 21:32:39 carstenklapp
664 // Bugfix: When DEFAULT_LANGUAGE was not 'en', a user's language prefs
665 // would revert to 'en' when the default <system language> was selected
666 // in UserPreferences and the user saved his preferences. (Check for
667 // empty or blank language pref in sanify function of class
668 // _UserPreference_language and return DEFAULT_LANGUAGE if nothing or
669 // default selected in UserPreferences.)
671 // Revision 1.40 2003/11/21 16:54:58 carstenklapp
672 // Bugfix: login.tmpl was always displayed in English despite
673 // DEFAULT_LANGUAGE set in index.php. (Added call to
674 // update_locale(DEFAULT_LANGUAGE) before printing login form).
676 // Revision 1.39 2003/10/28 21:13:46 carstenklapp
677 // Security bug fix for admin password, submitted by Julien Charbon.
679 // Revision 1.38 2003/09/13 22:25:38 carstenklapp
680 // Hook for new user preference 'noLinkIcons'.
682 // Revision 1.37 2003/02/22 20:49:55 dairiki
683 // Fixes for "Call-time pass by reference has been deprecated" errors.
685 // Revision 1.36 2003/02/21 22:50:51 dairiki
686 // Ensure that language preference is a string.
688 // Revision 1.35 2003/02/16 20:04:47 dairiki
689 // Refactor the HTTP validator generation/checking code.
691 // This also fixes a number of bugs with yesterdays validator mods.
693 // Revision 1.34 2003/02/15 02:21:54 dairiki
694 // API Change! Explicit $request argument added to contructor for WikiUser.
696 // This seemed the best way to fix a problem whereby the WikiDB
697 // was being opened twice. (Which while being merely inefficient
698 // when using an SQL backend causes hangage when using a dba backend.)
700 // Revision 1.33 2003/01/22 03:21:40 zorloc
701 // Modified WikiUser constructor to move the DB request for the homepage to
702 // the end of the logic to prevent it from being requested and then dropped.
703 // Added more phpdoc comments.
705 // Revision 1.32 2003/01/21 07:40:50 zorloc
706 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
707 // false and to return true only in the desired condition. Added phpdoc
710 // Revision 1.31 2003/01/15 05:37:20 carstenklapp
713 // Revision 1.30 2003/01/15 04:59:27 carstenklapp
714 // Bugfix: Previously stored preferences were not loading when user
715 // signed in. (Fixed... I hope.)
722 // c-hanging-comment-ender-p: nil
723 // indent-tabs-mode: nil