2 rcs_id('$Id: WikiUser.php,v 1.33 2003-01-22 03:21:40 zorloc 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 ($userid = false, $authlevel = false) {
57 $this->_request = &$GLOBALS['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; // 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;
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 function createUser ($userid, $pref) {
471 $user = new WikiUser ($userid);
472 $user->createUser($pref);
475 class _UserPreference
477 function _UserPreference ($default_value) {
478 $this->default_value = $default_value;
481 function sanify ($value) {
482 return (string)$value;
485 function update ($value) {
489 class _UserPreference_numeric
490 extends _UserPreference
492 function _UserPreference_numeric ($default, $minval = false,
494 $this->_UserPreference((double)$default);
495 $this->_minval = (double)$minval;
496 $this->_maxval = (double)$maxval;
499 function sanify ($value) {
500 $value = (double)$value;
501 if ($this->_minval !== false && $value < $this->_minval)
502 $value = $this->_minval;
503 if ($this->_maxval !== false && $value > $this->_maxval)
504 $value = $this->_maxval;
509 class _UserPreference_int
510 extends _UserPreference_numeric
512 function _UserPreference_int ($default, $minval = false, $maxval = false) {
513 $this->_UserPreference_numeric((int)$default, (int)$minval,
517 function sanify ($value) {
518 return (int)parent::sanify((int)$value);
522 class _UserPreference_bool
523 extends _UserPreference
525 function _UserPreference_bool ($default = false) {
526 $this->_UserPreference((bool)$default);
529 function sanify ($value) {
530 if (is_array($value)) {
531 /* This allows for constructs like:
533 * <input type="hidden" name="pref[boolPref][]" value="0" />
534 * <input type="checkbox" name="pref[boolPref][]" value="1" />
536 * (If the checkbox is not checked, only the hidden input
537 * gets sent. If the checkbox is sent, both inputs get
540 foreach ($value as $val) {
546 return (bool) $value;
550 class _UserPreference_language
551 extends _UserPreference
553 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
554 $this->_UserPreference($default);
557 function sanify ($value) {
558 // FIXME: check for valid locale
563 class _UserPreference_theme
564 extends _UserPreference
566 function _UserPreference_theme ($default = THEME) {
567 $this->_UserPreference($default);
570 function sanify ($value) {
571 if (file_exists($this->_themefile($value)))
573 return $this->default_value;
576 function update ($newvalue) {
578 include_once($this->_themefile($newvalue));
580 include_once($this->_themefile(THEME));
583 function _themefile ($theme) {
584 return "themes/$theme/themeinfo.php";
588 // don't save default preferences for efficiency.
589 class UserPreferences {
590 function UserPreferences ($saved_prefs = false) {
591 $this->_prefs = array();
593 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
594 foreach ($saved_prefs->_prefs as $name => $value)
595 $this->set($name, $value);
596 } elseif (is_array($saved_prefs)) {
597 foreach ($saved_prefs as $name => $value)
598 $this->set($name, $value);
602 function _getPref ($name) {
603 global $UserPreferences;
604 if (!isset($UserPreferences[$name])) {
605 if ($name == 'passwd2') return false;
606 trigger_error("$name: unknown preference", E_USER_NOTICE);
609 return $UserPreferences[$name];
612 function get ($name) {
613 if (isset($this->_prefs[$name]))
614 return $this->_prefs[$name];
615 if (!($pref = $this->_getPref($name)))
617 return $pref->default_value;
620 function set ($name, $value) {
621 if (!($pref = $this->_getPref($name)))
624 $newvalue = $pref->sanify($value);
625 $oldvalue = $this->get($name);
628 if ($newvalue != $oldvalue)
629 $pref->update($newvalue);
631 // don't set default values to save space (in cookies, db and
633 if ($value == $pref->default_value)
634 unset($this->_prefs[$name]);
636 $this->_prefs[$name] = $newvalue;
640 // $Log: not supported by cvs2svn $
641 // Revision 1.32 2003/01/21 07:40:50 zorloc
642 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
643 // false and to return true only in the desired condition. Added phpdoc
646 // Revision 1.31 2003/01/15 05:37:20 carstenklapp
649 // Revision 1.30 2003/01/15 04:59:27 carstenklapp
650 // Bugfix: Previously stored preferences were not loading when user
651 // signed in. (Fixed... I hope.)
658 // c-hanging-comment-ender-p: nil
659 // indent-tabs-mode: nil